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>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lesson13.Gui
{
public partial class Form1 : Form
{
private Television _television;
public Form1()
{
InitializeComponent();
_television = new Television("127.0.0.1", 8080);
}
private void ExecuteCommand(AquosCommand command)
{
command.Television = _television;
command.Execute();
}
private void button1_Click(object sender, EventArgs e)
{
var value = Convert.ToInt32(textBox1.Text);
ExecuteCommand(AquosCommand.Volume(value));
}
private void button2_Click(object sender, EventArgs e)
{
ExecuteCommand(AquosCommand.Power(PowerSetting.On));
}
private void button3_Click(object sender, EventArgs e)
{
ExecuteCommand(AquosCommand.Power(PowerSetting.Off));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson09
{
public class Computer : CompositeComponent
{
public Computer()
: base("Computer", 0) { }
}
}
<file_sep>using Lesson08.Standard;
namespace Lesson08.ThirdParty
{
public abstract class ThirdPartyBuilder
{
protected readonly Computer ComputerObject = new Computer();
public abstract void InputCores(int amount);
public abstract void InputCpuClock(decimal frequency);
public abstract void InputRamConfiguration(int amount);
public abstract void InputDrive(string type);
public abstract Computer GetComputer();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lesson03.Core;
namespace Lesson03
{
class Program
{
static void Main(string[] args)
{
Console.Write("Client (a or b): ");
var client = Console.ReadLine();
IFactory factory;
if (client == "a")
{
factory = new ClientAFactory();
}
else if (client == "b")
{
factory = new ClientBFactory();
}
else
{
return;
}
var order = new Order();
Console.Write("How many computers? ");
order.Computers = ConvertToInt32(Console.ReadLine());
Console.Write("How many tablets? ");
order.Tablets = ConvertToInt32(Console.ReadLine());
Console.Write("How many phones? ");
order.SmartPhones = ConvertToInt32(Console.ReadLine());
var company = new HandyDandyManufacturingCompany(factory);
company.Produce(order);
Console.WriteLine("Created " + company.Computers.Count() + " computers.");
Console.WriteLine("Created " + company.Tablets.Count() + " tablets.");
Console.WriteLine("Created " + company.SmartPhones.Count() + " phones.");
Console.ReadLine();
}
private static int ConvertToInt32(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return 0;
}
return Int32.Parse(input);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lesson08.Standard;
using Lesson08.ThirdParty;
namespace Lesson08.Core
{
// adapter
public class MidRangeComputerBuilder : ComputerBuilder
{
private readonly CustomComputerBuilder _builder = new CustomComputerBuilder();
public override void SetCores()
{
_builder.InputCores(4);
}
public override void SetCpuFrequency()
{
_builder.InputCpuClock(2.5m);
}
public override void SetRam()
{
_builder.InputRamConfiguration(8);
}
public override void SetDriveType()
{
_builder.InputDrive("hdd");
}
public override Computer GetComputer()
{
return _builder.GetComputer();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson15
{
// subject
public interface IProduct
{
string Name { get; }
decimal Price { get; }
void Notify(decimal price);
void AddFollower(ICustomer customer);
void RemoveFollower(ICustomer customer);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson09
{
public class Ssd : Component
{
public Ssd(int price)
: base("Ssd", price) { }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Lesson02.Data
{
public interface IUserRepository
{
IEnumerable<User> All();
User GetBy(Expression<Func<User, bool>> expression);
int Delete(Expression<Func<User, bool>> expression);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson03.Core
{
public class ClientBFactory : IFactory
{
public IComputer CreateComputer()
{
return new ClientBComputer();
}
public ITablet CreateTablet()
{
return new ClientBTablet();
}
public ISmartPhone CreateSmartPhone()
{
return new ClientBSmartPhone();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson05.Core
{
public class HandyDandyComputerStore
{
public Computer Build(ComputerBuilder builder)
{
builder.SetCores();
builder.SetCpuFrequency();
builder.SetRam();
builder.SetDriveType();
return builder.GetComputer();
}
}
}
<file_sep>using Lesson08.Core;
using Lesson08.Standard;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lesson07.Tests
{
[TestClass]
public class BuilderTests
{
[TestMethod]
public void SuperComputerBuilderTest()
{
var computer = new Computer
{
AmountOfCores = 64,
AmountOfRam = 256,
CpuFrequency = 3.4m,
DriveType = "ssd"
};
var builder = new SuperComputerBuilder();
var superComputer = HandyDandyComputerStore.Instance.Build(builder);
Assert.AreEqual(superComputer.AmountOfCores, computer.AmountOfCores);
Assert.AreEqual(superComputer.AmountOfRam, computer.AmountOfRam);
Assert.AreEqual(superComputer.CpuFrequency, computer.CpuFrequency);
Assert.AreEqual(superComputer.DriveType, computer.DriveType);
}
[TestMethod]
public void NotSoSuperComputerBuilderTest()
{
var computer = new Computer
{
AmountOfCores = 1,
AmountOfRam = 2,
CpuFrequency = 2.0m,
DriveType = "hdd"
};
var builder = new NotSoSuperComputerBuilder();
var superComputer = HandyDandyComputerStore.Instance.Build(builder);
Assert.AreEqual(superComputer.AmountOfCores, computer.AmountOfCores);
Assert.AreEqual(superComputer.AmountOfRam, computer.AmountOfRam);
Assert.AreEqual(superComputer.CpuFrequency, computer.CpuFrequency);
Assert.AreEqual(superComputer.DriveType, computer.DriveType);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
namespace Lesson11.Core
{
public class CustomComputerBuilder : ComputerBuilder
{
public override void SetCores(int amount)
{
_computer.AmountOfCores = amount;
}
public override void SetCpuFrequency(decimal frequency)
{
_computer.CpuFrequency = frequency;
}
public override void SetRam(int amount)
{
_computer.AmountOfRam = amount;
}
public override void SetDriveType(string type)
{
_computer.DriveType = type;
}
}
}
<file_sep>namespace Lesson05.Core
{
public abstract class ComputerBuilder
{
protected readonly Computer _computer = new Computer();
public abstract void SetCores();
public abstract void SetCpuFrequency();
public abstract void SetRam();
public abstract void SetDriveType();
public virtual Computer GetComputer()
{
return _computer;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson15
{
// concrete subject
class Cpu : IProduct
{
private decimal _price;
private readonly List<ICustomer> _customers = new List<ICustomer>();
public Cpu(decimal price)
{
_price = price;
}
public string Name
{
get { return "CPU"; }
}
public decimal Price
{
get { return _price; }
set
{
Notify(value);
}
}
public void AddFollower(ICustomer customer)
{
_customers.Add(customer);
}
public void RemoveFollower(ICustomer customer)
{
_customers.Remove(customer);
}
public void Notify(decimal price)
{
_price = price;
foreach (var customer in _customers)
{
customer.Update(this);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson14
{
public class CustomClass : IEnumerable<string>
{
public string Foo { get; set; }
public string Bar { get; set; }
public string Boo { get; set; }
public IEnumerator<string> GetEnumerator()
{
yield return Foo;
yield return Bar;
yield return Boo;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson13
{
// concrete command
public class AquosCommand : ICommand
{
protected const int CommandMaxLength = 4;
protected const int ParamMaxLength = 4;
public string Command { get; private set; }
public string Parameter { get; private set; }
public Television Television { get; set; }
private AquosCommand(string command, string parameters = null, Television television = null)
{
if (string.IsNullOrEmpty(command))
{
throw new ArgumentNullException("command");
}
command = command.Trim();
if (command.Length > CommandMaxLength)
{
throw new ArgumentException("Command cannot be more than four characters");
}
if (string.IsNullOrEmpty(parameters))
{
parameters = string.Empty;
}
parameters = parameters.Trim();
if (parameters.Length > ParamMaxLength)
{
throw new ArgumentException("Command parameters cannot be more than four characters");
}
Command = command;
Parameter = parameters.PadRight(ParamMaxLength);
Television = television;
}
public static AquosCommand Volume(int value, Television television = null)
{
return new AquosCommand("VOLM", Convert.ToString(value), television);
}
public static AquosCommand Power(PowerSetting setting, Television television = null)
{
return new AquosCommand("POWR", Convert.ToString((int)setting), television);
}
public override string ToString()
{
return string.Format("{0}{1}", Command, Parameter);
}
public void Execute()
{
if (Television == null)
{
throw new NullReferenceException("Television cannot be null.");
}
Television.Send(ToString());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson15
{
// concrete Observer
public class Customer : ICustomer
{
public void Update(IProduct product)
{
Console.WriteLine("{0} is now at ${1}", product.Name, product.Price);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson15
{
// observer
public interface ICustomer
{
void Update(IProduct product);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson10
{
public class Ham : Decorator
{
public Ham(SandwichComponent componet)
: base(componet)
{
_name = "Ham";
_price = 2.00m;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Lesson12.Server
{
class Program
{
static void Main(string[] args)
{
var ip = IPAddress.Parse("127.0.0.1");
var listener = new TcpListener(ip, 8080);
while (true)
{
listener.Start();
Console.WriteLine("Waiting for Connection...");
using (var socket = listener.AcceptSocket())
{
Console.WriteLine("Client Connected.");
var data = new byte[15];
socket.Receive(data);
var input = Encoding.Default.GetString(data).TrimEnd('\0');
Console.WriteLine("Client requested: {0}", input);
var prices = new StoredComponentPrices();
var price = 0m;
switch (input)
{
case "cpu":
price = prices.CpuPrice;
break;
case "ram":
price = prices.RamPrice;
break;
case "ssd":
price = prices.SsdPrice;
break;
}
var responseValue = Convert.ToString(price);
var response = Encoding.Default.GetBytes(responseValue);
socket.Send(response);
Console.WriteLine("Response sent to Client: {0}", responseValue);
Console.WriteLine();
}
listener.Stop();
}
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lesson14
{
[TestClass]
public class IteratorTests
{
[TestMethod]
public void TestMethod1()
{
var names = new List<string>()
{
"Jeremy",
"Jeffrey",
"Jordan",
"Jennifer"
};
foreach (var name in names)
{
Assert.IsTrue(names.Contains(name));
}
var iteratorOfT = names.GetEnumerator();
while (iteratorOfT.MoveNext())
{
var name = iteratorOfT.Current;
Assert.IsTrue(names.Contains(name));
}
var iterator = (IEnumerator) names.GetEnumerator();
while (iterator.MoveNext())
{
var name = (string)iterator.Current;
Assert.IsTrue(names.Contains(name));
}
}
[TestMethod]
public void CustomClassIterator()
{
var obj = new CustomClass
{
Foo = "foo",
Bar = "bar",
Boo = "boo"
};
var iterator = obj.GetEnumerator();
iterator.MoveNext();
Assert.AreEqual(obj.Foo, iterator.Current);
iterator.MoveNext();
Assert.AreEqual(obj.Bar, iterator.Current);
iterator.MoveNext();
Assert.AreEqual(obj.Boo, iterator.Current);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson03.Core
{
public class ClientAFactory : IFactory
{
public IComputer CreateComputer()
{
return new ClientAComputer();
}
public ITablet CreateTablet()
{
return new ClientATablet();
}
public ISmartPhone CreateSmartPhone()
{
return new ClientASmartPhone();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson11.Core
{
public class HandyDandyComputerStore
{
public Computer Build(Order order, ComputerBuilder builder)
{
builder.SetCores(order.AmountOfCores);
builder.SetCpuFrequency(order.CpuFrequency);
builder.SetRam(order.AmountOfRam);
builder.SetDriveType(order.DriveType);
Console.WriteLine("Built Computer.");
return builder.GetComputer();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lesson12.Core;
namespace Lesson12.Server
{
// real subject
internal class StoredComponentPrices : IComponentPrice
{
public decimal CpuPrice
{
get { return 250m; }
}
public decimal RamPrice
{
get { return 32m; }
}
public decimal SsdPrice
{
get { return 225m; }
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lesson10.Tests
{
[TestClass]
public class DecoratorTests
{
[TestMethod]
public void UntitledTest()
{
var sandwich = new BaseSandwich();
Assert.AreEqual(sandwich.Price, 1.00m);
var wheatBreadSandwich = new WheatBread(sandwich);
Assert.AreEqual(wheatBreadSandwich.Price, 2.00m);
var hamSandwich = new Ham(wheatBreadSandwich);
Assert.AreEqual(hamSandwich.Price, 4.00m);
var baconHam = new Bacon(new Bacon(hamSandwich));
Assert.IsTrue(baconHam.InnerComponent is Bacon);
Assert.AreEqual(baconHam.Price, 5.00m);
var discountedBaconHam = new BaconDiscount(new BaconDiscount(baconHam));
Assert.AreEqual(discountedBaconHam.Price, 4.00m);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson10
{
public abstract class SandwichComponent
{
public abstract string Name { get; }
public abstract decimal Price { get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Lesson12.Client
{
class Program
{
static void Main(string[] args)
{
var prices = new ComponentPriceProxy();
Console.WriteLine("CPU Price: {0}", prices.CpuPrice);
Thread.Sleep(500);
Console.WriteLine("RAM Price: {0}", prices.RamPrice);
Thread.Sleep(500);
Console.WriteLine("SSD Price: {0}", prices.SsdPrice);
// subject
// realsubject
// proxy
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson03.Core
{
public class HandyDandyManufacturingCompany
{
private readonly IFactory _factory;
private readonly List<IComputer> _computers;
private readonly List<ITablet> _tablets;
private readonly List<ISmartPhone> _phones;
public IEnumerable<IComputer> Computers { get { return _computers.ToArray(); } }
public IEnumerable<ITablet> Tablets { get { return _tablets.ToArray(); } }
public IEnumerable<ISmartPhone> SmartPhones { get { return _phones.ToArray(); } }
public HandyDandyManufacturingCompany(IFactory factory)
{
_factory = factory;
_computers = new List<IComputer>();
_tablets = new List<ITablet>();
_phones = new List<ISmartPhone>();
}
public void Produce(Order order)
{
CreateComputers(order.Computers);
CreateTablets(order.Tablets);
CreateSmartPhones(order.SmartPhones);
}
private void CreateComputers(int count)
{
while (_computers.Count < count)
{
_computers.Add(_factory.CreateComputer());
}
}
private void CreateTablets(int count)
{
while (_tablets.Count < count)
{
_tablets.Add(_factory.CreateTablet());
}
}
private void CreateSmartPhones(int count)
{
while (_phones.Count < count)
{
_phones.Add(_factory.CreateSmartPhone());
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson10
{
public abstract class Decorator : SandwichComponent
{
protected SandwichComponent _component;
protected string _name = "";
protected decimal _price = 0m;
protected Decorator(SandwichComponent component)
{
_component = component;
}
public override string Name
{
get { return string.Format("{0}, {1}", _component.Name, _name); }
}
public override decimal Price
{
get { return _component.Price + _price; }
}
public virtual SandwichComponent InnerComponent
{
get { return _component; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson15
{
class Program
{
static void Main(string[] args)
{
var cpu = new Cpu(150m);
var ram = new Ram(50m);
var cust1 = new Customer();
var cust2 = new Customer();
cpu.AddFollower(cust1);
ram.AddFollower(cust2);
cpu.Price = 100m;
ram.Price = 25m;
Console.Read();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson13.Gui
{
public enum PowerSetting
{
Off,
On
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson09
{
public abstract class Component
{
protected readonly string _name;
protected readonly int _price;
protected Component(string name, int price)
{
_name = name;
_price = price;
}
public virtual void Add(Component component)
{
throw new Exception("Component cannot be added to this component.");
}
public virtual string Name
{
get { return _name; }
}
public virtual int Price
{
get { return _price; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lesson11.Core;
namespace Lesson11
{
class Program
{
static void Main(string[] args)
{
Console.Write("Payment Method: ");
var method = Console.ReadLine();
Computer computer;
var order = new Order
{
AmountOfCores = 4,
AmountOfRam = 32,
CpuFrequency = 3.0m,
DriveType = "ssd"
};
var processingService = new OrderProcessingService();
if (method.ToLower() == "cash")
{
computer = processingService.MakeCashPurchase(order, 1500m);
}
else
{
computer = processingService.MakeCreditPurchase(order);
}
GiveComputerToCustomer(computer);
Console.Read();
}
public static void GiveComputerToCustomer(Computer computer)
{
Console.WriteLine("Gave computer to customer.");
}
}
}
<file_sep>using Lesson08.Standard;
namespace Lesson08.ThirdParty
{
// adaptee
public class CustomComputerBuilder : ThirdPartyBuilder
{
public override void InputCores(int amount)
{
ComputerObject.AmountOfCores = amount;
}
public override void InputCpuClock(decimal frequency)
{
ComputerObject.CpuFrequency = frequency;
}
public override void InputRamConfiguration(int amount)
{
ComputerObject.AmountOfRam = amount;
}
public override void InputDrive(string type)
{
ComputerObject.DriveType = type;
}
public override Computer GetComputer()
{
return ComputerObject;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson07
{
public class Computer
{
public decimal CpuFrequency { get; set; }
public int AmountOfCores { get; set; }
public string DriveType { get; set; }
public int AmountOfRam { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson15
{
class Ram : IProduct
{
private decimal _price;
private delegate void PriceUpdate(IProduct product);
private event PriceUpdate OnPriceUpdate;
public Ram(decimal price)
{
_price = price;
}
public string Name
{
get { return "RAM"; }
}
public decimal Price
{
get { return _price; }
set
{
Notify(value);
}
}
public void Notify(decimal price)
{
_price = price;
if (OnPriceUpdate != null)
{
OnPriceUpdate(this);
}
}
public void AddFollower(ICustomer customer)
{
OnPriceUpdate += customer.Update;
}
public void RemoveFollower(ICustomer customer)
{
OnPriceUpdate -= customer.Update;
}
}
}
<file_sep>using System;
using Lesson08.Core;
using Lesson08.Standard;
using Lesson08.ThirdParty;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lesson08.Tests
{
[TestClass]
public class ThirdPartyBuilderTests
{
[TestMethod]
public void CustomComputerBuilderTest()
{
var computer = new Computer
{
AmountOfCores = 4,
AmountOfRam = 8,
CpuFrequency = 2.5m,
DriveType = "hdd"
};
var builder = new MidRangeComputerBuilder();
var superComputer = HandyDandyComputerStore.Instance.Build(builder);
Assert.AreEqual(superComputer.AmountOfCores, computer.AmountOfCores);
Assert.AreEqual(superComputer.AmountOfRam, computer.AmountOfRam);
Assert.AreEqual(superComputer.CpuFrequency, computer.CpuFrequency);
Assert.AreEqual(superComputer.DriveType, computer.DriveType);
}
}
}
<file_sep>namespace Lesson11.Core
{
public abstract class ComputerBuilder
{
protected readonly Computer _computer = new Computer();
public abstract void SetCores(int amount);
public abstract void SetCpuFrequency(decimal frequency);
public abstract void SetRam(int amount);
public abstract void SetDriveType(string type);
public virtual Computer GetComputer()
{
return _computer;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson03.Core
{
public class Order
{
public int Computers { get; set; }
public int Tablets { get; set; }
public int SmartPhones { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Lesson02.Data;
using Lesson02.Data.SqlServer;
using System.IO;
namespace Lesson02
{
public class HandyDandyApplication
{
private IUserRepository _users;
public HandyDandyApplication(IUserRepository repository = null)
{
_users = repository ?? new UserRepository();
}
public void DisplayUsers(TextWriter writer)
{
foreach (var user in _users.All())
{
var userData = string.Format("{0}\t{1} {2}",
user.Id,
user.FirstName,
user.LastName);
writer.WriteLineAsync(userData);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson10
{
public class BaseSandwich : SandwichComponent
{
private string _name = "Basic Sandwich";
private decimal _price = 1.00m;
public override string Name
{
get { return _name; }
}
public override decimal Price
{
get { return _price; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson08.Core
{
public class SuperComputerBuilder : ComputerBuilder
{
public override void SetCores()
{
_computer.AmountOfCores = 64;
}
public override void SetCpuFrequency()
{
_computer.CpuFrequency = 3.4m;
}
public override void SetRam()
{
_computer.AmountOfRam = 256;
}
public override void SetDriveType()
{
_computer.DriveType = "ssd";
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.IO;
using Lesson02;
using Lesson02.Data.Test;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lesson02Tests
{
[TestClass]
public class ApplicationTests
{
[TestMethod]
public void DisplayFullList()
{
var testRepo = new TestUserRepository();
var app = new HandyDandyApplication(testRepo);
var data = string.Empty;
using (var writer = new StringWriter())
{
app.DisplayUsers(writer);
data = writer.ToString();
}
var lines = data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
Assert.IsTrue(lines.Length == 4);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson07
{
public class NotSoSuperComputerBuilder : ComputerBuilder
{
public override void SetCores()
{
_computer.AmountOfCores = 1;
}
public override void SetCpuFrequency()
{
_computer.CpuFrequency = 2.0m;
}
public override void SetRam()
{
_computer.AmountOfRam = 2;
}
public override void SetDriveType()
{
_computer.DriveType = "hdd";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson13
{
class Program
{
static void Main(string[] args)
{
var tv = new Television("127.0.0.1", 8080);
var volume = AquosCommand.Volume(15, tv);
volume.Execute();
Console.Read();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson11.Core
{
public class CreditProcessingService
{
public bool HasCreditAvailable(decimal purchasAmount)
{
Console.WriteLine("Checked if customer as available credit.");
return true; // we'll be generous!
}
public bool MakePurchase(decimal purchaseAmount)
{
Console.WriteLine("Credit processing successful.");
return true; // processing process always returns true; we have no issues!
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson10
{
public class Bacon : Decorator
{
public Bacon(SandwichComponent component)
: base(component)
{
_name = "Bacon";
_price = .50m;
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lesson04.Tests
{
[TestClass]
public class CommandTests
{
[TestMethod]
public void VolumeTest()
{
var volume2 = AquosCommand.Volume(30);
}
[TestMethod]
public void PowerTest()
{
var power2 = AquosCommand.Power(PowerSetting.Off);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson12.Core
{
// subject
public interface IComponentPrice
{
decimal CpuPrice { get; }
decimal RamPrice { get; }
decimal SsdPrice { get; }
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lesson07.Tests
{
[TestClass]
public class SingletonTests
{
[TestMethod]
public void IsHandyDandyComputerStoreASingleton()
{
Assert.AreSame(HandyDandyComputerStore.Instance,
HandyDandyComputerStore.Instance);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Lesson13.Gui
{
// receiver
public class Television
{
private readonly IPAddress _ipAddress;
private readonly int _port;
public Television(string ipAddress, int port)
: this(IPAddress.Parse(ipAddress), port) { }
public Television(IPAddress ipAddress, int port)
{
_ipAddress = ipAddress;
_port = port;
}
public void Send(string command)
{
using (var client = new TcpClient())
{
client.Connect(_ipAddress, _port);
var stream = client.GetStream();
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
writer.WriteLine(command);
client.Close();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson07
{
public class HandyDandyComputerStore
{
private static readonly HandyDandyComputerStore _instance = new HandyDandyComputerStore();
public static HandyDandyComputerStore Instance
{
get { return _instance; }
}
private HandyDandyComputerStore()
{
// initialize
}
public Computer Build(ComputerBuilder builder)
{
builder.SetCores();
builder.SetCpuFrequency();
builder.SetRam();
builder.SetDriveType();
return builder.GetComputer();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson09
{
public abstract class CompositeComponent : Component
{
protected readonly List<Component> _components = new List<Component>();
protected CompositeComponent(string name, int price)
: base(name, price) { }
public override void Add(Component component)
{
if (component is Computer)
{
throw new Exception("Computer can only be top most object.");
}
_components.Add(component);
}
public override int Price
{
get
{
var total = _price;
foreach (var component in _components)
{
total += component.Price;
}
return total;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Lesson12.Core;
namespace Lesson12.Client
{
public class ComponentPriceProxy : IComponentPrice
{
public decimal CpuPrice
{
get { return MakeRequest("cpu"); }
}
public decimal RamPrice
{
get { return MakeRequest("ram"); }
}
public decimal SsdPrice
{
get { return MakeRequest("ssd"); }
}
private decimal MakeRequest(string component)
{
using (var client = new TcpClient())
{
client.Connect("127.0.0.1", 8080);
var stream = client.GetStream();
var data = Encoding.Default.GetBytes(component);
stream.Write(data, 0, data.Length);
var rawResponse = new byte[15];
stream.Read(rawResponse, 0, rawResponse.Length);
var response = Encoding.Default.GetString(rawResponse);
return Convert.ToDecimal(response);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson10
{
public class WheatBread : Decorator
{
public WheatBread(SandwichComponent component)
: base(component)
{
_name = "<NAME>";
_price = 1.00m;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Lesson02.Data.Test
{
public class TestUserRepository : IUserRepository
{
private readonly List<User> _store;
public TestUserRepository()
{
_store = new List<User>(new[] {
new User { Id = 1, FirstName = "John", LastName = "Doe"},
new User { Id = 2, FirstName = "James", LastName = "Doe"},
new User { Id = 3, FirstName = "Jane", LastName = "Doe"},
new User { Id = 4, FirstName = "Jennifer", LastName = "Doe"}
});
}
public IEnumerable<User> All()
{
return _store.ToArray();
}
public User GetBy(Expression<Func<User, bool>> expression)
{
return _store.SingleOrDefault(expression.Compile());
}
public int Delete(Expression<Func<User, bool>> expression)
{
var predicate = new Predicate<User>(expression.Compile());
return _store.RemoveAll(predicate);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson11.Core
{
public class OrderProcessingService
{
private readonly CustomComputerBuilder computerBuilder = new CustomComputerBuilder();
private readonly HandyDandyComputerStore store = new HandyDandyComputerStore();
private readonly HandyDandyComputerFactory factory = new HandyDandyComputerFactory();
public Computer MakeCashPurchase(Order order, decimal amount)
{
var register = new CashRegisterService();
register.OpenDrawer();
var change = register.MakeChange(order.Price, amount);
var computer = store.Build(order, computerBuilder);
factory.PlaceOrder(order);
return computer;
}
public Computer MakeCreditPurchase(Order order)
{
var credit = new CreditProcessingService();
if (!credit.HasCreditAvailable(order.Price))
{
throw new Exception("Customer does not have avaiable credit.");
}
credit.MakePurchase(order.Price);
var computer = store.Build(order, computerBuilder);
factory.PlaceOrder(order);
return computer;
}
}
}
<file_sep>### Design Patterns in CSharp
There are 23 design patterns also known as Gang of Four design patterns (GoF). Gang of Four are the authors of the book, “Design Patterns: Elements of Reusable Object Oriented Software”. These 23 patterns are grouped into three main categories based on their:
1. Creational Design Pattern
* Factory Method
* Abstract Factory
* Builder
* Prototype
* Singleton
2. Structural Design Patterns
* Adapter
* Bridge
* Composite
* Decorator
* Facade
* Flyweight
* Proxy
3. Behavioral Design Patterns
* Chain of Responsibility
* Command
* Interpreter
* Iterator
* Mediator
* Memento
* Observer
* State
* Strategy
* Visitor
* Template Method
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson11.Core
{
public class CashRegisterService
{
public void OpenDrawer()
{
// super technical stuff to open drawer.
Console.WriteLine("Opened Cash Drawer.");
}
public decimal MakeChange(decimal purchaseAmount, decimal givenAmount)
{
var amt = givenAmount - purchaseAmount;
Console.WriteLine(string.Format("Amount Owed Customer: ${0}", amt));
return amt;
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lesson09.Tests
{
[TestClass]
public class CompositeTests
{
[TestMethod]
public void TestMethod1()
{
var computer = new Computer(); // composite
var motherboard = new Motherboard(125); // composite
var cpu = new Cpu(250); // leaf
var ram = new Ram(160); // leaf
var drive = new Ssd(250); // leaf
motherboard.Add(cpu);
motherboard.Add(ram);
computer.Add(motherboard);
computer.Add(drive);
Assert.AreEqual(computer.Price, 785);
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lesson06.Tests
{
[TestClass]
public class PrototypeTests
{
[TestMethod]
public void MemberwiseCloneTest()
{
var gpu = new GraphicsCard
{
AmountOfRam = 4,
GpuFrequency = 1.1m
};
var computer = new Computer
{
AmountOfCores = 4,
AmountOfRam = 32,
CpuFrequency = 3.4m,
DriveType = "ssd",
Gpu = gpu
};
var computer2 = (Computer)computer.Clone();
Assert.AreNotSame(computer2, computer);
Assert.AreNotSame(computer2.AmountOfCores, computer.AmountOfCores);
Assert.AreNotSame(computer2.AmountOfRam, computer.AmountOfRam);
Assert.AreNotSame(computer2.CpuFrequency, computer.CpuFrequency);
Assert.AreSame(computer2.DriveType, computer.DriveType);
Assert.AreEqual(computer2.Gpu.AmountOfRam, computer.Gpu.AmountOfRam);
Assert.AreEqual(computer2.Gpu.GpuFrequency, computer.Gpu.GpuFrequency);
computer.Gpu.AmountOfRam = 8;
Assert.AreNotEqual(computer2.Gpu.AmountOfRam, computer.Gpu.AmountOfRam);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson11.Core
{
public class HandyDandyComputerFactory
{
public void PlaceOrder(Order order)
{
Console.WriteLine("Ordered parts for inventory.");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Lesson13.TelevisionApp
{
internal class Program
{
private static void Main(string[] args)
{
var ip = IPAddress.Parse("127.0.0.1");
var listener = new TcpListener(ip, 8080);
while (true)
{
listener.Start();
Console.WriteLine("Waiting for Connection...");
using (var socket = listener.AcceptSocket())
{
Console.WriteLine("Client Connected.");
var data = new byte[8];
socket.Receive(data);
var input = Encoding.Default.GetString(data).TrimEnd('\0');
Console.WriteLine("Client requested: {0}", input);
var response = Encoding.Default.GetBytes("OK");
socket.Send(response);
Console.WriteLine("Response sent to Client: {0}", "OK");
Console.WriteLine();
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson06
{
public class Computer : ICloneable
{
public int AmountOfCores { get; set; }
public decimal CpuFrequency { get; set; }
public int AmountOfRam { get; set; }
public string DriveType { get; set; }
public GraphicsCard Gpu { get; set; }
public object Clone()
{
var clone = (Computer) MemberwiseClone();
clone.Gpu = (GraphicsCard)Gpu.Clone();
//clone.Gpu = new GraphicsCard
//{
// AmountOfRam = Gpu.AmountOfRam,
// GpuFrequency = Gpu.GpuFrequency
//};
return clone;
}
}
}
| 763217ef824e1af968848af00b65ef6774780cce | [
"Markdown",
"C#"
] | 64 | C# | sideez/DesignPatternsCSharp | a4bf8fda482dc20c1d31ed47daee2136dbc73028 | b4c1380112e92242f38b833330c3225095f117ee |
refs/heads/master | <file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
#include <locale.h>
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_org_lwjgl_system_libc_Locale_LC_1ALL(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jint)LC_ALL;
}
JNIEXPORT jint JNICALL Java_org_lwjgl_system_libc_Locale_LC_1COLLATE(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jint)LC_COLLATE;
}
JNIEXPORT jint JNICALL Java_org_lwjgl_system_libc_Locale_LC_1CTYPE(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jint)LC_CTYPE;
}
JNIEXPORT jint JNICALL Java_org_lwjgl_system_libc_Locale_LC_1MONETARY(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jint)LC_MONETARY;
}
JNIEXPORT jint JNICALL Java_org_lwjgl_system_libc_Locale_LC_1NUMERIC(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jint)LC_NUMERIC;
}
JNIEXPORT jint JNICALL Java_org_lwjgl_system_libc_Locale_LC_1TIME(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jint)LC_TIME;
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_libc_Locale_nsetlocale(JNIEnv *__env, jclass clazz, jint category, jlong localeAddress) {
const char *locale = (const char *)(intptr_t)localeAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)setlocale(category, locale);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import org.lwjgl.system.*;
import static org.lwjgl.system.dyncall.DynCallback.*;
/** Allocates memory. */
@FunctionalInterface
public interface BGFXReallocCallbackI extends CallbackI.P {
String SIGNATURE = "(pppppi)p";
@Override
default String getSignature() { return SIGNATURE; }
@Override
default long callback(long args) {
return invoke(
dcbArgPointer(args),
dcbArgPointer(args),
dcbArgPointer(args),
dcbArgPointer(args),
dcbArgPointer(args),
dcbArgInt(args)
);
}
/**
* Will be called when an allocation is requested.
*
* @param _this the allocator interface
* @param _ptr the previously allocated memory or {@code NULL}
* @param _size the number of bytes to allocate
* @param _align the allocation alignment, in bytes
* @param _file file path where allocation was generated
* @param _line line where allocation was generated
*/
long invoke(long _this, long _ptr, long _size, long _align, long _file, int _line);
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4710))
#endif
#include "common_tools.h"
DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4711 4738))
#endif
#include "OVR_CAPIShim.c"
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1Initialize(JNIEnv *__env, jclass clazz, jlong paramsAddress) {
const ovrInitParams *params = (const ovrInitParams *)(intptr_t)paramsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_Initialize(params);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_ovr_1Shutdown(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
ovr_Shutdown();
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetLastErrorInfo(JNIEnv *__env, jclass clazz, jlong errorInfoAddress) {
ovrErrorInfo *errorInfo = (ovrErrorInfo *)(intptr_t)errorInfoAddress;
UNUSED_PARAMS(__env, clazz)
ovr_GetLastErrorInfo(errorInfo);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetVersionString(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)ovr_GetVersionString();
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_ovr_OVR_novr_1TraceMessage(JNIEnv *__env, jclass clazz, jint level, jlong messageAddress) {
const char *message = (const char *)(intptr_t)messageAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)ovr_TraceMessage(level, message);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1IdentifyClient(JNIEnv *__env, jclass clazz, jlong identityAddress) {
const char *identity = (const char *)(intptr_t)identityAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_IdentifyClient(identity);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetHmdDesc(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong __result) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
*((ovrHmdDesc*)(intptr_t)__result) = ovr_GetHmdDesc(session);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTrackerCount(JNIEnv *__env, jclass clazz, jlong sessionAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetTrackerCount(session);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTrackerDesc(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint trackerDescIndex, jlong __result) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
*((ovrTrackerDesc*)(intptr_t)__result) = ovr_GetTrackerDesc(session, trackerDescIndex);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1Create(JNIEnv *__env, jclass clazz, jlong pSessionAddress, jlong luidAddress) {
ovrSession *pSession = (ovrSession *)(intptr_t)pSessionAddress;
ovrGraphicsLuid *luid = (ovrGraphicsLuid *)(intptr_t)luidAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_Create(pSession, luid);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1Destroy(JNIEnv *__env, jclass clazz, jlong sessionAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
ovr_Destroy(session);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetSessionStatus(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong sessionStatusAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrSessionStatus *sessionStatus = (ovrSessionStatus *)(intptr_t)sessionStatusAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetSessionStatus(session, sessionStatus);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1SetTrackingOriginType(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint origin) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_SetTrackingOriginType(session, origin);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTrackingOriginType(JNIEnv *__env, jclass clazz, jlong sessionAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetTrackingOriginType(session);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1RecenterTrackingOrigin(JNIEnv *__env, jclass clazz, jlong sessionAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_RecenterTrackingOrigin(session);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1ClearShouldRecenterFlag(JNIEnv *__env, jclass clazz, jlong sessionAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
ovr_ClearShouldRecenterFlag(session);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTrackingState(JNIEnv *__env, jclass clazz, jlong sessionAddress, jdouble absTime, jboolean latencyMarker, jlong __result) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
*((ovrTrackingState*)(intptr_t)__result) = ovr_GetTrackingState(session, absTime, latencyMarker);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTrackerPose(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint trackerPoseIndex, jlong __result) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
*((ovrTrackerPose*)(intptr_t)__result) = ovr_GetTrackerPose(session, trackerPoseIndex);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetInputState(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint controllerType, jlong inputStateAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrInputState *inputState = (ovrInputState *)(intptr_t)inputStateAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetInputState(session, controllerType, inputState);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetConnectedControllerTypes(JNIEnv *__env, jclass clazz, jlong sessionAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetConnectedControllerTypes(session);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTouchHapticsDesc(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint controllerType, jlong __result) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
*((ovrTouchHapticsDesc*)(intptr_t)__result) = ovr_GetTouchHapticsDesc(session, controllerType);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1SetControllerVibration(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint controllerType, jfloat frequency, jfloat amplitude) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_SetControllerVibration(session, controllerType, frequency, amplitude);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1SubmitControllerVibration(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint controllerType, jlong bufferAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const ovrHapticsBuffer *buffer = (const ovrHapticsBuffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_SubmitControllerVibration(session, controllerType, buffer);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetControllerVibrationState(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint controllerType, jlong outStateAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrHapticsPlaybackState *outState = (ovrHapticsPlaybackState *)(intptr_t)outStateAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetControllerVibrationState(session, controllerType, outState);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1TestBoundary(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint deviceBitmask, jint boundaryType, jlong outTestResultAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrBoundaryTestResult *outTestResult = (ovrBoundaryTestResult *)(intptr_t)outTestResultAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_TestBoundary(session, deviceBitmask, boundaryType, outTestResult);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1TestBoundaryPoint(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong pointAddress, jint singleBoundaryType, jlong outTestResultAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const ovrVector3f *point = (const ovrVector3f *)(intptr_t)pointAddress;
ovrBoundaryTestResult *outTestResult = (ovrBoundaryTestResult *)(intptr_t)outTestResultAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_TestBoundaryPoint(session, point, singleBoundaryType, outTestResult);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1SetBoundaryLookAndFeel(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong lookAndFeelAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const ovrBoundaryLookAndFeel *lookAndFeel = (const ovrBoundaryLookAndFeel *)(intptr_t)lookAndFeelAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_SetBoundaryLookAndFeel(session, lookAndFeel);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1ResetBoundaryLookAndFeel(JNIEnv *__env, jclass clazz, jlong sessionAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_ResetBoundaryLookAndFeel(session);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetBoundaryGeometry__JIJJ(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint boundaryType, jlong outFloorPointsAddress, jlong outFloorPointsCountAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrVector3f *outFloorPoints = (ovrVector3f *)(intptr_t)outFloorPointsAddress;
int *outFloorPointsCount = (int *)(intptr_t)outFloorPointsCountAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetBoundaryGeometry(session, boundaryType, outFloorPoints, outFloorPointsCount);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetBoundaryDimensions(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint boundaryType, jlong outDimensionsAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrVector3f *outDimensions = (ovrVector3f *)(intptr_t)outDimensionsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetBoundaryDimensions(session, boundaryType, outDimensions);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetBoundaryVisible(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong outIsVisibleAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrBool *outIsVisible = (ovrBool *)(intptr_t)outIsVisibleAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetBoundaryVisible(session, outIsVisible);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1RequestBoundaryVisible(JNIEnv *__env, jclass clazz, jlong sessionAddress, jboolean visible) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_RequestBoundaryVisible(session, visible);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTextureSwapChainLength__JJJ(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong chainAddress, jlong out_LengthAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
int *out_Length = (int *)(intptr_t)out_LengthAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetTextureSwapChainLength(session, chain, out_Length);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTextureSwapChainCurrentIndex__JJJ(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong chainAddress, jlong out_IndexAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
int *out_Index = (int *)(intptr_t)out_IndexAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetTextureSwapChainCurrentIndex(session, chain, out_Index);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTextureSwapChainDesc(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong chainAddress, jlong out_DescAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
ovrTextureSwapChainDesc *out_Desc = (ovrTextureSwapChainDesc *)(intptr_t)out_DescAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetTextureSwapChainDesc(session, chain, out_Desc);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1CommitTextureSwapChain(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong chainAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_CommitTextureSwapChain(session, chain);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1DestroyTextureSwapChain(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong chainAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
UNUSED_PARAMS(__env, clazz)
ovr_DestroyTextureSwapChain(session, chain);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1DestroyMirrorTexture(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong mirrorTextureAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrMirrorTexture mirrorTexture = (ovrMirrorTexture)(intptr_t)mirrorTextureAddress;
UNUSED_PARAMS(__env, clazz)
ovr_DestroyMirrorTexture(session, mirrorTexture);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetFovTextureSize(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint eye, jlong fovAddress, jfloat pixelsPerDisplayPixel, jlong __result) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrFovPort *fov = (ovrFovPort *)(intptr_t)fovAddress;
UNUSED_PARAMS(__env, clazz)
*((ovrSizei*)(intptr_t)__result) = ovr_GetFovTextureSize(session, eye, *fov, pixelsPerDisplayPixel);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetRenderDesc(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint eyeType, jlong fovAddress, jlong __result) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrFovPort *fov = (ovrFovPort *)(intptr_t)fovAddress;
UNUSED_PARAMS(__env, clazz)
*((ovrEyeRenderDesc*)(intptr_t)__result) = ovr_GetRenderDesc(session, eyeType, *fov);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1SubmitFrame(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong frameIndex, jlong viewScaleDescAddress, jlong layerPtrListAddress, jint layerCount) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const ovrViewScaleDesc *viewScaleDesc = (const ovrViewScaleDesc *)(intptr_t)viewScaleDescAddress;
const ovrLayerHeader * const *layerPtrList = (const ovrLayerHeader * const *)(intptr_t)layerPtrListAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_SubmitFrame(session, frameIndex, viewScaleDesc, layerPtrList, layerCount);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetPerfStats(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong outStatsAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrPerfStats *outStats = (ovrPerfStats *)(intptr_t)outStatsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetPerfStats(session, outStats);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1ResetPerfStats(JNIEnv *__env, jclass clazz, jlong sessionAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_ResetPerfStats(session);
}
JNIEXPORT jdouble JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetPredictedDisplayTime(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong frameIndex) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
UNUSED_PARAMS(__env, clazz)
return (jdouble)ovr_GetPredictedDisplayTime(session, frameIndex);
}
JNIEXPORT jdouble JNICALL Java_org_lwjgl_ovr_OVR_ovr_1GetTimeInSeconds(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jdouble)ovr_GetTimeInSeconds();
}
JNIEXPORT jboolean JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetBool(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jboolean defaultVal) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
UNUSED_PARAMS(__env, clazz)
return (jboolean)ovr_GetBool(session, propertyName, defaultVal);
}
JNIEXPORT jboolean JNICALL Java_org_lwjgl_ovr_OVR_novr_1SetBool(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jboolean value) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
UNUSED_PARAMS(__env, clazz)
return (jboolean)ovr_SetBool(session, propertyName, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetInt(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jint defaultVal) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetInt(session, propertyName, defaultVal);
}
JNIEXPORT jboolean JNICALL Java_org_lwjgl_ovr_OVR_novr_1SetInt(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jint value) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
UNUSED_PARAMS(__env, clazz)
return (jboolean)ovr_SetInt(session, propertyName, value);
}
JNIEXPORT jfloat JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetFloat(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jfloat defaultVal) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
UNUSED_PARAMS(__env, clazz)
return (jfloat)ovr_GetFloat(session, propertyName, defaultVal);
}
JNIEXPORT jboolean JNICALL Java_org_lwjgl_ovr_OVR_novr_1SetFloat(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jfloat value) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
UNUSED_PARAMS(__env, clazz)
return (jboolean)ovr_SetFloat(session, propertyName, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetFloatArray__JJJI(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jlong valuesAddress, jint valuesCapacity) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
float *values = (float *)(intptr_t)valuesAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetFloatArray(session, propertyName, values, valuesCapacity);
}
JNIEXPORT jboolean JNICALL Java_org_lwjgl_ovr_OVR_novr_1SetFloatArray__JJJI(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jlong valuesAddress, jint valuesSize) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
float *values = (float *)(intptr_t)valuesAddress;
UNUSED_PARAMS(__env, clazz)
return (jboolean)ovr_SetFloatArray(session, propertyName, values, valuesSize);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetString(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jlong defaultValAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
const char *defaultVal = (const char *)(intptr_t)defaultValAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)ovr_GetString(session, propertyName, defaultVal);
}
JNIEXPORT jboolean JNICALL Java_org_lwjgl_ovr_OVR_novr_1SetString(JNIEnv *__env, jclass clazz, jlong hmddescAddress, jlong propertyNameAddress, jlong valueAddress) {
ovrSession hmddesc = (ovrSession)(intptr_t)hmddescAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
const char *value = (const char *)(intptr_t)valueAddress;
UNUSED_PARAMS(__env, clazz)
return (jboolean)ovr_SetString(hmddesc, propertyName, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetBoundaryGeometry__JIJ_3I(JNIEnv *__env, jclass clazz, jlong sessionAddress, jint boundaryType, jlong outFloorPointsAddress, jintArray outFloorPointsCountAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrVector3f *outFloorPoints = (ovrVector3f *)(intptr_t)outFloorPointsAddress;
jint __result;
jint *outFloorPointsCount = outFloorPointsCountAddress == NULL ? NULL : (*__env)->GetPrimitiveArrayCritical(__env, outFloorPointsCountAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)ovr_GetBoundaryGeometry(session, boundaryType, outFloorPoints, (int *)outFloorPointsCount);
if ( outFloorPointsCount != NULL ) (*__env)->ReleasePrimitiveArrayCritical(__env, outFloorPointsCountAddress, outFloorPointsCount, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_ovr_OVR_novr_1GetBoundaryGeometry__JIJ_3I(jlong sessionAddress, jint boundaryType, jlong outFloorPointsAddress, jint outFloorPointsCount__length, jint* outFloorPointsCount) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrVector3f *outFloorPoints = (ovrVector3f *)(intptr_t)outFloorPointsAddress;
UNUSED_PARAM(outFloorPointsCount__length)
return (jint)ovr_GetBoundaryGeometry(session, boundaryType, outFloorPoints, (int *)outFloorPointsCount);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTextureSwapChainLength__JJ_3I(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong chainAddress, jintArray out_LengthAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
jint __result;
jint *out_Length = (*__env)->GetPrimitiveArrayCritical(__env, out_LengthAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)ovr_GetTextureSwapChainLength(session, chain, (int *)out_Length);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_LengthAddress, out_Length, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_ovr_OVR_novr_1GetTextureSwapChainLength__JJ_3I(jlong sessionAddress, jlong chainAddress, jint out_Length__length, jint* out_Length) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
UNUSED_PARAM(out_Length__length)
return (jint)ovr_GetTextureSwapChainLength(session, chain, (int *)out_Length);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetTextureSwapChainCurrentIndex__JJ_3I(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong chainAddress, jintArray out_IndexAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
jint __result;
jint *out_Index = (*__env)->GetPrimitiveArrayCritical(__env, out_IndexAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)ovr_GetTextureSwapChainCurrentIndex(session, chain, (int *)out_Index);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_IndexAddress, out_Index, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_ovr_OVR_novr_1GetTextureSwapChainCurrentIndex__JJ_3I(jlong sessionAddress, jlong chainAddress, jint out_Index__length, jint* out_Index) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
UNUSED_PARAM(out_Index__length)
return (jint)ovr_GetTextureSwapChainCurrentIndex(session, chain, (int *)out_Index);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVR_novr_1GetFloatArray__JJ_3FI(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jfloatArray valuesAddress, jint valuesCapacity) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
jint __result;
jfloat *values = (*__env)->GetPrimitiveArrayCritical(__env, valuesAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)ovr_GetFloatArray(session, propertyName, (float *)values, valuesCapacity);
(*__env)->ReleasePrimitiveArrayCritical(__env, valuesAddress, values, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_ovr_OVR_novr_1GetFloatArray__JJ_3FI(jlong sessionAddress, jlong propertyNameAddress, jint values__length, jfloat* values, jint valuesCapacity) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
UNUSED_PARAM(values__length)
return (jint)ovr_GetFloatArray(session, propertyName, (float *)values, valuesCapacity);
}
JNIEXPORT jboolean JNICALL Java_org_lwjgl_ovr_OVR_novr_1SetFloatArray__JJ_3FI(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong propertyNameAddress, jfloatArray valuesAddress, jint valuesSize) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
jboolean __result;
jfloat *values = (*__env)->GetPrimitiveArrayCritical(__env, valuesAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jboolean)ovr_SetFloatArray(session, propertyName, (float *)values, valuesSize);
(*__env)->ReleasePrimitiveArrayCritical(__env, valuesAddress, values, 0);
return __result;
}
JNIEXPORT jboolean JNICALL JavaCritical_org_lwjgl_ovr_OVR_novr_1SetFloatArray__JJ_3FI(jlong sessionAddress, jlong propertyNameAddress, jint values__length, jfloat* values, jint valuesSize) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const char *propertyName = (const char *)(intptr_t)propertyNameAddress;
UNUSED_PARAM(values__length)
return (jboolean)ovr_SetFloatArray(session, propertyName, (float *)values, valuesSize);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import org.lwjgl.system.*;
import static org.lwjgl.system.dyncall.DynCallback.*;
/** Captured frame. */
@FunctionalInterface
public interface BGFXCaptureFrameCallbackI extends CallbackI.V {
String SIGNATURE = "(ppi)v";
@Override
default String getSignature() { return SIGNATURE; }
@Override
default void callback(long args) {
invoke(
dcbArgPointer(args),
dcbArgPointer(args),
dcbArgInt(args)
);
}
/**
* Will be called when a frame is captured.
*
* @param _this the callback interface
* @param _data image data
* @param _size image size
*/
void invoke(long _this, long _data, int _size);
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4710))
#endif
#include "common_tools.h"
DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4701 4702 4711 4738))
#endif
#include "lwjgl_malloc.h"
#define STBIW_MALLOC(sz) org_lwjgl_malloc(sz)
#define STBIW_REALLOC(p,sz) org_lwjgl_realloc(p,sz)
#define STBIW_FREE(p) org_lwjgl_free(p)
#define STBIW_ASSERT(x)
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STB_IMAGE_WRITE_STATIC
#include "stb_image_write.h"
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1png(JNIEnv *__env, jclass clazz, jlong filenameAddress, jint w, jint h, jint comp, jlong dataAddress, jint stride_in_bytes) {
const char *filename = (const char *)(intptr_t)filenameAddress;
const void *data = (const void *)(intptr_t)dataAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_write_png(filename, w, h, comp, data, stride_in_bytes);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1bmp(JNIEnv *__env, jclass clazz, jlong filenameAddress, jint w, jint h, jint comp, jlong dataAddress) {
const char *filename = (const char *)(intptr_t)filenameAddress;
const void *data = (const void *)(intptr_t)dataAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_write_bmp(filename, w, h, comp, data);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1tga(JNIEnv *__env, jclass clazz, jlong filenameAddress, jint w, jint h, jint comp, jlong dataAddress) {
const char *filename = (const char *)(intptr_t)filenameAddress;
const void *data = (const void *)(intptr_t)dataAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_write_tga(filename, w, h, comp, data);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1tga_1with_1rle(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)&stbi_write_tga_with_rle;
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1hdr__JIIIJ(JNIEnv *__env, jclass clazz, jlong filenameAddress, jint w, jint h, jint comp, jlong dataAddress) {
const char *filename = (const char *)(intptr_t)filenameAddress;
const float *data = (const float *)(intptr_t)dataAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_write_hdr(filename, w, h, comp, data);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1png_1to_1func(JNIEnv *__env, jclass clazz, jlong funcAddress, jlong contextAddress, jint w, jint h, jint comp, jlong dataAddress, jint stride_in_bytes) {
stbi_write_func *func = (stbi_write_func *)(intptr_t)funcAddress;
void *context = (void *)(intptr_t)contextAddress;
const void *data = (const void *)(intptr_t)dataAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_write_png_to_func(func, context, w, h, comp, data, stride_in_bytes);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1bmp_1to_1func(JNIEnv *__env, jclass clazz, jlong funcAddress, jlong contextAddress, jint w, jint h, jint comp, jlong dataAddress) {
stbi_write_func *func = (stbi_write_func *)(intptr_t)funcAddress;
void *context = (void *)(intptr_t)contextAddress;
const void *data = (const void *)(intptr_t)dataAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_write_bmp_to_func(func, context, w, h, comp, data);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1tga_1to_1func(JNIEnv *__env, jclass clazz, jlong funcAddress, jlong contextAddress, jint w, jint h, jint comp, jlong dataAddress) {
stbi_write_func *func = (stbi_write_func *)(intptr_t)funcAddress;
void *context = (void *)(intptr_t)contextAddress;
const void *data = (const void *)(intptr_t)dataAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_write_tga_to_func(func, context, w, h, comp, data);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1hdr_1to_1func__JJIIIJ(JNIEnv *__env, jclass clazz, jlong funcAddress, jlong contextAddress, jint w, jint h, jint comp, jlong dataAddress) {
stbi_write_func *func = (stbi_write_func *)(intptr_t)funcAddress;
void *context = (void *)(intptr_t)contextAddress;
const float *data = (const float *)(intptr_t)dataAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_write_hdr_to_func(func, context, w, h, comp, data);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1hdr__JIII_3F(JNIEnv *__env, jclass clazz, jlong filenameAddress, jint w, jint h, jint comp, jfloatArray dataAddress) {
const char *filename = (const char *)(intptr_t)filenameAddress;
jint __result;
jfloat *data = (*__env)->GetPrimitiveArrayCritical(__env, dataAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)stbi_write_hdr(filename, w, h, comp, (const float *)data);
(*__env)->ReleasePrimitiveArrayCritical(__env, dataAddress, data, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_stb_STBImageWrite_nstbi_1write_1hdr__JIII_3F(jlong filenameAddress, jint w, jint h, jint comp, jint data__length, jfloat* data) {
const char *filename = (const char *)(intptr_t)filenameAddress;
UNUSED_PARAM(data__length)
return (jint)stbi_write_hdr(filename, w, h, comp, (const float *)data);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageWrite_nstbi_1write_1hdr_1to_1func__JJIII_3F(JNIEnv *__env, jclass clazz, jlong funcAddress, jlong contextAddress, jint w, jint h, jint comp, jfloatArray dataAddress) {
stbi_write_func *func = (stbi_write_func *)(intptr_t)funcAddress;
void *context = (void *)(intptr_t)contextAddress;
jint __result;
jfloat *data = (*__env)->GetPrimitiveArrayCritical(__env, dataAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)stbi_write_hdr_to_func(func, context, w, h, comp, (const float *)data);
(*__env)->ReleasePrimitiveArrayCritical(__env, dataAddress, data, 0);
return __result;
}
#ifdef LWJGL_WINDOWS
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_stb_STBImageWrite_nstbi_1write_1hdr_1to_1func__JJIII_3F(jlong funcAddress, jlong contextAddress, jint w, jint h, jint comp, jint data__length, jfloat* data) {
stbi_write_func *func = (stbi_write_func *)(intptr_t)funcAddress;
void *context = (void *)(intptr_t)contextAddress;
UNUSED_PARAM(data__length)
return (jint)stbi_write_hdr_to_func(func, context, w, h, comp, (const float *)data);
}
#endif
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4711))
#endif
#include "common_tools.h"
DISABLE_WARNINGS()
#include "OVR_CAPI.h"
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVRUtil_novr_1Detect(JNIEnv *__env, jclass clazz, jint timeoutMilliseconds, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((ovrDetectResult*)(intptr_t)__result) = ovr_Detect(timeoutMilliseconds);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVRUtil_novrMatrix4f_1Projection(JNIEnv *__env, jclass clazz, jlong fovAddress, jfloat znear, jfloat zfar, jint projectionModFlags, jlong __result) {
ovrFovPort *fov = (ovrFovPort *)(intptr_t)fovAddress;
UNUSED_PARAMS(__env, clazz)
*((ovrMatrix4f*)(intptr_t)__result) = ovrMatrix4f_Projection(*fov, znear, zfar, projectionModFlags);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVRUtil_novrTimewarpProjectionDesc_1FromProjection(JNIEnv *__env, jclass clazz, jlong projectionAddress, jint projectionModFlags, jlong __result) {
ovrMatrix4f *projection = (ovrMatrix4f *)(intptr_t)projectionAddress;
UNUSED_PARAMS(__env, clazz)
*((ovrTimewarpProjectionDesc*)(intptr_t)__result) = ovrTimewarpProjectionDesc_FromProjection(*projection, projectionModFlags);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVRUtil_novrMatrix4f_1OrthoSubProjection(JNIEnv *__env, jclass clazz, jlong projectionAddress, jlong orthoScaleAddress, jfloat orthoDistance, jfloat HmdToEyeOffsetX, jlong __result) {
ovrMatrix4f *projection = (ovrMatrix4f *)(intptr_t)projectionAddress;
ovrVector2f *orthoScale = (ovrVector2f *)(intptr_t)orthoScaleAddress;
UNUSED_PARAMS(__env, clazz)
*((ovrMatrix4f*)(intptr_t)__result) = ovrMatrix4f_OrthoSubProjection(*projection, *orthoScale, orthoDistance, HmdToEyeOffsetX);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVRUtil_novr_1CalcEyePoses(JNIEnv *__env, jclass clazz, jlong headPoseAddress, jlong HmdToEyeOffsetAddress, jlong outEyePosesAddress) {
ovrPosef *headPose = (ovrPosef *)(intptr_t)headPoseAddress;
const ovrVector3f *HmdToEyeOffset = (const ovrVector3f *)(intptr_t)HmdToEyeOffsetAddress;
ovrPosef *outEyePoses = (ovrPosef *)(intptr_t)outEyePosesAddress;
UNUSED_PARAMS(__env, clazz)
ovr_CalcEyePoses(*headPose, HmdToEyeOffset, outEyePoses);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVRUtil_novr_1GetEyePoses__JJZJJJ(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong frameIndex, jboolean latencyMarker, jlong hmdToEyeOffsetAddress, jlong outEyePosesAddress, jlong outSensorSampleTimeAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const ovrVector3f *hmdToEyeOffset = (const ovrVector3f *)(intptr_t)hmdToEyeOffsetAddress;
ovrPosef *outEyePoses = (ovrPosef *)(intptr_t)outEyePosesAddress;
double *outSensorSampleTime = (double *)(intptr_t)outSensorSampleTimeAddress;
UNUSED_PARAMS(__env, clazz)
ovr_GetEyePoses(session, frameIndex, latencyMarker, hmdToEyeOffset, outEyePoses, outSensorSampleTime);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVRUtil_novrPosef_1FlipHandedness(JNIEnv *__env, jclass clazz, jlong inPoseAddress, jlong outPoseAddress) {
const ovrPosef *inPose = (const ovrPosef *)(intptr_t)inPoseAddress;
ovrPosef *outPose = (ovrPosef *)(intptr_t)outPoseAddress;
UNUSED_PARAMS(__env, clazz)
ovrPosef_FlipHandedness(inPose, outPose);
}
JNIEXPORT void JNICALL Java_org_lwjgl_ovr_OVRUtil_novr_1GetEyePoses__JJZJJ_3D(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong frameIndex, jboolean latencyMarker, jlong hmdToEyeOffsetAddress, jlong outEyePosesAddress, jdoubleArray outSensorSampleTimeAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const ovrVector3f *hmdToEyeOffset = (const ovrVector3f *)(intptr_t)hmdToEyeOffsetAddress;
ovrPosef *outEyePoses = (ovrPosef *)(intptr_t)outEyePosesAddress;
jdouble *outSensorSampleTime = outSensorSampleTimeAddress == NULL ? NULL : (*__env)->GetPrimitiveArrayCritical(__env, outSensorSampleTimeAddress, 0);
UNUSED_PARAMS(__env, clazz)
ovr_GetEyePoses(session, frameIndex, latencyMarker, hmdToEyeOffset, outEyePoses, (double *)outSensorSampleTime);
if ( outSensorSampleTime != NULL ) (*__env)->ReleasePrimitiveArrayCritical(__env, outSensorSampleTimeAddress, outSensorSampleTime, 0);
}
#ifdef LWJGL_WINDOWS
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_ovr_OVRUtil_novr_1GetEyePoses__JJZJJ_3D(jlong sessionAddress, jlong frameIndex, jboolean latencyMarker, jlong hmdToEyeOffsetAddress, jlong outEyePosesAddress, jint outSensorSampleTime__length, jdouble* outSensorSampleTime) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const ovrVector3f *hmdToEyeOffset = (const ovrVector3f *)(intptr_t)hmdToEyeOffsetAddress;
ovrPosef *outEyePoses = (ovrPosef *)(intptr_t)outEyePosesAddress;
UNUSED_PARAM(outSensorSampleTime__length)
ovr_GetEyePoses(session, frameIndex, latencyMarker, hmdToEyeOffset, outEyePoses, (double *)outSensorSampleTime);
}
#endif
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
/** The IMG_format_pvrtc extension. */
public final class IMGFormatPVRTC {
/** The extension specification version. */
public static final int VK_IMG_FORMAT_PVRTC_SPEC_VERSION = 1;
/** The extension name. */
public static final String VK_IMG_FORMAT_PVRTC_EXTENSION_NAME = "VK_IMG_format_pvrtc";
/** VkFormat */
public static final int
VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG = 1000054000,
VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG = 1000054001,
VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG = 1000054002,
VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG = 1000054003,
VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG = 1000054004,
VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG = 1000054005,
VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG = 1000054006,
VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG = 1000054007;
private IMGFormatPVRTC() {}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import org.lwjgl.system.*;
import static org.lwjgl.system.dyncall.DynCallback.*;
/**
* Prints a debug message.
*
* <p>Not thread safe and it can be called from any thread.</p>
*/
@FunctionalInterface
public interface BGFXTraceVarArgsCallbackI extends CallbackI.V {
String SIGNATURE = "(ppspp)v";
@Override
default String getSignature() { return SIGNATURE; }
@Override
default void callback(long args) {
invoke(
dcbArgPointer(args),
dcbArgPointer(args),
dcbArgShort(args),
dcbArgPointer(args),
dcbArgPointer(args)
);
}
/**
* Will be called when a debug message is produced.
*
* @param _this the callback interface
* @param _filePath file path where debug message was generated
* @param _line line where debug message was generated
* @param _format {@code printf} style format
* @param _argList variable arguments list initialized with {@code va_start}
*/
void invoke(long _this, long _filePath, short _line, long _format, long _argList);
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import org.lwjgl.system.*;
import static org.lwjgl.system.dyncall.DynCallback.*;
/** Called when capture begins. */
@FunctionalInterface
public interface BGFXCaptureBeginCallbackI extends CallbackI.V {
String SIGNATURE = "(piiiiB)v";
@Override
default String getSignature() { return SIGNATURE; }
@Override
default void callback(long args) {
invoke(
dcbArgPointer(args),
dcbArgInt(args),
dcbArgInt(args),
dcbArgInt(args),
dcbArgInt(args),
dcbArgBool(args) != 0
);
}
/**
* Will be called when capture begins.
*
* @param _this the callback interface
* @param _width image width
* @param _height image height
* @param _pitch number of bytes to skip to next line
* @param _format texture format
* @param _yflip if true image origin is bottom left
*/
void invoke(long _this, int _width, int _height, int _pitch, int _format, boolean _yflip);
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
DISABLE_WARNINGS()
#include "OVR_CAPI_GL.h"
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVRGL_novr_1CreateTextureSwapChainGL(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong descAddress, jlong out_TextureSwapChainAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const ovrTextureSwapChainDesc *desc = (const ovrTextureSwapChainDesc *)(intptr_t)descAddress;
ovrTextureSwapChain *out_TextureSwapChain = (ovrTextureSwapChain *)(intptr_t)out_TextureSwapChainAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_CreateTextureSwapChainGL(session, desc, out_TextureSwapChain);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVRGL_novr_1GetTextureSwapChainBufferGL__JJIJ(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong chainAddress, jint index, jlong out_TexIdAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
unsigned int *out_TexId = (unsigned int *)(intptr_t)out_TexIdAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetTextureSwapChainBufferGL(session, chain, index, out_TexId);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVRGL_novr_1CreateMirrorTextureGL(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong descAddress, jlong out_MirrorTextureAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
const ovrMirrorTextureDesc *desc = (const ovrMirrorTextureDesc *)(intptr_t)descAddress;
ovrMirrorTexture *out_MirrorTexture = (ovrMirrorTexture *)(intptr_t)out_MirrorTextureAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_CreateMirrorTextureGL(session, desc, out_MirrorTexture);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVRGL_novr_1GetMirrorTextureBufferGL__JJJ(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong mirrorTextureAddress, jlong out_TexIdAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrMirrorTexture mirrorTexture = (ovrMirrorTexture)(intptr_t)mirrorTextureAddress;
unsigned int *out_TexId = (unsigned int *)(intptr_t)out_TexIdAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)ovr_GetMirrorTextureBufferGL(session, mirrorTexture, out_TexId);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVRGL_novr_1GetTextureSwapChainBufferGL__JJI_3I(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong chainAddress, jint index, jintArray out_TexIdAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
jint __result;
jint *out_TexId = (*__env)->GetPrimitiveArrayCritical(__env, out_TexIdAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)ovr_GetTextureSwapChainBufferGL(session, chain, index, (unsigned int *)out_TexId);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_TexIdAddress, out_TexId, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_ovr_OVRGL_novr_1GetTextureSwapChainBufferGL__JJI_3I(jlong sessionAddress, jlong chainAddress, jint index, jint out_TexId__length, jint* out_TexId) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrTextureSwapChain chain = (ovrTextureSwapChain)(intptr_t)chainAddress;
UNUSED_PARAM(out_TexId__length)
return (jint)ovr_GetTextureSwapChainBufferGL(session, chain, index, (unsigned int *)out_TexId);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_ovr_OVRGL_novr_1GetMirrorTextureBufferGL__JJ_3I(JNIEnv *__env, jclass clazz, jlong sessionAddress, jlong mirrorTextureAddress, jintArray out_TexIdAddress) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrMirrorTexture mirrorTexture = (ovrMirrorTexture)(intptr_t)mirrorTextureAddress;
jint __result;
jint *out_TexId = (*__env)->GetPrimitiveArrayCritical(__env, out_TexIdAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)ovr_GetMirrorTextureBufferGL(session, mirrorTexture, (unsigned int *)out_TexId);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_TexIdAddress, out_TexId, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_ovr_OVRGL_novr_1GetMirrorTextureBufferGL__JJ_3I(jlong sessionAddress, jlong mirrorTextureAddress, jint out_TexId__length, jint* out_TexId) {
ovrSession session = (ovrSession)(intptr_t)sessionAddress;
ovrMirrorTexture mirrorTexture = (ovrMirrorTexture)(intptr_t)mirrorTextureAddress;
UNUSED_PARAM(out_TexId__length)
return (jint)ovr_GetMirrorTextureBufferGL(session, mirrorTexture, (unsigned int *)out_TexId);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import org.lwjgl.system.*;
import static org.lwjgl.system.dyncall.DynCallback.*;
/** Reads cached item. */
@FunctionalInterface
public interface BGFXCacheReadCallbackI extends CallbackI.Z {
String SIGNATURE = "(plpi)B";
@Override
default String getSignature() { return SIGNATURE; }
@Override
default boolean callback(long args) {
return invoke(
dcbArgPointer(args),
dcbArgLong(args),
dcbArgPointer(args),
dcbArgInt(args)
);
}
/**
* Will be called to read a cached item.
*
* @param _this the callback interface
* @param _id cache id
* @param _data buffer where to read data
* @param _size size of data to read
*
* @return true if data is read
*/
boolean invoke(long _this, long _id, long _data, int _size);
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opengl;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* Native bindings to the <a href="http://www.opengl.org/registry/specs/ARB/gl_spirv.txt">ARB_gl_spirv</a> extension.
*
* <p>This is version 100 of the GL_ARB_gl_spirv extension.</p>
*
* <p>This extension does two things:</p>
*
* <ol>
* <li>Allows a SPIR-V module to be specified as containing a programmable shader stage, rather than using GLSL, whatever the source language was used to
* create the SPIR-V module.</li>
* <li>Modifies GLSL to be a source language for creating SPIR-V modules for OpenGL consumption. Such GLSL can be used to create such SPIR-V modules,
* outside of the OpenGL runtime.</li>
* </ol>
*
* <p>Requires {@link GL33 OpenGL 3.3}.</p>
*/
public class ARBGLSPIRV {
/** Accepted by the {@code binaryformat} parameter of {@link GL41#glShaderBinary ShaderBinary}. */
public static final int GL_SHADER_BINARY_FORMAT_SPIR_V_ARB = 0x9551;
/** Accepted by the {@code pname} parameter of {@link GL20#glGetShaderiv GetShaderiv}. */
public static final int GL_SPIR_V_BINARY_ARB = 0x9552;
protected ARBGLSPIRV() {
throw new UnsupportedOperationException();
}
static boolean isAvailable(GLCapabilities caps) {
return checkFunctions(
caps.glSpecializeShaderARB
);
}
// --- [ glSpecializeShaderARB ] ---
/**
* Specializes a shader created from a SPIR-V module.
*
* @param shader
* @param pEntryPoint
* @param numSpecializationConstants
* @param pConstantIndex
* @param pConstantValue
*/
public static void nglSpecializeShaderARB(int shader, long pEntryPoint, int numSpecializationConstants, long pConstantIndex, long pConstantValue) {
long __functionAddress = GL.getCapabilities().glSpecializeShaderARB;
if ( CHECKS )
checkFunctionAddress(__functionAddress);
callPPPV(__functionAddress, shader, pEntryPoint, numSpecializationConstants, pConstantIndex, pConstantValue);
}
/**
* Specializes a shader created from a SPIR-V module.
*
* @param shader
* @param pEntryPoint
* @param pConstantIndex
* @param pConstantValue
*/
public static void glSpecializeShaderARB(int shader, ByteBuffer pEntryPoint, IntBuffer pConstantIndex, IntBuffer pConstantValue) {
if ( CHECKS ) {
checkNT1(pEntryPoint);
checkBuffer(pConstantValue, pConstantIndex.remaining());
}
nglSpecializeShaderARB(shader, memAddress(pEntryPoint), pConstantIndex.remaining(), memAddress(pConstantIndex), memAddress(pConstantValue));
}
/**
* Specializes a shader created from a SPIR-V module.
*
* @param shader
* @param pEntryPoint
* @param pConstantIndex
* @param pConstantValue
*/
public static void glSpecializeShaderARB(int shader, CharSequence pEntryPoint, IntBuffer pConstantIndex, IntBuffer pConstantValue) {
if ( CHECKS )
checkBuffer(pConstantValue, pConstantIndex.remaining());
MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();
try {
ByteBuffer pEntryPointEncoded = stack.UTF8(pEntryPoint);
nglSpecializeShaderARB(shader, memAddress(pEntryPointEncoded), pConstantIndex.remaining(), memAddress(pConstantIndex), memAddress(pConstantValue));
} finally {
stack.setPointer(stackPointer);
}
}
/** Array version of: {@link #glSpecializeShaderARB SpecializeShaderARB} */
public static void glSpecializeShaderARB(int shader, ByteBuffer pEntryPoint, int[] pConstantIndex, int[] pConstantValue) {
long __functionAddress = GL.getCapabilities().glSpecializeShaderARB;
if ( CHECKS ) {
checkFunctionAddress(__functionAddress);
checkNT1(pEntryPoint);
checkBuffer(pConstantValue, pConstantIndex.length);
}
callPPPV(__functionAddress, shader, memAddress(pEntryPoint), pConstantIndex.length, pConstantIndex, pConstantValue);
}
/** Array version of: {@link #glSpecializeShaderARB SpecializeShaderARB} */
public static void glSpecializeShaderARB(int shader, CharSequence pEntryPoint, int[] pConstantIndex, int[] pConstantValue) {
long __functionAddress = GL.getCapabilities().glSpecializeShaderARB;
if ( CHECKS ) {
checkFunctionAddress(__functionAddress);
checkBuffer(pConstantValue, pConstantIndex.length);
}
MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();
try {
ByteBuffer pEntryPointEncoded = stack.UTF8(pEntryPoint);
callPPPV(__functionAddress, shader, memAddress(pEntryPointEncoded), pConstantIndex.length, pConstantIndex, pConstantValue);
} finally {
stack.setPointer(stackPointer);
}
}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4701 4702 4711 4738))
#endif
#define STB_PERLIN_IMPLEMENTATION
#include "stb_perlin.h"
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT jfloat JNICALL Java_org_lwjgl_stb_STBPerlin_stb_1perlin_1noise3(JNIEnv *__env, jclass clazz, jfloat x, jfloat y, jfloat z, jint x_wrap, jint y_wrap, jint z_wrap) {
UNUSED_PARAMS(__env, clazz)
return (jfloat)stb_perlin_noise3(x, y, z, x_wrap, y_wrap, z_wrap);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4710))
#endif
#include "common_tools.h"
DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4711))
#endif
#define XXH_PRIVATE_API
#include "lwjgl_malloc.h"
#include "xxhash.h"
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH32(JNIEnv *__env, jclass clazz, jlong inputAddress, jlong length, jint seed) {
const void *input = (const void *)(intptr_t)inputAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)XXH32(input, (size_t)length, seed);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH32_1createState(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)XXH32_createState();
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH32_1freeState(JNIEnv *__env, jclass clazz, jlong statePtrAddress) {
XXH32_state_t *statePtr = (XXH32_state_t *)(intptr_t)statePtrAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)XXH32_freeState(statePtr);
}
JNIEXPORT void JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH32_1copyState(JNIEnv *__env, jclass clazz, jlong dst_stateAddress, jlong src_stateAddress) {
XXH32_state_t *dst_state = (XXH32_state_t *)(intptr_t)dst_stateAddress;
const XXH32_state_t *src_state = (const XXH32_state_t *)(intptr_t)src_stateAddress;
UNUSED_PARAMS(__env, clazz)
XXH32_copyState(dst_state, src_state);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH32_1reset(JNIEnv *__env, jclass clazz, jlong statePtrAddress, jint seed) {
XXH32_state_t *statePtr = (XXH32_state_t *)(intptr_t)statePtrAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)XXH32_reset(statePtr, seed);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH32_1update(JNIEnv *__env, jclass clazz, jlong statePtrAddress, jlong inputAddress, jlong length) {
XXH32_state_t *statePtr = (XXH32_state_t *)(intptr_t)statePtrAddress;
const void *input = (const void *)(intptr_t)inputAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)XXH32_update(statePtr, input, (size_t)length);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH32_1digest(JNIEnv *__env, jclass clazz, jlong statePtrAddress) {
const XXH32_state_t *statePtr = (const XXH32_state_t *)(intptr_t)statePtrAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)XXH32_digest(statePtr);
}
JNIEXPORT void JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH32_1canonicalFromHash(JNIEnv *__env, jclass clazz, jlong dstAddress, jint hash) {
XXH32_canonical_t *dst = (XXH32_canonical_t *)(intptr_t)dstAddress;
UNUSED_PARAMS(__env, clazz)
XXH32_canonicalFromHash(dst, hash);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH32_1hashFromCanonical(JNIEnv *__env, jclass clazz, jlong srcAddress) {
const XXH32_canonical_t *src = (const XXH32_canonical_t *)(intptr_t)srcAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)XXH32_hashFromCanonical(src);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH64(JNIEnv *__env, jclass clazz, jlong inputAddress, jlong length, jlong seed) {
const void *input = (const void *)(intptr_t)inputAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)XXH64(input, (size_t)length, seed);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH64_1createState(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)XXH64_createState();
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH64_1freeState(JNIEnv *__env, jclass clazz, jlong statePtrAddress) {
XXH64_state_t *statePtr = (XXH64_state_t *)(intptr_t)statePtrAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)XXH64_freeState(statePtr);
}
JNIEXPORT void JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH64_1copyState(JNIEnv *__env, jclass clazz, jlong dst_stateAddress, jlong src_stateAddress) {
XXH64_state_t *dst_state = (XXH64_state_t *)(intptr_t)dst_stateAddress;
const XXH64_state_t *src_state = (const XXH64_state_t *)(intptr_t)src_stateAddress;
UNUSED_PARAMS(__env, clazz)
XXH64_copyState(dst_state, src_state);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH64_1reset(JNIEnv *__env, jclass clazz, jlong statePtrAddress, jlong seed) {
XXH64_state_t *statePtr = (XXH64_state_t *)(intptr_t)statePtrAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)XXH64_reset(statePtr, seed);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH64_1update(JNIEnv *__env, jclass clazz, jlong statePtrAddress, jlong inputAddress, jlong length) {
XXH64_state_t *statePtr = (XXH64_state_t *)(intptr_t)statePtrAddress;
const void *input = (const void *)(intptr_t)inputAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)XXH64_update(statePtr, input, (size_t)length);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH64_1digest(JNIEnv *__env, jclass clazz, jlong statePtrAddress) {
const XXH64_state_t *statePtr = (const XXH64_state_t *)(intptr_t)statePtrAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)XXH64_digest(statePtr);
}
JNIEXPORT void JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH64_1canonicalFromHash(JNIEnv *__env, jclass clazz, jlong dstAddress, jlong hash) {
XXH64_canonical_t *dst = (XXH64_canonical_t *)(intptr_t)dstAddress;
UNUSED_PARAMS(__env, clazz)
XXH64_canonicalFromHash(dst, hash);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_xxhash_XXHash_nXXH64_1hashFromCanonical(JNIEnv *__env, jclass clazz, jlong srcAddress) {
const XXH64_canonical_t *src = (const XXH64_canonical_t *)(intptr_t)srcAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)XXH64_hashFromCanonical(src);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4701 4702 4711 4738))
#endif
#include "lwjgl_malloc.h"
#define STBIR_MALLOC(size,c) org_lwjgl_malloc(size)
#define STBIR_FREE(ptr,c) org_lwjgl_free(ptr)
#define STBIR_ASSERT(x)
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_STATIC
#include "stb_image_resize.h"
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1uint8(JNIEnv *__env, jclass clazz, jlong input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jlong output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels) {
const unsigned char *input_pixels = (const unsigned char *)(intptr_t)input_pixelsAddress;
unsigned char *output_pixels = (unsigned char *)(intptr_t)output_pixelsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbir_resize_uint8(input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, num_channels);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1float__JIIIJIIII(JNIEnv *__env, jclass clazz, jlong input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jlong output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels) {
const float *input_pixels = (const float *)(intptr_t)input_pixelsAddress;
float *output_pixels = (float *)(intptr_t)output_pixelsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbir_resize_float(input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, num_channels);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1uint8_1srgb(JNIEnv *__env, jclass clazz, jlong input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jlong output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels, jint alpha_channel, jint flags) {
const unsigned char *input_pixels = (const unsigned char *)(intptr_t)input_pixelsAddress;
unsigned char *output_pixels = (unsigned char *)(intptr_t)output_pixelsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbir_resize_uint8_srgb(input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, num_channels, alpha_channel, flags);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1uint8_1srgb_1edgemode(JNIEnv *__env, jclass clazz, jlong input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jlong output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels, jint alpha_channel, jint flags, jint edge_wrap_mode) {
const unsigned char *input_pixels = (const unsigned char *)(intptr_t)input_pixelsAddress;
unsigned char *output_pixels = (unsigned char *)(intptr_t)output_pixelsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbir_resize_uint8_srgb_edgemode(input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, num_channels, alpha_channel, flags, edge_wrap_mode);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1uint8_1generic(JNIEnv *__env, jclass clazz, jlong input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jlong output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels, jint alpha_channel, jint flags, jint edge_wrap_mode, jint filter, jint space, jlong alloc_contextAddress) {
const unsigned char *input_pixels = (const unsigned char *)(intptr_t)input_pixelsAddress;
unsigned char *output_pixels = (unsigned char *)(intptr_t)output_pixelsAddress;
void *alloc_context = (void *)(intptr_t)alloc_contextAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbir_resize_uint8_generic(input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, num_channels, alpha_channel, flags, edge_wrap_mode, filter, space, alloc_context);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1uint16_1generic__JIIIJIIIIIIIIIJ(JNIEnv *__env, jclass clazz, jlong input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jlong output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels, jint alpha_channel, jint flags, jint edge_wrap_mode, jint filter, jint space, jlong alloc_contextAddress) {
const stbir_uint16 *input_pixels = (const stbir_uint16 *)(intptr_t)input_pixelsAddress;
stbir_uint16 *output_pixels = (stbir_uint16 *)(intptr_t)output_pixelsAddress;
void *alloc_context = (void *)(intptr_t)alloc_contextAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbir_resize_uint16_generic(input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, num_channels, alpha_channel, flags, edge_wrap_mode, filter, space, alloc_context);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1float_1generic__JIIIJIIIIIIIIIJ(JNIEnv *__env, jclass clazz, jlong input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jlong output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels, jint alpha_channel, jint flags, jint edge_wrap_mode, jint filter, jint space, jlong alloc_contextAddress) {
const float *input_pixels = (const float *)(intptr_t)input_pixelsAddress;
float *output_pixels = (float *)(intptr_t)output_pixelsAddress;
void *alloc_context = (void *)(intptr_t)alloc_contextAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbir_resize_float_generic(input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, num_channels, alpha_channel, flags, edge_wrap_mode, filter, space, alloc_context);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize(JNIEnv *__env, jclass clazz, jlong input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jlong output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint datatype, jint num_channels, jint alpha_channel, jint flags, jint edge_mode_horizontal, jint edge_mode_vertical, jint filter_horizontal, jint filter_vertical, jint space, jlong alloc_contextAddress) {
const void *input_pixels = (const void *)(intptr_t)input_pixelsAddress;
void *output_pixels = (void *)(intptr_t)output_pixelsAddress;
void *alloc_context = (void *)(intptr_t)alloc_contextAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbir_resize(input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, datatype, num_channels, alpha_channel, flags, edge_mode_horizontal, edge_mode_vertical, filter_horizontal, filter_vertical, space, alloc_context);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1subpixel(JNIEnv *__env, jclass clazz, jlong input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jlong output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint datatype, jint num_channels, jint alpha_channel, jint flags, jint edge_mode_horizontal, jint edge_mode_vertical, jint filter_horizontal, jint filter_vertical, jint space, jlong alloc_contextAddress, jfloat x_scale, jfloat y_scale, jfloat x_offset, jfloat y_offset) {
const void *input_pixels = (const void *)(intptr_t)input_pixelsAddress;
void *output_pixels = (void *)(intptr_t)output_pixelsAddress;
void *alloc_context = (void *)(intptr_t)alloc_contextAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbir_resize_subpixel(input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, datatype, num_channels, alpha_channel, flags, edge_mode_horizontal, edge_mode_vertical, filter_horizontal, filter_vertical, space, alloc_context, x_scale, y_scale, x_offset, y_offset);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1region(JNIEnv *__env, jclass clazz, jlong input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jlong output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint datatype, jint num_channels, jint alpha_channel, jint flags, jint edge_mode_horizontal, jint edge_mode_vertical, jint filter_horizontal, jint filter_vertical, jint space, jlong alloc_contextAddress, jfloat s0, jfloat t0, jfloat s1, jfloat t1) {
const void *input_pixels = (const void *)(intptr_t)input_pixelsAddress;
void *output_pixels = (void *)(intptr_t)output_pixelsAddress;
void *alloc_context = (void *)(intptr_t)alloc_contextAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbir_resize_region(input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, datatype, num_channels, alpha_channel, flags, edge_mode_horizontal, edge_mode_vertical, filter_horizontal, filter_vertical, space, alloc_context, s0, t0, s1, t1);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1float___3FIII_3FIIII(JNIEnv *__env, jclass clazz, jfloatArray input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jfloatArray output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels) {
jint __result;
jfloat *input_pixels = (*__env)->GetPrimitiveArrayCritical(__env, input_pixelsAddress, 0);
jfloat *output_pixels = (*__env)->GetPrimitiveArrayCritical(__env, output_pixelsAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)stbir_resize_float((const float *)input_pixels, input_w, input_h, input_stride_in_bytes, (float *)output_pixels, output_w, output_h, output_stride_in_bytes, num_channels);
(*__env)->ReleasePrimitiveArrayCritical(__env, output_pixelsAddress, output_pixels, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, input_pixelsAddress, input_pixels, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_stb_STBImageResize_nstbir_1resize_1float___3FIII_3FIIII(jint input_pixels__length, jfloat* input_pixels, jint input_w, jint input_h, jint input_stride_in_bytes, jint output_pixels__length, jfloat* output_pixels, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels) {
UNUSED_PARAM(input_pixels__length)
UNUSED_PARAM(output_pixels__length)
return (jint)stbir_resize_float((const float *)input_pixels, input_w, input_h, input_stride_in_bytes, (float *)output_pixels, output_w, output_h, output_stride_in_bytes, num_channels);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1uint16_1generic___3SIII_3SIIIIIIIIIJ(JNIEnv *__env, jclass clazz, jshortArray input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jshortArray output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels, jint alpha_channel, jint flags, jint edge_wrap_mode, jint filter, jint space, jlong alloc_contextAddress) {
void *alloc_context = (void *)(intptr_t)alloc_contextAddress;
jint __result;
jshort *input_pixels = (*__env)->GetPrimitiveArrayCritical(__env, input_pixelsAddress, 0);
jshort *output_pixels = (*__env)->GetPrimitiveArrayCritical(__env, output_pixelsAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)stbir_resize_uint16_generic((const stbir_uint16 *)input_pixels, input_w, input_h, input_stride_in_bytes, (stbir_uint16 *)output_pixels, output_w, output_h, output_stride_in_bytes, num_channels, alpha_channel, flags, edge_wrap_mode, filter, space, alloc_context);
(*__env)->ReleasePrimitiveArrayCritical(__env, output_pixelsAddress, output_pixels, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, input_pixelsAddress, input_pixels, 0);
return __result;
}
#ifdef LWJGL_WINDOWS
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_stb_STBImageResize_nstbir_1resize_1uint16_1generic___3SIII_3SIIIIIIIIIJ(jint input_pixels__length, jshort* input_pixels, jint input_w, jint input_h, jint input_stride_in_bytes, jint output_pixels__length, jshort* output_pixels, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels, jint alpha_channel, jint flags, jint edge_wrap_mode, jint filter, jint space, jlong alloc_contextAddress) {
void *alloc_context = (void *)(intptr_t)alloc_contextAddress;
UNUSED_PARAM(input_pixels__length)
UNUSED_PARAM(output_pixels__length)
return (jint)stbir_resize_uint16_generic((const stbir_uint16 *)input_pixels, input_w, input_h, input_stride_in_bytes, (stbir_uint16 *)output_pixels, output_w, output_h, output_stride_in_bytes, num_channels, alpha_channel, flags, edge_wrap_mode, filter, space, alloc_context);
}
#endif
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImageResize_nstbir_1resize_1float_1generic___3FIII_3FIIIIIIIIIJ(JNIEnv *__env, jclass clazz, jfloatArray input_pixelsAddress, jint input_w, jint input_h, jint input_stride_in_bytes, jfloatArray output_pixelsAddress, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels, jint alpha_channel, jint flags, jint edge_wrap_mode, jint filter, jint space, jlong alloc_contextAddress) {
void *alloc_context = (void *)(intptr_t)alloc_contextAddress;
jint __result;
jfloat *input_pixels = (*__env)->GetPrimitiveArrayCritical(__env, input_pixelsAddress, 0);
jfloat *output_pixels = (*__env)->GetPrimitiveArrayCritical(__env, output_pixelsAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)stbir_resize_float_generic((const float *)input_pixels, input_w, input_h, input_stride_in_bytes, (float *)output_pixels, output_w, output_h, output_stride_in_bytes, num_channels, alpha_channel, flags, edge_wrap_mode, filter, space, alloc_context);
(*__env)->ReleasePrimitiveArrayCritical(__env, output_pixelsAddress, output_pixels, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, input_pixelsAddress, input_pixels, 0);
return __result;
}
#ifdef LWJGL_WINDOWS
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_stb_STBImageResize_nstbir_1resize_1float_1generic___3FIII_3FIIIIIIIIIJ(jint input_pixels__length, jfloat* input_pixels, jint input_w, jint input_h, jint input_stride_in_bytes, jint output_pixels__length, jfloat* output_pixels, jint output_w, jint output_h, jint output_stride_in_bytes, jint num_channels, jint alpha_channel, jint flags, jint edge_wrap_mode, jint filter, jint space, jlong alloc_contextAddress) {
void *alloc_context = (void *)(intptr_t)alloc_contextAddress;
UNUSED_PARAM(input_pixels__length)
UNUSED_PARAM(output_pixels__length)
return (jint)stbir_resize_float_generic((const float *)input_pixels, input_w, input_h, input_stride_in_bytes, (float *)output_pixels, output_w, output_h, output_stride_in_bytes, num_channels, alpha_channel, flags, edge_wrap_mode, filter, space, alloc_context);
}
#endif
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.nuklear;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* <h3>Layout</h3>
*
* <pre><code>struct nk_style_scrollbar {
{@link NkStyleItem struct nk_style_item} normal;
{@link NkStyleItem struct nk_style_item} hover;
{@link NkStyleItem struct nk_style_item} active;
{@link NkColor struct nk_color} border_color;
{@link NkStyleItem struct nk_style_item} cursor_normal;
{@link NkStyleItem struct nk_style_item} cursor_hover;
{@link NkStyleItem struct nk_style_item} cursor_active;
{@link NkColor struct nk_color} cursor_border_color;
float border;
float rounding;
float border_cursor;
float rounding_cursor;
{@link NkVec2 struct nk_vec2} padding;
int show_buttons;
{@link NkStyleButton struct nk_style_button} inc_button;
{@link NkStyleButton struct nk_style_button} dec_button;
nk_symbol_type inc_symbol;
nk_symbol_type dec_symbol;
{@link NkHandle nk_handle} userdata;
nk_draw_begin draw_begin;
nk_draw_end draw_end;
}</code></pre>
*/
public class NkStyleScrollbar extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
NORMAL,
HOVER,
ACTIVE,
BORDER_COLOR,
CURSOR_NORMAL,
CURSOR_HOVER,
CURSOR_ACTIVE,
CURSOR_BORDER_COLOR,
BORDER,
ROUNDING,
BORDER_CURSOR,
ROUNDING_CURSOR,
PADDING,
SHOW_BUTTONS,
INC_BUTTON,
DEC_BUTTON,
INC_SYMBOL,
DEC_SYMBOL,
USERDATA,
DRAW_BEGIN,
DRAW_END;
static {
Layout layout = __struct(
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkColor.SIZEOF, NkColor.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkColor.SIZEOF, NkColor.ALIGNOF),
__member(4),
__member(4),
__member(4),
__member(4),
__member(NkVec2.SIZEOF, NkVec2.ALIGNOF),
__member(4),
__member(NkStyleButton.SIZEOF, NkStyleButton.ALIGNOF),
__member(NkStyleButton.SIZEOF, NkStyleButton.ALIGNOF),
__member(4),
__member(4),
__member(NkHandle.SIZEOF, NkHandle.ALIGNOF),
__member(POINTER_SIZE),
__member(POINTER_SIZE)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
NORMAL = layout.offsetof(0);
HOVER = layout.offsetof(1);
ACTIVE = layout.offsetof(2);
BORDER_COLOR = layout.offsetof(3);
CURSOR_NORMAL = layout.offsetof(4);
CURSOR_HOVER = layout.offsetof(5);
CURSOR_ACTIVE = layout.offsetof(6);
CURSOR_BORDER_COLOR = layout.offsetof(7);
BORDER = layout.offsetof(8);
ROUNDING = layout.offsetof(9);
BORDER_CURSOR = layout.offsetof(10);
ROUNDING_CURSOR = layout.offsetof(11);
PADDING = layout.offsetof(12);
SHOW_BUTTONS = layout.offsetof(13);
INC_BUTTON = layout.offsetof(14);
DEC_BUTTON = layout.offsetof(15);
INC_SYMBOL = layout.offsetof(16);
DEC_SYMBOL = layout.offsetof(17);
USERDATA = layout.offsetof(18);
DRAW_BEGIN = layout.offsetof(19);
DRAW_END = layout.offsetof(20);
}
NkStyleScrollbar(long address, ByteBuffer container) {
super(address, container);
}
/**
* Creates a {@link NkStyleScrollbar} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public NkStyleScrollbar(ByteBuffer container) {
this(memAddress(container), checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** Returns a {@link NkStyleItem} view of the {@code normal} field. */
public NkStyleItem normal() { return nnormal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code hover} field. */
public NkStyleItem hover() { return nhover(address()); }
/** Returns a {@link NkStyleItem} view of the {@code active} field. */
public NkStyleItem active() { return nactive(address()); }
/** Returns a {@link NkColor} view of the {@code border_color} field. */
public NkColor border_color() { return nborder_color(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_normal} field. */
public NkStyleItem cursor_normal() { return ncursor_normal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_hover} field. */
public NkStyleItem cursor_hover() { return ncursor_hover(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_active} field. */
public NkStyleItem cursor_active() { return ncursor_active(address()); }
/** Returns a {@link NkColor} view of the {@code cursor_border_color} field. */
public NkColor cursor_border_color() { return ncursor_border_color(address()); }
/** Returns the value of the {@code border} field. */
public float border() { return nborder(address()); }
/** Returns the value of the {@code rounding} field. */
public float rounding() { return nrounding(address()); }
/** Returns the value of the {@code border_cursor} field. */
public float border_cursor() { return nborder_cursor(address()); }
/** Returns the value of the {@code rounding_cursor} field. */
public float rounding_cursor() { return nrounding_cursor(address()); }
/** Returns a {@link NkVec2} view of the {@code padding} field. */
public NkVec2 padding() { return npadding(address()); }
/** Returns the value of the {@code show_buttons} field. */
public int show_buttons() { return nshow_buttons(address()); }
/** Returns a {@link NkStyleButton} view of the {@code inc_button} field. */
public NkStyleButton inc_button() { return ninc_button(address()); }
/** Returns a {@link NkStyleButton} view of the {@code dec_button} field. */
public NkStyleButton dec_button() { return ndec_button(address()); }
/** Returns the value of the {@code inc_symbol} field. */
public int inc_symbol() { return ninc_symbol(address()); }
/** Returns the value of the {@code dec_symbol} field. */
public int dec_symbol() { return ndec_symbol(address()); }
/** Returns a {@link NkHandle} view of the {@code userdata} field. */
public NkHandle userdata() { return nuserdata(address()); }
/** Returns the {@code NkDrawBeginCallback} instance at the {@code draw_begin} field. */
public NkDrawBeginCallback draw_begin() { return NkDrawBeginCallback.create(ndraw_begin(address())); }
/** Returns the {@code NkDrawEndCallback} instance at the {@code draw_end} field. */
public NkDrawEndCallback draw_end() { return NkDrawEndCallback.create(ndraw_end(address())); }
/** Copies the specified {@link NkStyleItem} to the {@code normal} field. */
public NkStyleScrollbar normal(NkStyleItem value) { nnormal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code hover} field. */
public NkStyleScrollbar hover(NkStyleItem value) { nhover(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code active} field. */
public NkStyleScrollbar active(NkStyleItem value) { nactive(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code border_color} field. */
public NkStyleScrollbar border_color(NkColor value) { nborder_color(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_normal} field. */
public NkStyleScrollbar cursor_normal(NkStyleItem value) { ncursor_normal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_hover} field. */
public NkStyleScrollbar cursor_hover(NkStyleItem value) { ncursor_hover(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_active} field. */
public NkStyleScrollbar cursor_active(NkStyleItem value) { ncursor_active(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code cursor_border_color} field. */
public NkStyleScrollbar cursor_border_color(NkColor value) { ncursor_border_color(address(), value); return this; }
/** Sets the specified value to the {@code border} field. */
public NkStyleScrollbar border(float value) { nborder(address(), value); return this; }
/** Sets the specified value to the {@code rounding} field. */
public NkStyleScrollbar rounding(float value) { nrounding(address(), value); return this; }
/** Sets the specified value to the {@code border_cursor} field. */
public NkStyleScrollbar border_cursor(float value) { nborder_cursor(address(), value); return this; }
/** Sets the specified value to the {@code rounding_cursor} field. */
public NkStyleScrollbar rounding_cursor(float value) { nrounding_cursor(address(), value); return this; }
/** Copies the specified {@link NkVec2} to the {@code padding} field. */
public NkStyleScrollbar padding(NkVec2 value) { npadding(address(), value); return this; }
/** Sets the specified value to the {@code show_buttons} field. */
public NkStyleScrollbar show_buttons(int value) { nshow_buttons(address(), value); return this; }
/** Copies the specified {@link NkStyleButton} to the {@code inc_button} field. */
public NkStyleScrollbar inc_button(NkStyleButton value) { ninc_button(address(), value); return this; }
/** Copies the specified {@link NkStyleButton} to the {@code dec_button} field. */
public NkStyleScrollbar dec_button(NkStyleButton value) { ndec_button(address(), value); return this; }
/** Sets the specified value to the {@code inc_symbol} field. */
public NkStyleScrollbar inc_symbol(int value) { ninc_symbol(address(), value); return this; }
/** Sets the specified value to the {@code dec_symbol} field. */
public NkStyleScrollbar dec_symbol(int value) { ndec_symbol(address(), value); return this; }
/** Copies the specified {@link NkHandle} to the {@code userdata} field. */
public NkStyleScrollbar userdata(NkHandle value) { nuserdata(address(), value); return this; }
/** Sets the address of the specified {@link NkDrawBeginCallbackI} to the {@code draw_begin} field. */
public NkStyleScrollbar draw_begin(NkDrawBeginCallbackI value) { ndraw_begin(address(), addressSafe(value)); return this; }
/** Sets the address of the specified {@link NkDrawEndCallbackI} to the {@code draw_end} field. */
public NkStyleScrollbar draw_end(NkDrawEndCallbackI value) { ndraw_end(address(), addressSafe(value)); return this; }
/** Unsafe version of {@link #set(NkStyleScrollbar) set}. */
public NkStyleScrollbar nset(long struct) {
memCopy(struct, address(), SIZEOF);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public NkStyleScrollbar set(NkStyleScrollbar src) {
return nset(src.address());
}
// -----------------------------------
/** Returns a new {@link NkStyleScrollbar} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static NkStyleScrollbar malloc() {
return create(nmemAlloc(SIZEOF));
}
/** Returns a new {@link NkStyleScrollbar} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static NkStyleScrollbar calloc() {
return create(nmemCalloc(1, SIZEOF));
}
/** Returns a new {@link NkStyleScrollbar} instance allocated with {@link BufferUtils}. */
public static NkStyleScrollbar create() {
return new NkStyleScrollbar(BufferUtils.createByteBuffer(SIZEOF));
}
/** Returns a new {@link NkStyleScrollbar} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
public static NkStyleScrollbar create(long address) {
return address == NULL ? null : new NkStyleScrollbar(address, null);
}
/**
* Returns a new {@link NkStyleScrollbar.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer malloc(int capacity) {
return create(nmemAlloc(capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link NkStyleScrollbar.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer calloc(int capacity) {
return create(nmemCalloc(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link NkStyleScrollbar.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static Buffer create(int capacity) {
return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF));
}
/**
* Create a {@link NkStyleScrollbar.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static Buffer create(long address, int capacity) {
return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
}
// -----------------------------------
/** Returns a new {@link NkStyleScrollbar} instance allocated on the thread-local {@link MemoryStack}. */
public static NkStyleScrollbar mallocStack() {
return mallocStack(stackGet());
}
/** Returns a new {@link NkStyleScrollbar} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
public static NkStyleScrollbar callocStack() {
return callocStack(stackGet());
}
/**
* Returns a new {@link NkStyleScrollbar} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static NkStyleScrollbar mallocStack(MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@link NkStyleScrollbar} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static NkStyleScrollbar callocStack(MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link NkStyleScrollbar.Buffer} instance allocated on the thread-local {@link MemoryStack}.
*
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity) {
return mallocStack(capacity, stackGet());
}
/**
* Returns a new {@link NkStyleScrollbar.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
*
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity) {
return callocStack(capacity, stackGet());
}
/**
* Returns a new {@link NkStyleScrollbar.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity, MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link NkStyleScrollbar.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity, MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #normal}. */
public static NkStyleItem nnormal(long struct) { return NkStyleItem.create(struct + NkStyleScrollbar.NORMAL); }
/** Unsafe version of {@link #hover}. */
public static NkStyleItem nhover(long struct) { return NkStyleItem.create(struct + NkStyleScrollbar.HOVER); }
/** Unsafe version of {@link #active}. */
public static NkStyleItem nactive(long struct) { return NkStyleItem.create(struct + NkStyleScrollbar.ACTIVE); }
/** Unsafe version of {@link #border_color}. */
public static NkColor nborder_color(long struct) { return NkColor.create(struct + NkStyleScrollbar.BORDER_COLOR); }
/** Unsafe version of {@link #cursor_normal}. */
public static NkStyleItem ncursor_normal(long struct) { return NkStyleItem.create(struct + NkStyleScrollbar.CURSOR_NORMAL); }
/** Unsafe version of {@link #cursor_hover}. */
public static NkStyleItem ncursor_hover(long struct) { return NkStyleItem.create(struct + NkStyleScrollbar.CURSOR_HOVER); }
/** Unsafe version of {@link #cursor_active}. */
public static NkStyleItem ncursor_active(long struct) { return NkStyleItem.create(struct + NkStyleScrollbar.CURSOR_ACTIVE); }
/** Unsafe version of {@link #cursor_border_color}. */
public static NkColor ncursor_border_color(long struct) { return NkColor.create(struct + NkStyleScrollbar.CURSOR_BORDER_COLOR); }
/** Unsafe version of {@link #border}. */
public static float nborder(long struct) { return memGetFloat(struct + NkStyleScrollbar.BORDER); }
/** Unsafe version of {@link #rounding}. */
public static float nrounding(long struct) { return memGetFloat(struct + NkStyleScrollbar.ROUNDING); }
/** Unsafe version of {@link #border_cursor}. */
public static float nborder_cursor(long struct) { return memGetFloat(struct + NkStyleScrollbar.BORDER_CURSOR); }
/** Unsafe version of {@link #rounding_cursor}. */
public static float nrounding_cursor(long struct) { return memGetFloat(struct + NkStyleScrollbar.ROUNDING_CURSOR); }
/** Unsafe version of {@link #padding}. */
public static NkVec2 npadding(long struct) { return NkVec2.create(struct + NkStyleScrollbar.PADDING); }
/** Unsafe version of {@link #show_buttons}. */
public static int nshow_buttons(long struct) { return memGetInt(struct + NkStyleScrollbar.SHOW_BUTTONS); }
/** Unsafe version of {@link #inc_button}. */
public static NkStyleButton ninc_button(long struct) { return NkStyleButton.create(struct + NkStyleScrollbar.INC_BUTTON); }
/** Unsafe version of {@link #dec_button}. */
public static NkStyleButton ndec_button(long struct) { return NkStyleButton.create(struct + NkStyleScrollbar.DEC_BUTTON); }
/** Unsafe version of {@link #inc_symbol}. */
public static int ninc_symbol(long struct) { return memGetInt(struct + NkStyleScrollbar.INC_SYMBOL); }
/** Unsafe version of {@link #dec_symbol}. */
public static int ndec_symbol(long struct) { return memGetInt(struct + NkStyleScrollbar.DEC_SYMBOL); }
/** Unsafe version of {@link #userdata}. */
public static NkHandle nuserdata(long struct) { return NkHandle.create(struct + NkStyleScrollbar.USERDATA); }
/** Unsafe version of {@link #draw_begin}. */
public static long ndraw_begin(long struct) { return memGetAddress(struct + NkStyleScrollbar.DRAW_BEGIN); }
/** Unsafe version of {@link #draw_end}. */
public static long ndraw_end(long struct) { return memGetAddress(struct + NkStyleScrollbar.DRAW_END); }
/** Unsafe version of {@link #normal(NkStyleItem) normal}. */
public static void nnormal(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleScrollbar.NORMAL, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #hover(NkStyleItem) hover}. */
public static void nhover(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleScrollbar.HOVER, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #active(NkStyleItem) active}. */
public static void nactive(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleScrollbar.ACTIVE, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #border_color(NkColor) border_color}. */
public static void nborder_color(long struct, NkColor value) { memCopy(value.address(), struct + NkStyleScrollbar.BORDER_COLOR, NkColor.SIZEOF); }
/** Unsafe version of {@link #cursor_normal(NkStyleItem) cursor_normal}. */
public static void ncursor_normal(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleScrollbar.CURSOR_NORMAL, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #cursor_hover(NkStyleItem) cursor_hover}. */
public static void ncursor_hover(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleScrollbar.CURSOR_HOVER, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #cursor_active(NkStyleItem) cursor_active}. */
public static void ncursor_active(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleScrollbar.CURSOR_ACTIVE, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #cursor_border_color(NkColor) cursor_border_color}. */
public static void ncursor_border_color(long struct, NkColor value) { memCopy(value.address(), struct + NkStyleScrollbar.CURSOR_BORDER_COLOR, NkColor.SIZEOF); }
/** Unsafe version of {@link #border(float) border}. */
public static void nborder(long struct, float value) { memPutFloat(struct + NkStyleScrollbar.BORDER, value); }
/** Unsafe version of {@link #rounding(float) rounding}. */
public static void nrounding(long struct, float value) { memPutFloat(struct + NkStyleScrollbar.ROUNDING, value); }
/** Unsafe version of {@link #border_cursor(float) border_cursor}. */
public static void nborder_cursor(long struct, float value) { memPutFloat(struct + NkStyleScrollbar.BORDER_CURSOR, value); }
/** Unsafe version of {@link #rounding_cursor(float) rounding_cursor}. */
public static void nrounding_cursor(long struct, float value) { memPutFloat(struct + NkStyleScrollbar.ROUNDING_CURSOR, value); }
/** Unsafe version of {@link #padding(NkVec2) padding}. */
public static void npadding(long struct, NkVec2 value) { memCopy(value.address(), struct + NkStyleScrollbar.PADDING, NkVec2.SIZEOF); }
/** Unsafe version of {@link #show_buttons(int) show_buttons}. */
public static void nshow_buttons(long struct, int value) { memPutInt(struct + NkStyleScrollbar.SHOW_BUTTONS, value); }
/** Unsafe version of {@link #inc_button(NkStyleButton) inc_button}. */
public static void ninc_button(long struct, NkStyleButton value) { memCopy(value.address(), struct + NkStyleScrollbar.INC_BUTTON, NkStyleButton.SIZEOF); }
/** Unsafe version of {@link #dec_button(NkStyleButton) dec_button}. */
public static void ndec_button(long struct, NkStyleButton value) { memCopy(value.address(), struct + NkStyleScrollbar.DEC_BUTTON, NkStyleButton.SIZEOF); }
/** Unsafe version of {@link #inc_symbol(int) inc_symbol}. */
public static void ninc_symbol(long struct, int value) { memPutInt(struct + NkStyleScrollbar.INC_SYMBOL, value); }
/** Unsafe version of {@link #dec_symbol(int) dec_symbol}. */
public static void ndec_symbol(long struct, int value) { memPutInt(struct + NkStyleScrollbar.DEC_SYMBOL, value); }
/** Unsafe version of {@link #userdata(NkHandle) userdata}. */
public static void nuserdata(long struct, NkHandle value) { memCopy(value.address(), struct + NkStyleScrollbar.USERDATA, NkHandle.SIZEOF); }
/** Unsafe version of {@link #draw_begin(NkDrawBeginCallbackI) draw_begin}. */
public static void ndraw_begin(long struct, long value) { memPutAddress(struct + NkStyleScrollbar.DRAW_BEGIN, value); }
/** Unsafe version of {@link #draw_end(NkDrawEndCallbackI) draw_end}. */
public static void ndraw_end(long struct, long value) { memPutAddress(struct + NkStyleScrollbar.DRAW_END, value); }
// -----------------------------------
/** An array of {@link NkStyleScrollbar} structs. */
public static class Buffer extends StructBuffer<NkStyleScrollbar, Buffer> implements NativeResource {
/**
* Creates a new {@link NkStyleScrollbar.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link NkStyleScrollbar#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
return new Buffer(address, container, mark, pos, lim, cap);
}
@Override
protected NkStyleScrollbar newInstance(long address) {
return new NkStyleScrollbar(address, container);
}
@Override
protected int sizeof() {
return SIZEOF;
}
/** Returns a {@link NkStyleItem} view of the {@code normal} field. */
public NkStyleItem normal() { return NkStyleScrollbar.nnormal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code hover} field. */
public NkStyleItem hover() { return NkStyleScrollbar.nhover(address()); }
/** Returns a {@link NkStyleItem} view of the {@code active} field. */
public NkStyleItem active() { return NkStyleScrollbar.nactive(address()); }
/** Returns a {@link NkColor} view of the {@code border_color} field. */
public NkColor border_color() { return NkStyleScrollbar.nborder_color(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_normal} field. */
public NkStyleItem cursor_normal() { return NkStyleScrollbar.ncursor_normal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_hover} field. */
public NkStyleItem cursor_hover() { return NkStyleScrollbar.ncursor_hover(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_active} field. */
public NkStyleItem cursor_active() { return NkStyleScrollbar.ncursor_active(address()); }
/** Returns a {@link NkColor} view of the {@code cursor_border_color} field. */
public NkColor cursor_border_color() { return NkStyleScrollbar.ncursor_border_color(address()); }
/** Returns the value of the {@code border} field. */
public float border() { return NkStyleScrollbar.nborder(address()); }
/** Returns the value of the {@code rounding} field. */
public float rounding() { return NkStyleScrollbar.nrounding(address()); }
/** Returns the value of the {@code border_cursor} field. */
public float border_cursor() { return NkStyleScrollbar.nborder_cursor(address()); }
/** Returns the value of the {@code rounding_cursor} field. */
public float rounding_cursor() { return NkStyleScrollbar.nrounding_cursor(address()); }
/** Returns a {@link NkVec2} view of the {@code padding} field. */
public NkVec2 padding() { return NkStyleScrollbar.npadding(address()); }
/** Returns the value of the {@code show_buttons} field. */
public int show_buttons() { return NkStyleScrollbar.nshow_buttons(address()); }
/** Returns a {@link NkStyleButton} view of the {@code inc_button} field. */
public NkStyleButton inc_button() { return NkStyleScrollbar.ninc_button(address()); }
/** Returns a {@link NkStyleButton} view of the {@code dec_button} field. */
public NkStyleButton dec_button() { return NkStyleScrollbar.ndec_button(address()); }
/** Returns the value of the {@code inc_symbol} field. */
public int inc_symbol() { return NkStyleScrollbar.ninc_symbol(address()); }
/** Returns the value of the {@code dec_symbol} field. */
public int dec_symbol() { return NkStyleScrollbar.ndec_symbol(address()); }
/** Returns a {@link NkHandle} view of the {@code userdata} field. */
public NkHandle userdata() { return NkStyleScrollbar.nuserdata(address()); }
/** Returns the {@code NkDrawBeginCallback} instance at the {@code draw_begin} field. */
public NkDrawBeginCallback draw_begin() { return NkDrawBeginCallback.create(NkStyleScrollbar.ndraw_begin(address())); }
/** Returns the {@code NkDrawEndCallback} instance at the {@code draw_end} field. */
public NkDrawEndCallback draw_end() { return NkDrawEndCallback.create(NkStyleScrollbar.ndraw_end(address())); }
/** Copies the specified {@link NkStyleItem} to the {@code normal} field. */
public NkStyleScrollbar.Buffer normal(NkStyleItem value) { NkStyleScrollbar.nnormal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code hover} field. */
public NkStyleScrollbar.Buffer hover(NkStyleItem value) { NkStyleScrollbar.nhover(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code active} field. */
public NkStyleScrollbar.Buffer active(NkStyleItem value) { NkStyleScrollbar.nactive(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code border_color} field. */
public NkStyleScrollbar.Buffer border_color(NkColor value) { NkStyleScrollbar.nborder_color(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_normal} field. */
public NkStyleScrollbar.Buffer cursor_normal(NkStyleItem value) { NkStyleScrollbar.ncursor_normal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_hover} field. */
public NkStyleScrollbar.Buffer cursor_hover(NkStyleItem value) { NkStyleScrollbar.ncursor_hover(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_active} field. */
public NkStyleScrollbar.Buffer cursor_active(NkStyleItem value) { NkStyleScrollbar.ncursor_active(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code cursor_border_color} field. */
public NkStyleScrollbar.Buffer cursor_border_color(NkColor value) { NkStyleScrollbar.ncursor_border_color(address(), value); return this; }
/** Sets the specified value to the {@code border} field. */
public NkStyleScrollbar.Buffer border(float value) { NkStyleScrollbar.nborder(address(), value); return this; }
/** Sets the specified value to the {@code rounding} field. */
public NkStyleScrollbar.Buffer rounding(float value) { NkStyleScrollbar.nrounding(address(), value); return this; }
/** Sets the specified value to the {@code border_cursor} field. */
public NkStyleScrollbar.Buffer border_cursor(float value) { NkStyleScrollbar.nborder_cursor(address(), value); return this; }
/** Sets the specified value to the {@code rounding_cursor} field. */
public NkStyleScrollbar.Buffer rounding_cursor(float value) { NkStyleScrollbar.nrounding_cursor(address(), value); return this; }
/** Copies the specified {@link NkVec2} to the {@code padding} field. */
public NkStyleScrollbar.Buffer padding(NkVec2 value) { NkStyleScrollbar.npadding(address(), value); return this; }
/** Sets the specified value to the {@code show_buttons} field. */
public NkStyleScrollbar.Buffer show_buttons(int value) { NkStyleScrollbar.nshow_buttons(address(), value); return this; }
/** Copies the specified {@link NkStyleButton} to the {@code inc_button} field. */
public NkStyleScrollbar.Buffer inc_button(NkStyleButton value) { NkStyleScrollbar.ninc_button(address(), value); return this; }
/** Copies the specified {@link NkStyleButton} to the {@code dec_button} field. */
public NkStyleScrollbar.Buffer dec_button(NkStyleButton value) { NkStyleScrollbar.ndec_button(address(), value); return this; }
/** Sets the specified value to the {@code inc_symbol} field. */
public NkStyleScrollbar.Buffer inc_symbol(int value) { NkStyleScrollbar.ninc_symbol(address(), value); return this; }
/** Sets the specified value to the {@code dec_symbol} field. */
public NkStyleScrollbar.Buffer dec_symbol(int value) { NkStyleScrollbar.ndec_symbol(address(), value); return this; }
/** Copies the specified {@link NkHandle} to the {@code userdata} field. */
public NkStyleScrollbar.Buffer userdata(NkHandle value) { NkStyleScrollbar.nuserdata(address(), value); return this; }
/** Sets the address of the specified {@link NkDrawBeginCallbackI} to the {@code draw_begin} field. */
public NkStyleScrollbar.Buffer draw_begin(NkDrawBeginCallbackI value) { NkStyleScrollbar.ndraw_begin(address(), addressSafe(value)); return this; }
/** Sets the address of the specified {@link NkDrawEndCallbackI} to the {@code draw_end} field. */
public NkStyleScrollbar.Buffer draw_end(NkDrawEndCallbackI value) { NkStyleScrollbar.ndraw_end(address(), addressSafe(value)); return this; }
}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.system.jemalloc;
/** Macros for jemalloc. */
public final class JEmacros {
private JEmacros() {}
/** The major version. */
public static final int JEMALLOC_VERSION_MAJOR = 4;
/** The minor version. */
public static final int JEMALLOC_VERSION_MINOR = 2;
/** The bugfix version. */
public static final int JEMALLOC_VERSION_BUGFIX = 1;
/** Tthe revision number. */
public static final int JEMALLOC_VERSION_NREV = 0;
/** The globally unique identifier (git commit hash). */
public static final String JEMALLOC_VERSION_GID = "3de035335255d553bdb344c32ffdb603816195d8";
/** Returns the version string. */
public static final String JEMALLOC_VERSION =
JEMALLOC_VERSION_MAJOR + "." + JEMALLOC_VERSION_MINOR + "." + JEMALLOC_VERSION_BUGFIX + "-" + JEMALLOC_VERSION_NREV + "-g" + JEMALLOC_VERSION_GID;
/**
* Align the memory allocation to start at an address that is a multiple of {@code (1 << la)}. This macro does not validate that {@code la} is within the
* valid range.
*
* @param la the alignment shift
*/
public static int MALLOCX_LG_ALIGN(int la) {
return la;
}
/**
* Align the memory allocation to start at an address that is a multiple of {@code a}, where {@code a} is a power of two. This macro does not validate
* that {@code a} is a power of 2.
*
* @param a the alignment
*/
public static int MALLOCX_ALIGN(int a) {
return Integer.numberOfTrailingZeros(a);
}
/**
* Initialize newly allocated memory to contain zero bytes. In the growing reallocation case, the real size prior to reallocation defines the boundary
* between untouched bytes and those that are initialized to contain zero bytes. If this macro is absent, newly allocated memory is uninitialized.
*/
public static final int MALLOCX_ZERO = 0x40;
/**
* Use the thread-specific cache (tcache) specified by the identifier {@code tc}, which must have been acquired via the {@code tcache.create} mallctl.
* This macro does not validate that {@code tc} specifies a valid identifier.
*
* @param tc the thread-specific cache
*/
public static int MALLOCX_TCACHE(int tc) {
return (tc + 2) << 8;
}
/**
* Do not use a thread-specific cache (tcache). Unless {@link #MALLOCX_TCACHE} or {@code MALLOCX_TCACHE_NONE} is specified, an automatically managed
* tcache
* will be used under many circumstances. This macro cannot be used in the same {@code flags} argument as {@code MALLOCX_TCACHE(tc)}.
*/
public static final int MALLOCX_TCACHE_NONE = MALLOCX_TCACHE(-1);
/**
* Use the arena specified by the index {@code a} (and by necessity bypass the thread cache). This macro has no effect for huge regions, nor for regions
* that were allocated via an arena other than the one specified. This macro does not validate that {@code a} specifies an arena index in the valid range.
*
* @param a the arena index
*/
public static int MALLOCX_ARENA(int a) {
return (a + 1) << 20;
}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4701 4702 4711 4738))
#endif
#include "lwjgl_malloc.h"
#define STBI_MALLOC(sz) org_lwjgl_malloc(sz)
#define STBI_REALLOC(p,sz) org_lwjgl_realloc(p,sz)
#define STBI_FREE(p) org_lwjgl_free(p)
#define STBI_FAILURE_USERMSG
#define STBI_ASSERT(x)
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#include "stb_image.h"
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1load__JJJJI(JNIEnv *__env, jclass clazz, jlong filenameAddress, jlong xAddress, jlong yAddress, jlong compAddress, jint req_comp) {
const char *filename = (const char *)(intptr_t)filenameAddress;
int *x = (int *)(intptr_t)xAddress;
int *y = (int *)(intptr_t)yAddress;
int *comp = (int *)(intptr_t)compAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_load(filename, x, y, comp, req_comp);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1load_1from_1memory__JIJJJI(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len, jlong xAddress, jlong yAddress, jlong compAddress, jint req_comp) {
const stbi_uc *buffer = (const stbi_uc *)(intptr_t)bufferAddress;
int *x = (int *)(intptr_t)xAddress;
int *y = (int *)(intptr_t)yAddress;
int *comp = (int *)(intptr_t)compAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_load_from_memory(buffer, len, x, y, comp, req_comp);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1load_1from_1callbacks__JJJJJI(JNIEnv *__env, jclass clazz, jlong clbkAddress, jlong userAddress, jlong xAddress, jlong yAddress, jlong compAddress, jint req_comp) {
const stbi_io_callbacks *clbk = (const stbi_io_callbacks *)(intptr_t)clbkAddress;
void *user = (void *)(intptr_t)userAddress;
int *x = (int *)(intptr_t)xAddress;
int *y = (int *)(intptr_t)yAddress;
int *comp = (int *)(intptr_t)compAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_load_from_callbacks(clbk, user, x, y, comp, req_comp);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1loadf__JJJJI(JNIEnv *__env, jclass clazz, jlong filenameAddress, jlong xAddress, jlong yAddress, jlong compAddress, jint req_comp) {
const char *filename = (const char *)(intptr_t)filenameAddress;
int *x = (int *)(intptr_t)xAddress;
int *y = (int *)(intptr_t)yAddress;
int *comp = (int *)(intptr_t)compAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_loadf(filename, x, y, comp, req_comp);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1loadf_1from_1memory__JIJJJI(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len, jlong xAddress, jlong yAddress, jlong compAddress, jint req_comp) {
const stbi_uc *buffer = (const stbi_uc *)(intptr_t)bufferAddress;
int *x = (int *)(intptr_t)xAddress;
int *y = (int *)(intptr_t)yAddress;
int *comp = (int *)(intptr_t)compAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_loadf_from_memory(buffer, len, x, y, comp, req_comp);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1loadf_1from_1callbacks__JJJJJI(JNIEnv *__env, jclass clazz, jlong clbkAddress, jlong userAddress, jlong xAddress, jlong yAddress, jlong compAddress, jint req_comp) {
const stbi_io_callbacks *clbk = (const stbi_io_callbacks *)(intptr_t)clbkAddress;
void *user = (void *)(intptr_t)userAddress;
int *x = (int *)(intptr_t)xAddress;
int *y = (int *)(intptr_t)yAddress;
int *comp = (int *)(intptr_t)compAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_loadf_from_callbacks(clbk, user, x, y, comp, req_comp);
}
JNIEXPORT void JNICALL Java_org_lwjgl_stb_STBImage_stbi_1hdr_1to_1ldr_1gamma(JNIEnv *__env, jclass clazz, jfloat gamma) {
UNUSED_PARAMS(__env, clazz)
stbi_hdr_to_ldr_gamma(gamma);
}
JNIEXPORT void JNICALL Java_org_lwjgl_stb_STBImage_stbi_1hdr_1to_1ldr_1scale(JNIEnv *__env, jclass clazz, jfloat scale) {
UNUSED_PARAMS(__env, clazz)
stbi_hdr_to_ldr_scale(scale);
}
JNIEXPORT void JNICALL Java_org_lwjgl_stb_STBImage_stbi_1ldr_1to_1hdr_1gamma(JNIEnv *__env, jclass clazz, jfloat gamma) {
UNUSED_PARAMS(__env, clazz)
stbi_ldr_to_hdr_gamma(gamma);
}
JNIEXPORT void JNICALL Java_org_lwjgl_stb_STBImage_stbi_1ldr_1to_1hdr_1scale(JNIEnv *__env, jclass clazz, jfloat scale) {
UNUSED_PARAMS(__env, clazz)
stbi_ldr_to_hdr_scale(scale);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1is_1hdr(JNIEnv *__env, jclass clazz, jlong filenameAddress) {
const char *filename = (const char *)(intptr_t)filenameAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_is_hdr(filename);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1is_1hdr_1from_1memory(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len) {
const stbi_uc *buffer = (const stbi_uc *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_is_hdr_from_memory(buffer, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1is_1hdr_1from_1callbacks(JNIEnv *__env, jclass clazz, jlong clbkAddress, jlong userAddress) {
const stbi_io_callbacks *clbk = (const stbi_io_callbacks *)(intptr_t)clbkAddress;
void *user = (void *)(intptr_t)userAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_is_hdr_from_callbacks(clbk, user);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1failure_1reason(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_failure_reason();
}
JNIEXPORT void JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1image_1free(JNIEnv *__env, jclass clazz, jlong retval_from_stbi_loadAddress) {
void *retval_from_stbi_load = (void *)(intptr_t)retval_from_stbi_loadAddress;
UNUSED_PARAMS(__env, clazz)
stbi_image_free(retval_from_stbi_load);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1info__JJJJ(JNIEnv *__env, jclass clazz, jlong filenameAddress, jlong xAddress, jlong yAddress, jlong compAddress) {
const char *filename = (const char *)(intptr_t)filenameAddress;
int *x = (int *)(intptr_t)xAddress;
int *y = (int *)(intptr_t)yAddress;
int *comp = (int *)(intptr_t)compAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_info(filename, x, y, comp);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1info_1from_1memory__JIJJJ(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len, jlong xAddress, jlong yAddress, jlong compAddress) {
const stbi_uc *buffer = (const stbi_uc *)(intptr_t)bufferAddress;
int *x = (int *)(intptr_t)xAddress;
int *y = (int *)(intptr_t)yAddress;
int *comp = (int *)(intptr_t)compAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_info_from_memory(buffer, len, x, y, comp);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1info_1from_1callbacks__JJJJJ(JNIEnv *__env, jclass clazz, jlong clbkAddress, jlong userAddress, jlong xAddress, jlong yAddress, jlong compAddress) {
const stbi_io_callbacks *clbk = (const stbi_io_callbacks *)(intptr_t)clbkAddress;
void *user = (void *)(intptr_t)userAddress;
int *x = (int *)(intptr_t)xAddress;
int *y = (int *)(intptr_t)yAddress;
int *comp = (int *)(intptr_t)compAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_info_from_callbacks(clbk, user, x, y, comp);
}
JNIEXPORT void JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1set_1unpremultiply_1on_1load(JNIEnv *__env, jclass clazz, jint flag_true_if_should_unpremultiply) {
UNUSED_PARAMS(__env, clazz)
stbi_set_unpremultiply_on_load(flag_true_if_should_unpremultiply);
}
JNIEXPORT void JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1convert_1iphone_1png_1to_1rgb(JNIEnv *__env, jclass clazz, jint flag_true_if_should_convert) {
UNUSED_PARAMS(__env, clazz)
stbi_convert_iphone_png_to_rgb(flag_true_if_should_convert);
}
JNIEXPORT void JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1set_1flip_1vertically_1on_1load(JNIEnv *__env, jclass clazz, jint flag_true_if_should_flip) {
UNUSED_PARAMS(__env, clazz)
stbi_set_flip_vertically_on_load(flag_true_if_should_flip);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1zlib_1decode_1malloc_1guesssize(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len, jint initial_size, jlong outlenAddress) {
const char *buffer = (const char *)(intptr_t)bufferAddress;
int *outlen = (int *)(intptr_t)outlenAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_zlib_decode_malloc_guesssize(buffer, len, initial_size, outlen);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1zlib_1decode_1malloc_1guesssize_1headerflag(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len, jint initial_size, jlong outlenAddress, jint parse_header) {
const char *buffer = (const char *)(intptr_t)bufferAddress;
int *outlen = (int *)(intptr_t)outlenAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_zlib_decode_malloc_guesssize_headerflag(buffer, len, initial_size, outlen, parse_header);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1zlib_1decode_1malloc(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len, jlong outlenAddress) {
const char *buffer = (const char *)(intptr_t)bufferAddress;
int *outlen = (int *)(intptr_t)outlenAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_zlib_decode_malloc(buffer, len, outlen);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1zlib_1decode_1buffer(JNIEnv *__env, jclass clazz, jlong obufferAddress, jint olen, jlong ibufferAddress, jint ilen) {
char *obuffer = (char *)(intptr_t)obufferAddress;
const char *ibuffer = (const char *)(intptr_t)ibufferAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_zlib_decode_buffer(obuffer, olen, ibuffer, ilen);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1zlib_1decode_1noheader_1malloc(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len, jlong outlenAddress) {
const char *buffer = (const char *)(intptr_t)bufferAddress;
int *outlen = (int *)(intptr_t)outlenAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)stbi_zlib_decode_noheader_malloc(buffer, len, outlen);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1zlib_1decode_1noheader_1buffer(JNIEnv *__env, jclass clazz, jlong obufferAddress, jint olen, jlong ibufferAddress, jint ilen) {
char *obuffer = (char *)(intptr_t)obufferAddress;
const char *ibuffer = (const char *)(intptr_t)ibufferAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)stbi_zlib_decode_noheader_buffer(obuffer, olen, ibuffer, ilen);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1load__J_3I_3I_3II(JNIEnv *__env, jclass clazz, jlong filenameAddress, jintArray xAddress, jintArray yAddress, jintArray compAddress, jint req_comp) {
const char *filename = (const char *)(intptr_t)filenameAddress;
jlong __result;
jint *x = (*__env)->GetPrimitiveArrayCritical(__env, xAddress, 0);
jint *y = (*__env)->GetPrimitiveArrayCritical(__env, yAddress, 0);
jint *comp = (*__env)->GetPrimitiveArrayCritical(__env, compAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jlong)(intptr_t)stbi_load(filename, (int *)x, (int *)y, (int *)comp, req_comp);
(*__env)->ReleasePrimitiveArrayCritical(__env, compAddress, comp, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, yAddress, y, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, xAddress, x, 0);
return __result;
}
JNIEXPORT jlong JNICALL JavaCritical_org_lwjgl_stb_STBImage_nstbi_1load__J_3I_3I_3II(jlong filenameAddress, jint x__length, jint* x, jint y__length, jint* y, jint comp__length, jint* comp, jint req_comp) {
const char *filename = (const char *)(intptr_t)filenameAddress;
UNUSED_PARAM(x__length)
UNUSED_PARAM(y__length)
UNUSED_PARAM(comp__length)
return (jlong)(intptr_t)stbi_load(filename, (int *)x, (int *)y, (int *)comp, req_comp);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1load_1from_1memory__JI_3I_3I_3II(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len, jintArray xAddress, jintArray yAddress, jintArray compAddress, jint req_comp) {
const stbi_uc *buffer = (const stbi_uc *)(intptr_t)bufferAddress;
jlong __result;
jint *x = (*__env)->GetPrimitiveArrayCritical(__env, xAddress, 0);
jint *y = (*__env)->GetPrimitiveArrayCritical(__env, yAddress, 0);
jint *comp = (*__env)->GetPrimitiveArrayCritical(__env, compAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jlong)(intptr_t)stbi_load_from_memory(buffer, len, (int *)x, (int *)y, (int *)comp, req_comp);
(*__env)->ReleasePrimitiveArrayCritical(__env, compAddress, comp, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, yAddress, y, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, xAddress, x, 0);
return __result;
}
#ifdef LWJGL_WINDOWS
JNIEXPORT jlong JNICALL JavaCritical_org_lwjgl_stb_STBImage_nstbi_1load_1from_1memory__JI_3I_3I_3II(jlong bufferAddress, jint len, jint x__length, jint* x, jint y__length, jint* y, jint comp__length, jint* comp, jint req_comp) {
const stbi_uc *buffer = (const stbi_uc *)(intptr_t)bufferAddress;
UNUSED_PARAM(x__length)
UNUSED_PARAM(y__length)
UNUSED_PARAM(comp__length)
return (jlong)(intptr_t)stbi_load_from_memory(buffer, len, (int *)x, (int *)y, (int *)comp, req_comp);
}
#endif
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1load_1from_1callbacks__JJ_3I_3I_3II(JNIEnv *__env, jclass clazz, jlong clbkAddress, jlong userAddress, jintArray xAddress, jintArray yAddress, jintArray compAddress, jint req_comp) {
const stbi_io_callbacks *clbk = (const stbi_io_callbacks *)(intptr_t)clbkAddress;
void *user = (void *)(intptr_t)userAddress;
jlong __result;
jint *x = (*__env)->GetPrimitiveArrayCritical(__env, xAddress, 0);
jint *y = (*__env)->GetPrimitiveArrayCritical(__env, yAddress, 0);
jint *comp = (*__env)->GetPrimitiveArrayCritical(__env, compAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jlong)(intptr_t)stbi_load_from_callbacks(clbk, user, (int *)x, (int *)y, (int *)comp, req_comp);
(*__env)->ReleasePrimitiveArrayCritical(__env, compAddress, comp, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, yAddress, y, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, xAddress, x, 0);
return __result;
}
#ifdef LWJGL_WINDOWS
JNIEXPORT jlong JNICALL JavaCritical_org_lwjgl_stb_STBImage_nstbi_1load_1from_1callbacks__JJ_3I_3I_3II(jlong clbkAddress, jlong userAddress, jint x__length, jint* x, jint y__length, jint* y, jint comp__length, jint* comp, jint req_comp) {
const stbi_io_callbacks *clbk = (const stbi_io_callbacks *)(intptr_t)clbkAddress;
void *user = (void *)(intptr_t)userAddress;
UNUSED_PARAM(x__length)
UNUSED_PARAM(y__length)
UNUSED_PARAM(comp__length)
return (jlong)(intptr_t)stbi_load_from_callbacks(clbk, user, (int *)x, (int *)y, (int *)comp, req_comp);
}
#endif
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1loadf__J_3I_3I_3II(JNIEnv *__env, jclass clazz, jlong filenameAddress, jintArray xAddress, jintArray yAddress, jintArray compAddress, jint req_comp) {
const char *filename = (const char *)(intptr_t)filenameAddress;
jlong __result;
jint *x = (*__env)->GetPrimitiveArrayCritical(__env, xAddress, 0);
jint *y = (*__env)->GetPrimitiveArrayCritical(__env, yAddress, 0);
jint *comp = (*__env)->GetPrimitiveArrayCritical(__env, compAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jlong)(intptr_t)stbi_loadf(filename, (int *)x, (int *)y, (int *)comp, req_comp);
(*__env)->ReleasePrimitiveArrayCritical(__env, compAddress, comp, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, yAddress, y, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, xAddress, x, 0);
return __result;
}
JNIEXPORT jlong JNICALL JavaCritical_org_lwjgl_stb_STBImage_nstbi_1loadf__J_3I_3I_3II(jlong filenameAddress, jint x__length, jint* x, jint y__length, jint* y, jint comp__length, jint* comp, jint req_comp) {
const char *filename = (const char *)(intptr_t)filenameAddress;
UNUSED_PARAM(x__length)
UNUSED_PARAM(y__length)
UNUSED_PARAM(comp__length)
return (jlong)(intptr_t)stbi_loadf(filename, (int *)x, (int *)y, (int *)comp, req_comp);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1loadf_1from_1memory__JI_3I_3I_3II(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len, jintArray xAddress, jintArray yAddress, jintArray compAddress, jint req_comp) {
const stbi_uc *buffer = (const stbi_uc *)(intptr_t)bufferAddress;
jlong __result;
jint *x = (*__env)->GetPrimitiveArrayCritical(__env, xAddress, 0);
jint *y = (*__env)->GetPrimitiveArrayCritical(__env, yAddress, 0);
jint *comp = (*__env)->GetPrimitiveArrayCritical(__env, compAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jlong)(intptr_t)stbi_loadf_from_memory(buffer, len, (int *)x, (int *)y, (int *)comp, req_comp);
(*__env)->ReleasePrimitiveArrayCritical(__env, compAddress, comp, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, yAddress, y, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, xAddress, x, 0);
return __result;
}
#ifdef LWJGL_WINDOWS
JNIEXPORT jlong JNICALL JavaCritical_org_lwjgl_stb_STBImage_nstbi_1loadf_1from_1memory__JI_3I_3I_3II(jlong bufferAddress, jint len, jint x__length, jint* x, jint y__length, jint* y, jint comp__length, jint* comp, jint req_comp) {
const stbi_uc *buffer = (const stbi_uc *)(intptr_t)bufferAddress;
UNUSED_PARAM(x__length)
UNUSED_PARAM(y__length)
UNUSED_PARAM(comp__length)
return (jlong)(intptr_t)stbi_loadf_from_memory(buffer, len, (int *)x, (int *)y, (int *)comp, req_comp);
}
#endif
JNIEXPORT jlong JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1loadf_1from_1callbacks__JJ_3I_3I_3II(JNIEnv *__env, jclass clazz, jlong clbkAddress, jlong userAddress, jintArray xAddress, jintArray yAddress, jintArray compAddress, jint req_comp) {
const stbi_io_callbacks *clbk = (const stbi_io_callbacks *)(intptr_t)clbkAddress;
void *user = (void *)(intptr_t)userAddress;
jlong __result;
jint *x = (*__env)->GetPrimitiveArrayCritical(__env, xAddress, 0);
jint *y = (*__env)->GetPrimitiveArrayCritical(__env, yAddress, 0);
jint *comp = (*__env)->GetPrimitiveArrayCritical(__env, compAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jlong)(intptr_t)stbi_loadf_from_callbacks(clbk, user, (int *)x, (int *)y, (int *)comp, req_comp);
(*__env)->ReleasePrimitiveArrayCritical(__env, compAddress, comp, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, yAddress, y, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, xAddress, x, 0);
return __result;
}
#ifdef LWJGL_WINDOWS
JNIEXPORT jlong JNICALL JavaCritical_org_lwjgl_stb_STBImage_nstbi_1loadf_1from_1callbacks__JJ_3I_3I_3II(jlong clbkAddress, jlong userAddress, jint x__length, jint* x, jint y__length, jint* y, jint comp__length, jint* comp, jint req_comp) {
const stbi_io_callbacks *clbk = (const stbi_io_callbacks *)(intptr_t)clbkAddress;
void *user = (void *)(intptr_t)userAddress;
UNUSED_PARAM(x__length)
UNUSED_PARAM(y__length)
UNUSED_PARAM(comp__length)
return (jlong)(intptr_t)stbi_loadf_from_callbacks(clbk, user, (int *)x, (int *)y, (int *)comp, req_comp);
}
#endif
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1info__J_3I_3I_3I(JNIEnv *__env, jclass clazz, jlong filenameAddress, jintArray xAddress, jintArray yAddress, jintArray compAddress) {
const char *filename = (const char *)(intptr_t)filenameAddress;
jint __result;
jint *x = (*__env)->GetPrimitiveArrayCritical(__env, xAddress, 0);
jint *y = (*__env)->GetPrimitiveArrayCritical(__env, yAddress, 0);
jint *comp = (*__env)->GetPrimitiveArrayCritical(__env, compAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)stbi_info(filename, (int *)x, (int *)y, (int *)comp);
(*__env)->ReleasePrimitiveArrayCritical(__env, compAddress, comp, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, yAddress, y, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, xAddress, x, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_stb_STBImage_nstbi_1info__J_3I_3I_3I(jlong filenameAddress, jint x__length, jint* x, jint y__length, jint* y, jint comp__length, jint* comp) {
const char *filename = (const char *)(intptr_t)filenameAddress;
UNUSED_PARAM(x__length)
UNUSED_PARAM(y__length)
UNUSED_PARAM(comp__length)
return (jint)stbi_info(filename, (int *)x, (int *)y, (int *)comp);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1info_1from_1memory__JI_3I_3I_3I(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint len, jintArray xAddress, jintArray yAddress, jintArray compAddress) {
const stbi_uc *buffer = (const stbi_uc *)(intptr_t)bufferAddress;
jint __result;
jint *x = (*__env)->GetPrimitiveArrayCritical(__env, xAddress, 0);
jint *y = (*__env)->GetPrimitiveArrayCritical(__env, yAddress, 0);
jint *comp = (*__env)->GetPrimitiveArrayCritical(__env, compAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)stbi_info_from_memory(buffer, len, (int *)x, (int *)y, (int *)comp);
(*__env)->ReleasePrimitiveArrayCritical(__env, compAddress, comp, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, yAddress, y, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, xAddress, x, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_stb_STBImage_nstbi_1info_1from_1memory__JI_3I_3I_3I(jlong bufferAddress, jint len, jint x__length, jint* x, jint y__length, jint* y, jint comp__length, jint* comp) {
const stbi_uc *buffer = (const stbi_uc *)(intptr_t)bufferAddress;
UNUSED_PARAM(x__length)
UNUSED_PARAM(y__length)
UNUSED_PARAM(comp__length)
return (jint)stbi_info_from_memory(buffer, len, (int *)x, (int *)y, (int *)comp);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_stb_STBImage_nstbi_1info_1from_1callbacks__JJ_3I_3I_3I(JNIEnv *__env, jclass clazz, jlong clbkAddress, jlong userAddress, jintArray xAddress, jintArray yAddress, jintArray compAddress) {
const stbi_io_callbacks *clbk = (const stbi_io_callbacks *)(intptr_t)clbkAddress;
void *user = (void *)(intptr_t)userAddress;
jint __result;
jint *x = (*__env)->GetPrimitiveArrayCritical(__env, xAddress, 0);
jint *y = (*__env)->GetPrimitiveArrayCritical(__env, yAddress, 0);
jint *comp = (*__env)->GetPrimitiveArrayCritical(__env, compAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)stbi_info_from_callbacks(clbk, user, (int *)x, (int *)y, (int *)comp);
(*__env)->ReleasePrimitiveArrayCritical(__env, compAddress, comp, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, yAddress, y, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, xAddress, x, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_stb_STBImage_nstbi_1info_1from_1callbacks__JJ_3I_3I_3I(jlong clbkAddress, jlong userAddress, jint x__length, jint* x, jint y__length, jint* y, jint comp__length, jint* comp) {
const stbi_io_callbacks *clbk = (const stbi_io_callbacks *)(intptr_t)clbkAddress;
void *user = (void *)(intptr_t)userAddress;
UNUSED_PARAM(x__length)
UNUSED_PARAM(y__length)
UNUSED_PARAM(comp__length)
return (jint)stbi_info_from_callbacks(clbk, user, (int *)x, (int *)y, (int *)comp);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.nuklear;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
/** Instances of this class may be passed to the {@link #nk_combo_callback} and {@link #nk_combobox_callback} functions. */
public abstract class NkItemGetter extends Callback implements NkItemGetterI {
/** Creates a {@code NkItemGetter} instance from the specified function pointer. */
public static NkItemGetter create(long functionPointer) {
if ( functionPointer == NULL )
return null;
NkItemGetterI instance = Callback.get(functionPointer);
return instance instanceof NkItemGetter
? (NkItemGetter)instance
: new Container(functionPointer, instance);
}
/** Creates a {@code NkItemGetter} instance that delegates to the specified {@code NkItemGetterI} instance. */
public static NkItemGetter create(NkItemGetterI instance) {
return instance instanceof NkItemGetter
? (NkItemGetter)instance
: new Container(instance.address(), instance);
}
protected NkItemGetter() {
super(SIGNATURE);
}
private NkItemGetter(long functionPointer) {
super(functionPointer);
}
private static final class Container extends NkItemGetter {
private final NkItemGetterI delegate;
Container(long functionPointer, NkItemGetterI delegate) {
super(functionPointer);
this.delegate = delegate;
}
@Override
public float invoke(long userdata, int selected, long item) {
return delegate.invoke(userdata, selected, item);
}
}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#ifdef LWJGL_WINDOWS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "common_tools.h"
#include "lwjgl_malloc.h"
#include "nfd_common.h"
#include "nfd.h"
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4711))
#endif
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_org_lwjgl_util_nfd_NativeFileDialog_nNFD_1OpenDialog(JNIEnv *__env, jclass clazz, jlong filterListAddress, jlong defaultPathAddress, jlong outPathAddress) {
const nfdchar_t *filterList = (const nfdchar_t *)(intptr_t)filterListAddress;
const nfdchar_t *defaultPath = (const nfdchar_t *)(intptr_t)defaultPathAddress;
nfdchar_t **outPath = (nfdchar_t **)(intptr_t)outPathAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)NFD_OpenDialog(filterList, defaultPath, outPath);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_nfd_NativeFileDialog_nNFD_1OpenDialogMultiple(JNIEnv *__env, jclass clazz, jlong filterListAddress, jlong defaultPathAddress, jlong outPathsAddress) {
const nfdchar_t *filterList = (const nfdchar_t *)(intptr_t)filterListAddress;
const nfdchar_t *defaultPath = (const nfdchar_t *)(intptr_t)defaultPathAddress;
nfdpathset_t *outPaths = (nfdpathset_t *)(intptr_t)outPathsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)NFD_OpenDialogMultiple(filterList, defaultPath, outPaths);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_nfd_NativeFileDialog_nNFD_1SaveDialog(JNIEnv *__env, jclass clazz, jlong filterListAddress, jlong defaultPathAddress, jlong outPathAddress) {
const nfdchar_t *filterList = (const nfdchar_t *)(intptr_t)filterListAddress;
const nfdchar_t *defaultPath = (const nfdchar_t *)(intptr_t)defaultPathAddress;
nfdchar_t **outPath = (nfdchar_t **)(intptr_t)outPathAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)NFD_SaveDialog(filterList, defaultPath, outPath);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_nfd_NativeFileDialog_nNFD_1PickFolder(JNIEnv *__env, jclass clazz, jlong defaultPathAddress, jlong outPathAddress) {
const nfdchar_t *defaultPath = (const nfdchar_t *)(intptr_t)defaultPathAddress;
nfdchar_t **outPath = (nfdchar_t **)(intptr_t)outPathAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)NFD_PickFolder(defaultPath, outPath);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_nfd_NativeFileDialog_nNFD_1GetError(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)NFD_GetError();
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_nfd_NativeFileDialog_nNFD_1PathSet_1GetCount(JNIEnv *__env, jclass clazz, jlong pathSetAddress) {
const nfdpathset_t *pathSet = (const nfdpathset_t *)(intptr_t)pathSetAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)NFD_PathSet_GetCount(pathSet);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_nfd_NativeFileDialog_nNFD_1PathSet_1GetPath(JNIEnv *__env, jclass clazz, jlong pathSetAddress, jlong index) {
const nfdpathset_t *pathSet = (const nfdpathset_t *)(intptr_t)pathSetAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)NFD_PathSet_GetPath(pathSet, (size_t)index);
}
JNIEXPORT void JNICALL Java_org_lwjgl_util_nfd_NativeFileDialog_nNFD_1PathSet_1Free(JNIEnv *__env, jclass clazz, jlong pathSetAddress) {
nfdpathset_t *pathSet = (nfdpathset_t *)(intptr_t)pathSetAddress;
UNUSED_PARAMS(__env, clazz)
NFD_PathSet_Free(pathSet);
}
JNIEXPORT void JNICALL Java_org_lwjgl_util_nfd_NativeFileDialog_nNFDi_1Free(JNIEnv *__env, jclass clazz, jlong outPathAddress) {
void *outPath = (void *)(intptr_t)outPathAddress;
UNUSED_PARAMS(__env, clazz)
NFDi_Free(outPath);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* Custom allocator. When custom allocator is not specified, library uses default CRT allocator. The library assumes custom allocator is thread safe.
*
* <h3>Member documentation</h3>
*
* <ul>
* <li>{@code vtbl} – the allocator virtual table</li>
* </ul>
*
* <h3>Layout</h3>
*
* <pre><code>struct bgfx_allocator_interface_t {
const bgfx_allocator_vtbl_t * vtbl;
}</code></pre>
*/
public class BGFXAllocatorInterface extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
VTBL;
static {
Layout layout = __struct(
__member(POINTER_SIZE)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
VTBL = layout.offsetof(0);
}
BGFXAllocatorInterface(long address, ByteBuffer container) {
super(address, container);
}
/**
* Creates a {@link BGFXAllocatorInterface} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public BGFXAllocatorInterface(ByteBuffer container) {
this(memAddress(container), checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** Returns a {@link BGFXAllocatorVtbl} view of the struct pointed to by the {@code vtbl} field. */
public BGFXAllocatorVtbl vtbl() { return nvtbl(address()); }
/** Sets the address of the specified {@link BGFXAllocatorVtbl} to the {@code vtbl} field. */
public BGFXAllocatorInterface vtbl(BGFXAllocatorVtbl value) { nvtbl(address(), value); return this; }
/** Unsafe version of {@link #set(BGFXAllocatorInterface) set}. */
public BGFXAllocatorInterface nset(long struct) {
memCopy(struct, address(), SIZEOF);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public BGFXAllocatorInterface set(BGFXAllocatorInterface src) {
return nset(src.address());
}
// -----------------------------------
/** Returns a new {@link BGFXAllocatorInterface} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static BGFXAllocatorInterface malloc() {
return create(nmemAlloc(SIZEOF));
}
/** Returns a new {@link BGFXAllocatorInterface} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static BGFXAllocatorInterface calloc() {
return create(nmemCalloc(1, SIZEOF));
}
/** Returns a new {@link BGFXAllocatorInterface} instance allocated with {@link BufferUtils}. */
public static BGFXAllocatorInterface create() {
return new BGFXAllocatorInterface(BufferUtils.createByteBuffer(SIZEOF));
}
/** Returns a new {@link BGFXAllocatorInterface} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
public static BGFXAllocatorInterface create(long address) {
return address == NULL ? null : new BGFXAllocatorInterface(address, null);
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer malloc(int capacity) {
return create(nmemAlloc(capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer calloc(int capacity) {
return create(nmemCalloc(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static Buffer create(int capacity) {
return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF));
}
/**
* Create a {@link BGFXAllocatorInterface.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static Buffer create(long address, int capacity) {
return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
}
// -----------------------------------
/** Returns a new {@link BGFXAllocatorInterface} instance allocated on the thread-local {@link MemoryStack}. */
public static BGFXAllocatorInterface mallocStack() {
return mallocStack(stackGet());
}
/** Returns a new {@link BGFXAllocatorInterface} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
public static BGFXAllocatorInterface callocStack() {
return callocStack(stackGet());
}
/**
* Returns a new {@link BGFXAllocatorInterface} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static BGFXAllocatorInterface mallocStack(MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@link BGFXAllocatorInterface} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static BGFXAllocatorInterface callocStack(MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated on the thread-local {@link MemoryStack}.
*
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity) {
return mallocStack(capacity, stackGet());
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
*
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity) {
return callocStack(capacity, stackGet());
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity, MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity, MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #vtbl}. */
public static BGFXAllocatorVtbl nvtbl(long struct) { return BGFXAllocatorVtbl.create(memGetAddress(struct + BGFXAllocatorInterface.VTBL)); }
/** Unsafe version of {@link #vtbl(BGFXAllocatorVtbl) vtbl}. */
public static void nvtbl(long struct, BGFXAllocatorVtbl value) { memPutAddress(struct + BGFXAllocatorInterface.VTBL, value.address()); }
/**
* Validates pointer members that should not be {@code NULL}.
*
* @param struct the struct to validate
*/
public static void validate(long struct) {
long vtbl = memGetAddress(struct + BGFXAllocatorInterface.VTBL);
checkPointer(vtbl);
BGFXAllocatorVtbl.validate(vtbl);
}
/**
* Calls {@link #validate(long)} for each struct contained in the specified struct array.
*
* @param array the struct array to validate
* @param count the number of structs in {@code array}
*/
public static void validate(long array, int count) {
for ( int i = 0; i < count; i++ )
validate(array + i * SIZEOF);
}
// -----------------------------------
/** An array of {@link BGFXAllocatorInterface} structs. */
public static class Buffer extends StructBuffer<BGFXAllocatorInterface, Buffer> implements NativeResource {
/**
* Creates a new {@link BGFXAllocatorInterface.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link BGFXAllocatorInterface#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
return new Buffer(address, container, mark, pos, lim, cap);
}
@Override
protected BGFXAllocatorInterface newInstance(long address) {
return new BGFXAllocatorInterface(address, container);
}
@Override
protected int sizeof() {
return SIZEOF;
}
/** Returns a {@link BGFXAllocatorVtbl} view of the struct pointed to by the {@code vtbl} field. */
public BGFXAllocatorVtbl vtbl() { return BGFXAllocatorInterface.nvtbl(address()); }
/** Sets the address of the specified {@link BGFXAllocatorVtbl} to the {@code vtbl} field. */
public BGFXAllocatorInterface.Buffer vtbl(BGFXAllocatorVtbl value) { BGFXAllocatorInterface.nvtbl(address(), value); return this; }
}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.system.jemalloc;
import org.lwjgl.system.*;
import static org.lwjgl.system.dyncall.DynCallback.*;
/** Instances of this interface may be set to the {@link ChunkHooks} struct. */
@FunctionalInterface
public interface ChunkPurgeI extends CallbackI.Z {
String SIGNATURE = "(ppppi)B";
@Override
default String getSignature() { return SIGNATURE; }
@Override
default boolean callback(long args) {
return invoke(
dcbArgPointer(args),
dcbArgPointer(args),
dcbArgPointer(args),
dcbArgPointer(args),
dcbArgInt(args)
);
}
/**
* Chunk purge hook.
*
* @param chunk
* @param size
* @param offset
* @param length
* @param arena_ind
*/
boolean invoke(long chunk, long size, long offset, long length, int arena_ind);
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4710 4711))
#endif
#include "common_tools.h"
DISABLE_WARNINGS()
#define NANOVG_GL2_IMPLEMENTATION
#include "nanovg.h"
#include "nanovg_gl.h"
#include "nanovg_gl_utils.h"
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_org_lwjgl_nanovg_NanoVGGL2_nnvglCreateImageFromHandleGL2(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint textureId, jint w, jint h, jint flags) {
NVGcontext *ctx = (NVGcontext *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nvglCreateImageFromHandleGL2(ctx, textureId, w, h, flags);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nanovg_NanoVGGL2_nnvglImageHandleGL2(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint image) {
NVGcontext *ctx = (NVGcontext *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nvglImageHandleGL2(ctx, image);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nanovg_NanoVGGL2_nnvgCreateGL2(JNIEnv *__env, jclass clazz, jint flags) {
UNUSED_PARAM(clazz)
return (jlong)(intptr_t)nvgCreateGL2(__env, flags);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nanovg_NanoVGGL2_nnvgDeleteGL2(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
NVGcontext *ctx = (NVGcontext *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nvgDeleteGL2(ctx);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nanovg_NanoVGGL2_nnvgluCreateFramebufferGL2(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint w, jint h, jint imageFlags) {
NVGcontext *ctx = (NVGcontext *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nvgluCreateFramebufferGL2(ctx, w, h, imageFlags);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nanovg_NanoVGGL2_nnvgluBindFramebufferGL2(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong fbAddress) {
NVGcontext *ctx = (NVGcontext *)(intptr_t)ctxAddress;
NVGLUframebuffer *fb = (NVGLUframebuffer *)(intptr_t)fbAddress;
UNUSED_PARAMS(__env, clazz)
nvgluBindFramebufferGL2(ctx, fb);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nanovg_NanoVGGL2_nnvgluDeleteFramebufferGL2(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong fbAddress) {
NVGcontext *ctx = (NVGcontext *)(intptr_t)ctxAddress;
NVGLUframebuffer *fb = (NVGLUframebuffer *)(intptr_t)fbAddress;
UNUSED_PARAMS(__env, clazz)
nvgluDeleteFramebufferGL2(ctx, fb);
}
EXTERN_C_EXIT
<file_sep>LWJGL - Lightweight Java Game Library 3.0
======
This repo tracks the generated source code of the LWJGL 3 templates.<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* Renderer statistics data.
*
* <h3>Member documentation</h3>
*
* <ul>
* <li>{@code cpuTimeBegin} – CPU frame begin time</li>
* <li>{@code cpuTimeEnd} – CPU frame end time</li>
* <li>{@code cpuTimerFreq} – CPU timer frequency</li>
* <li>{@code gpuTimeBegin} – GPU frame begin time</li>
* <li>{@code gpuTimeEnd} – GPU frame end time</li>
* <li>{@code gpuTimerFreq} – GPU timer frequency</li>
* <li>{@code waitRender} – time spent waiting for render backend thread to finish issuing draw commands to underlying graphics API</li>
* <li>{@code waitSubmit} – time spent waiting for submit thread to advance to next frame</li>
* </ul>
*
* <h3>Layout</h3>
*
* <pre><code>struct bgfx_stats_t {
uint64_t cpuTimeBegin;
uint64_t cpuTimeEnd;
uint64_t cpuTimerFreq;
uint64_t gpuTimeBegin;
uint64_t gpuTimeEnd;
uint64_t gpuTimerFreq;
int64_t waitRender;
int64_t waitSubmit;
}</code></pre>
*/
public class BGFXStats extends Struct {
/** The struct size in bytes. */
public static final int SIZEOF;
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
CPUTIMEBEGIN,
CPUTIMEEND,
CPUTIMERFREQ,
GPUTIMEBEGIN,
GPUTIMEEND,
GPUTIMERFREQ,
WAITRENDER,
WAITSUBMIT;
static {
Layout layout = __struct(
__member(8),
__member(8),
__member(8),
__member(8),
__member(8),
__member(8),
__member(8),
__member(8)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
CPUTIMEBEGIN = layout.offsetof(0);
CPUTIMEEND = layout.offsetof(1);
CPUTIMERFREQ = layout.offsetof(2);
GPUTIMEBEGIN = layout.offsetof(3);
GPUTIMEEND = layout.offsetof(4);
GPUTIMERFREQ = layout.offsetof(5);
WAITRENDER = layout.offsetof(6);
WAITSUBMIT = layout.offsetof(7);
}
BGFXStats(long address, ByteBuffer container) {
super(address, container);
}
/**
* Creates a {@link BGFXStats} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public BGFXStats(ByteBuffer container) {
this(memAddress(container), checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** Returns the value of the {@code cpuTimeBegin} field. */
public long cpuTimeBegin() { return ncpuTimeBegin(address()); }
/** Returns the value of the {@code cpuTimeEnd} field. */
public long cpuTimeEnd() { return ncpuTimeEnd(address()); }
/** Returns the value of the {@code cpuTimerFreq} field. */
public long cpuTimerFreq() { return ncpuTimerFreq(address()); }
/** Returns the value of the {@code gpuTimeBegin} field. */
public long gpuTimeBegin() { return ngpuTimeBegin(address()); }
/** Returns the value of the {@code gpuTimeEnd} field. */
public long gpuTimeEnd() { return ngpuTimeEnd(address()); }
/** Returns the value of the {@code gpuTimerFreq} field. */
public long gpuTimerFreq() { return ngpuTimerFreq(address()); }
/** Returns the value of the {@code waitRender} field. */
public long waitRender() { return nwaitRender(address()); }
/** Returns the value of the {@code waitSubmit} field. */
public long waitSubmit() { return nwaitSubmit(address()); }
// -----------------------------------
/** Returns a new {@link BGFXStats} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
public static BGFXStats create(long address) {
return address == NULL ? null : new BGFXStats(address, null);
}
/**
* Create a {@link BGFXStats.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static Buffer create(long address, int capacity) {
return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
}
// -----------------------------------
/** Unsafe version of {@link #cpuTimeBegin}. */
public static long ncpuTimeBegin(long struct) { return memGetLong(struct + BGFXStats.CPUTIMEBEGIN); }
/** Unsafe version of {@link #cpuTimeEnd}. */
public static long ncpuTimeEnd(long struct) { return memGetLong(struct + BGFXStats.CPUTIMEEND); }
/** Unsafe version of {@link #cpuTimerFreq}. */
public static long ncpuTimerFreq(long struct) { return memGetLong(struct + BGFXStats.CPUTIMERFREQ); }
/** Unsafe version of {@link #gpuTimeBegin}. */
public static long ngpuTimeBegin(long struct) { return memGetLong(struct + BGFXStats.GPUTIMEBEGIN); }
/** Unsafe version of {@link #gpuTimeEnd}. */
public static long ngpuTimeEnd(long struct) { return memGetLong(struct + BGFXStats.GPUTIMEEND); }
/** Unsafe version of {@link #gpuTimerFreq}. */
public static long ngpuTimerFreq(long struct) { return memGetLong(struct + BGFXStats.GPUTIMERFREQ); }
/** Unsafe version of {@link #waitRender}. */
public static long nwaitRender(long struct) { return memGetLong(struct + BGFXStats.WAITRENDER); }
/** Unsafe version of {@link #waitSubmit}. */
public static long nwaitSubmit(long struct) { return memGetLong(struct + BGFXStats.WAITSUBMIT); }
// -----------------------------------
/** An array of {@link BGFXStats} structs. */
public static class Buffer extends StructBuffer<BGFXStats, Buffer> {
/**
* Creates a new {@link BGFXStats.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link BGFXStats#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
return new Buffer(address, container, mark, pos, lim, cap);
}
@Override
protected BGFXStats newInstance(long address) {
return new BGFXStats(address, container);
}
@Override
protected int sizeof() {
return SIZEOF;
}
/** Returns the value of the {@code cpuTimeBegin} field. */
public long cpuTimeBegin() { return BGFXStats.ncpuTimeBegin(address()); }
/** Returns the value of the {@code cpuTimeEnd} field. */
public long cpuTimeEnd() { return BGFXStats.ncpuTimeEnd(address()); }
/** Returns the value of the {@code cpuTimerFreq} field. */
public long cpuTimerFreq() { return BGFXStats.ncpuTimerFreq(address()); }
/** Returns the value of the {@code gpuTimeBegin} field. */
public long gpuTimeBegin() { return BGFXStats.ngpuTimeBegin(address()); }
/** Returns the value of the {@code gpuTimeEnd} field. */
public long gpuTimeEnd() { return BGFXStats.ngpuTimeEnd(address()); }
/** Returns the value of the {@code gpuTimerFreq} field. */
public long gpuTimerFreq() { return BGFXStats.ngpuTimerFreq(address()); }
/** Returns the value of the {@code waitRender} field. */
public long waitRender() { return BGFXStats.nwaitRender(address()); }
/** Returns the value of the {@code waitSubmit} field. */
public long waitSubmit() { return BGFXStats.nwaitSubmit(address()); }
}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import org.lwjgl.system.*;
import static org.lwjgl.system.dyncall.DynCallback.*;
/** Writes cached item. */
@FunctionalInterface
public interface BGFXCacheWriteCallbackI extends CallbackI.V {
String SIGNATURE = "(plpi)v";
@Override
default String getSignature() { return SIGNATURE; }
@Override
default void callback(long args) {
invoke(
dcbArgPointer(args),
dcbArgLong(args),
dcbArgPointer(args),
dcbArgInt(args)
);
}
/**
* Will be called to writes a cached item.
*
* @param _this the callback interface
* @param _id cache id
* @param _data data to write
* @param _size size of data to write
*/
void invoke(long _this, long _id, long _data, int _size);
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
#include "MacOSXLWJGL.h"
#include <dlfcn.h>
EXTERN_C_ENTER
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_macosx_DynamicLinkLoader_ndlopen(JNIEnv *__env, jclass clazz, jlong pathAddress, jint mode) {
const char *path = (const char *)(intptr_t)pathAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)dlopen(path, mode);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_macosx_DynamicLinkLoader_ndlerror(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)dlerror();
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_macosx_DynamicLinkLoader_ndlsym(JNIEnv *__env, jclass clazz, jlong handleAddress, jlong nameAddress) {
void *handle = (void *)(intptr_t)handleAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)dlsym(handle, name);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_system_macosx_DynamicLinkLoader_ndlclose(JNIEnv *__env, jclass clazz, jlong handleAddress) {
void *handle = (void *)(intptr_t)handleAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)dlclose(handle);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
#include "OVR_ErrorCode.h"
EXTERN_C_ENTER
JNIEXPORT jboolean JNICALL Java_org_lwjgl_ovr_OVRErrorCode_OVR_1SUCCESS(JNIEnv *__env, jclass clazz, jint result) {
UNUSED_PARAMS(__env, clazz)
return (jboolean)OVR_SUCCESS(result);
}
JNIEXPORT jboolean JNICALL Java_org_lwjgl_ovr_OVRErrorCode_OVR_1UNQUALIFIED_1SUCCESS(JNIEnv *__env, jclass clazz, jint result) {
UNUSED_PARAMS(__env, clazz)
return (jboolean)OVR_UNQUALIFIED_SUCCESS(result);
}
JNIEXPORT jboolean JNICALL Java_org_lwjgl_ovr_OVRErrorCode_OVR_1FAILURE(JNIEnv *__env, jclass clazz, jint result) {
UNUSED_PARAMS(__env, clazz)
return (jboolean)OVR_FAILURE(result);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import org.lwjgl.system.*;
import static org.lwjgl.system.dyncall.DynCallback.*;
/** Instances of this interface may be passed to the {@link BGFX#bgfx_make_ref_release make_ref_release} method. */
@FunctionalInterface
public interface BGFXReleaseFunctionCallbackI extends CallbackI.V {
String SIGNATURE = "(pp)v";
@Override
default String getSignature() { return SIGNATURE; }
@Override
default void callback(long args) {
invoke(
dcbArgPointer(args),
dcbArgPointer(args)
);
}
/**
* Memory release callback.
*
* @param _ptr
* @param _userData
*/
void invoke(long _ptr, long _userData);
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.util.lmdb;
import org.lwjgl.system.*;
import static org.lwjgl.system.dyncall.DynCallback.*;
@FunctionalInterface
public interface MDBCmpFuncI extends CallbackI.I {
String SIGNATURE = "(pp)i";
@Override
default String getSignature() { return SIGNATURE; }
@Override
default int callback(long args) {
return invoke(
dcbArgPointer(args),
dcbArgPointer(args)
);
}
/**
* A callback function used to compare two keys in a database.
*
* @param a the first item to compare
* @param b the second item to compare
*
* @return < 0 if a < b, 0 if a == b, > 0 if a > b
*/
int invoke(long a, long b);
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#ifdef LWJGL_WINDOWS
#define _CRT_SECURE_NO_WARNINGS
__pragma(warning(disable : 4710))
#endif
#include "common_tools.h"
#include <stdio.h>
EXTERN_C_ENTER
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_libc_Stdio_sscanf(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)sscanf;
}
JNIEXPORT jint JNICALL Java_org_lwjgl_system_libc_Stdio_nvsscanf(JNIEnv *__env, jclass clazz, jlong bufferAddress, jlong formatAddress, jlong vlistAddress) {
const char *buffer = (const char *)(intptr_t)bufferAddress;
const char *format = (const char *)(intptr_t)formatAddress;
va_list *vlist = VA_LIST_CAST(intptr_t)vlistAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)vsscanf(buffer, format, *vlist);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_libc_Stdio_sprintf(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)sprintf;
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_libc_Stdio_snprintf(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)snprintf;
}
JNIEXPORT jint JNICALL Java_org_lwjgl_system_libc_Stdio_nvsnprintf(JNIEnv *__env, jclass clazz, jlong bufferAddress, jlong buf_size, jlong formatAddress, jlong vlistAddress) {
char *buffer = (char *)(intptr_t)bufferAddress;
const char *format = (const char *)(intptr_t)formatAddress;
va_list *vlist = VA_LIST_CAST(intptr_t)vlistAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)vsnprintf(buffer, (size_t)buf_size, format, *vlist);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opengl;
/**
* Native bindings to the <a href="http://www.opengl.org/registry/specs/ARB/conditional_render_inverted.txt">ARB_conditional_render_inverted</a> extension.
*
* <p>This extension adds new modes to {@link GL30#glBeginConditionalRender BeginConditionalRender} which invert the condition used to determine whether to draw or not.</p>
*
* <p>Requires {@link GL30 OpenGL 3.0}. Promoted to core in {@link GL45 OpenGL 4.5}.</p>
*/
public final class ARBConditionalRenderInverted {
/** Accepted by the {@code mode} parameter of {@link GL30#glBeginConditionalRender BeginConditionalRender}. */
public static final int
GL_QUERY_WAIT_INVERTED = 0x8E17,
GL_QUERY_NO_WAIT_INVERTED = 0x8E18,
GL_QUERY_BY_REGION_WAIT_INVERTED = 0x8E19,
GL_QUERY_BY_REGION_NO_WAIT_INVERTED = 0x8E1A;
private ARBConditionalRenderInverted() {}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
/**
* This extension provides the {@link VkValidationFlagsEXT} struct that can be included in the {@code pNext} chain at {@link VK10#vkCreateInstance CreateInstance} time. The new struct
* contains an array of {@code VkValidationCheckEXT} values that will be disabled by the validation layers.
*/
public final class EXTValidationFlags {
/** The extension specification version. */
public static final int VK_EXT_VALIDATION_FLAGS_SPEC_VERSION = 1;
/** The extension name. */
public static final String VK_EXT_VALIDATION_FLAGS_EXTENSION_NAME = "VK_EXT_validation_flags";
/** VkStructureType */
public static final int VK_STRUCTURE_TYPE_VALIDATION_FLAGS_EXT = 1000061000;
/** disables all validation checks */
public static final int VK_VALIDATION_CHECK_ALL_EXT = 0;
private EXTValidationFlags() {}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
#include "tinyfiledialogs.h"
#ifndef LWJGL_WINDOWS
static int tinyfd_winUtf8;
#endif
EXTERN_C_ENTER
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_tinyfd_TinyFileDialogs_ntinyfd_1version(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)tinyfd_version;
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_tinyfd_TinyFileDialogs_ntinyfd_1winUtf8(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)&tinyfd_winUtf8;
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_tinyfd_TinyFileDialogs_ntinyfd_1forceConsole(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)&tinyfd_forceConsole;
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_tinyfd_TinyFileDialogs_ntinyfd_1response(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)tinyfd_response;
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_tinyfd_TinyFileDialogs_ntinyfd_1messageBox(JNIEnv *__env, jclass clazz, jlong aTitleAddress, jlong aMessageAddress, jlong aDialogTypeAddress, jlong aIconTypeAddress, jint aDefaultButton) {
const char *aTitle = (const char *)(intptr_t)aTitleAddress;
const char *aMessage = (const char *)(intptr_t)aMessageAddress;
const char *aDialogType = (const char *)(intptr_t)aDialogTypeAddress;
const char *aIconType = (const char *)(intptr_t)aIconTypeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)tinyfd_messageBox(aTitle, aMessage, aDialogType, aIconType, aDefaultButton);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_tinyfd_TinyFileDialogs_ntinyfd_1inputBox(JNIEnv *__env, jclass clazz, jlong aTitleAddress, jlong aMessageAddress, jlong aDefaultInputAddress) {
const char *aTitle = (const char *)(intptr_t)aTitleAddress;
const char *aMessage = (const char *)(intptr_t)aMessageAddress;
const char *aDefaultInput = (const char *)(intptr_t)aDefaultInputAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)tinyfd_inputBox(aTitle, aMessage, aDefaultInput);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_tinyfd_TinyFileDialogs_ntinyfd_1saveFileDialog(JNIEnv *__env, jclass clazz, jlong aTitleAddress, jlong aDefaultPathAndFileAddress, jint aNumOfFilterPatterns, jlong aFilterPatternsAddress, jlong aSingleFilterDescriptionAddress) {
const char *aTitle = (const char *)(intptr_t)aTitleAddress;
const char *aDefaultPathAndFile = (const char *)(intptr_t)aDefaultPathAndFileAddress;
const char * const *aFilterPatterns = (const char * const *)(intptr_t)aFilterPatternsAddress;
const char *aSingleFilterDescription = (const char *)(intptr_t)aSingleFilterDescriptionAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)tinyfd_saveFileDialog(aTitle, aDefaultPathAndFile, aNumOfFilterPatterns, aFilterPatterns, aSingleFilterDescription);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_tinyfd_TinyFileDialogs_ntinyfd_1openFileDialog(JNIEnv *__env, jclass clazz, jlong aTitleAddress, jlong aDefaultPathAndFileAddress, jint aNumOfFilterPatterns, jlong aFilterPatternsAddress, jlong aSingleFilterDescriptionAddress, jint aAllowMultipleSelects) {
const char *aTitle = (const char *)(intptr_t)aTitleAddress;
const char *aDefaultPathAndFile = (const char *)(intptr_t)aDefaultPathAndFileAddress;
const char * const *aFilterPatterns = (const char * const *)(intptr_t)aFilterPatternsAddress;
const char *aSingleFilterDescription = (const char *)(intptr_t)aSingleFilterDescriptionAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)tinyfd_openFileDialog(aTitle, aDefaultPathAndFile, aNumOfFilterPatterns, aFilterPatterns, aSingleFilterDescription, aAllowMultipleSelects);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_tinyfd_TinyFileDialogs_ntinyfd_1selectFolderDialog(JNIEnv *__env, jclass clazz, jlong aTitleAddress, jlong aDefaultPathAddress) {
const char *aTitle = (const char *)(intptr_t)aTitleAddress;
const char *aDefaultPath = (const char *)(intptr_t)aDefaultPathAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)tinyfd_selectFolderDialog(aTitle, aDefaultPath);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_util_tinyfd_TinyFileDialogs_ntinyfd_1colorChooser(JNIEnv *__env, jclass clazz, jlong aTitleAddress, jlong aDefaultHexRGBAddress, jlong aDefaultRGBAddress, jlong aoResultRGBAddress) {
const char *aTitle = (const char *)(intptr_t)aTitleAddress;
const char *aDefaultHexRGB = (const char *)(intptr_t)aDefaultHexRGBAddress;
unsigned char *aDefaultRGB = (unsigned char *)(intptr_t)aDefaultRGBAddress;
unsigned char *aoResultRGB = (unsigned char *)(intptr_t)aoResultRGBAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)tinyfd_colorChooser(aTitle, aDefaultHexRGB, aDefaultRGB, aoResultRGB);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
#include <stdlib.h>
#ifdef LWJGL_WINDOWS
#define aligned_alloc(alignment, size) _aligned_malloc(size, alignment)
#define aligned_free _aligned_free
#else
#ifndef __USE_ISOC11
inline void* aligned_alloc(size_t alignment, size_t size) {
void *p = NULL;
posix_memalign(&p, alignment, size);
return p;
}
#endif
#define aligned_free free
#endif
EXTERN_C_ENTER
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_libc_Stdlib_nmalloc(JNIEnv *__env, jclass clazz, jlong size) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)malloc((size_t)size);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_libc_Stdlib_ncalloc(JNIEnv *__env, jclass clazz, jlong nmemb, jlong size) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)calloc((size_t)nmemb, (size_t)size);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_libc_Stdlib_nrealloc(JNIEnv *__env, jclass clazz, jlong ptrAddress, jlong size) {
void *ptr = (void *)(intptr_t)ptrAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)realloc(ptr, (size_t)size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_system_libc_Stdlib_nfree(JNIEnv *__env, jclass clazz, jlong ptrAddress) {
void *ptr = (void *)(intptr_t)ptrAddress;
UNUSED_PARAMS(__env, clazz)
free(ptr);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_libc_Stdlib_naligned_1alloc(JNIEnv *__env, jclass clazz, jlong alignment, jlong size) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)aligned_alloc((size_t)alignment, (size_t)size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_system_libc_Stdlib_naligned_1free(JNIEnv *__env, jclass clazz, jlong ptrAddress) {
void *ptr = (void *)(intptr_t)ptrAddress;
UNUSED_PARAMS(__env, clazz)
aligned_free(ptr);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.nuklear;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* <h3>Layout</h3>
*
* <pre><code>struct nk_style_toggle {
{@link NkStyleItem struct nk_style_item} normal;
{@link NkStyleItem struct nk_style_item} hover;
{@link NkStyleItem struct nk_style_item} active;
{@link NkColor struct nk_color} border_color;
{@link NkStyleItem struct nk_style_item} cursor_normal;
{@link NkStyleItem struct nk_style_item} cursor_hover;
{@link NkColor struct nk_color} text_normal;
{@link NkColor struct nk_color} text_hover;
{@link NkColor struct nk_color} text_active;
{@link NkColor struct nk_color} text_background;
nk_flags text_alignment;
{@link NkVec2 struct nk_vec2} padding;
{@link NkVec2 struct nk_vec2} touch_padding;
float spacing;
float border;
{@link NkHandle nk_handle} userdata;
nk_draw_begin draw_begin;
nk_draw_end draw_end;
}</code></pre>
*/
public class NkStyleToggle extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
NORMAL,
HOVER,
ACTIVE,
BORDER_COLOR,
CURSOR_NORMAL,
CURSOR_HOVER,
TEXT_NORMAL,
TEXT_HOVER,
TEXT_ACTIVE,
TEXT_BACKGROUND,
TEXT_ALIGNMENT,
PADDING,
TOUCH_PADDING,
SPACING,
BORDER,
USERDATA,
DRAW_BEGIN,
DRAW_END;
static {
Layout layout = __struct(
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkColor.SIZEOF, NkColor.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkColor.SIZEOF, NkColor.ALIGNOF),
__member(NkColor.SIZEOF, NkColor.ALIGNOF),
__member(NkColor.SIZEOF, NkColor.ALIGNOF),
__member(NkColor.SIZEOF, NkColor.ALIGNOF),
__member(4),
__member(NkVec2.SIZEOF, NkVec2.ALIGNOF),
__member(NkVec2.SIZEOF, NkVec2.ALIGNOF),
__member(4),
__member(4),
__member(NkHandle.SIZEOF, NkHandle.ALIGNOF),
__member(POINTER_SIZE),
__member(POINTER_SIZE)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
NORMAL = layout.offsetof(0);
HOVER = layout.offsetof(1);
ACTIVE = layout.offsetof(2);
BORDER_COLOR = layout.offsetof(3);
CURSOR_NORMAL = layout.offsetof(4);
CURSOR_HOVER = layout.offsetof(5);
TEXT_NORMAL = layout.offsetof(6);
TEXT_HOVER = layout.offsetof(7);
TEXT_ACTIVE = layout.offsetof(8);
TEXT_BACKGROUND = layout.offsetof(9);
TEXT_ALIGNMENT = layout.offsetof(10);
PADDING = layout.offsetof(11);
TOUCH_PADDING = layout.offsetof(12);
SPACING = layout.offsetof(13);
BORDER = layout.offsetof(14);
USERDATA = layout.offsetof(15);
DRAW_BEGIN = layout.offsetof(16);
DRAW_END = layout.offsetof(17);
}
NkStyleToggle(long address, ByteBuffer container) {
super(address, container);
}
/**
* Creates a {@link NkStyleToggle} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public NkStyleToggle(ByteBuffer container) {
this(memAddress(container), checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** Returns a {@link NkStyleItem} view of the {@code normal} field. */
public NkStyleItem normal() { return nnormal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code hover} field. */
public NkStyleItem hover() { return nhover(address()); }
/** Returns a {@link NkStyleItem} view of the {@code active} field. */
public NkStyleItem active() { return nactive(address()); }
/** Returns a {@link NkColor} view of the {@code border_color} field. */
public NkColor border_color() { return nborder_color(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_normal} field. */
public NkStyleItem cursor_normal() { return ncursor_normal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_hover} field. */
public NkStyleItem cursor_hover() { return ncursor_hover(address()); }
/** Returns a {@link NkColor} view of the {@code text_normal} field. */
public NkColor text_normal() { return ntext_normal(address()); }
/** Returns a {@link NkColor} view of the {@code text_hover} field. */
public NkColor text_hover() { return ntext_hover(address()); }
/** Returns a {@link NkColor} view of the {@code text_active} field. */
public NkColor text_active() { return ntext_active(address()); }
/** Returns a {@link NkColor} view of the {@code text_background} field. */
public NkColor text_background() { return ntext_background(address()); }
/** Returns the value of the {@code text_alignment} field. */
public int text_alignment() { return ntext_alignment(address()); }
/** Returns a {@link NkVec2} view of the {@code padding} field. */
public NkVec2 padding() { return npadding(address()); }
/** Returns a {@link NkVec2} view of the {@code touch_padding} field. */
public NkVec2 touch_padding() { return ntouch_padding(address()); }
/** Returns the value of the {@code spacing} field. */
public float spacing() { return nspacing(address()); }
/** Returns the value of the {@code border} field. */
public float border() { return nborder(address()); }
/** Returns a {@link NkHandle} view of the {@code userdata} field. */
public NkHandle userdata() { return nuserdata(address()); }
/** Returns the {@code NkDrawBeginCallback} instance at the {@code draw_begin} field. */
public NkDrawBeginCallback draw_begin() { return NkDrawBeginCallback.create(ndraw_begin(address())); }
/** Returns the {@code NkDrawEndCallback} instance at the {@code draw_end} field. */
public NkDrawEndCallback draw_end() { return NkDrawEndCallback.create(ndraw_end(address())); }
/** Copies the specified {@link NkStyleItem} to the {@code normal} field. */
public NkStyleToggle normal(NkStyleItem value) { nnormal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code hover} field. */
public NkStyleToggle hover(NkStyleItem value) { nhover(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code active} field. */
public NkStyleToggle active(NkStyleItem value) { nactive(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code border_color} field. */
public NkStyleToggle border_color(NkColor value) { nborder_color(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_normal} field. */
public NkStyleToggle cursor_normal(NkStyleItem value) { ncursor_normal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_hover} field. */
public NkStyleToggle cursor_hover(NkStyleItem value) { ncursor_hover(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code text_normal} field. */
public NkStyleToggle text_normal(NkColor value) { ntext_normal(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code text_hover} field. */
public NkStyleToggle text_hover(NkColor value) { ntext_hover(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code text_active} field. */
public NkStyleToggle text_active(NkColor value) { ntext_active(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code text_background} field. */
public NkStyleToggle text_background(NkColor value) { ntext_background(address(), value); return this; }
/** Sets the specified value to the {@code text_alignment} field. */
public NkStyleToggle text_alignment(int value) { ntext_alignment(address(), value); return this; }
/** Copies the specified {@link NkVec2} to the {@code padding} field. */
public NkStyleToggle padding(NkVec2 value) { npadding(address(), value); return this; }
/** Copies the specified {@link NkVec2} to the {@code touch_padding} field. */
public NkStyleToggle touch_padding(NkVec2 value) { ntouch_padding(address(), value); return this; }
/** Sets the specified value to the {@code spacing} field. */
public NkStyleToggle spacing(float value) { nspacing(address(), value); return this; }
/** Sets the specified value to the {@code border} field. */
public NkStyleToggle border(float value) { nborder(address(), value); return this; }
/** Copies the specified {@link NkHandle} to the {@code userdata} field. */
public NkStyleToggle userdata(NkHandle value) { nuserdata(address(), value); return this; }
/** Sets the address of the specified {@link NkDrawBeginCallbackI} to the {@code draw_begin} field. */
public NkStyleToggle draw_begin(NkDrawBeginCallbackI value) { ndraw_begin(address(), addressSafe(value)); return this; }
/** Sets the address of the specified {@link NkDrawEndCallbackI} to the {@code draw_end} field. */
public NkStyleToggle draw_end(NkDrawEndCallbackI value) { ndraw_end(address(), addressSafe(value)); return this; }
/** Unsafe version of {@link #set(NkStyleToggle) set}. */
public NkStyleToggle nset(long struct) {
memCopy(struct, address(), SIZEOF);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public NkStyleToggle set(NkStyleToggle src) {
return nset(src.address());
}
// -----------------------------------
/** Returns a new {@link NkStyleToggle} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static NkStyleToggle malloc() {
return create(nmemAlloc(SIZEOF));
}
/** Returns a new {@link NkStyleToggle} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static NkStyleToggle calloc() {
return create(nmemCalloc(1, SIZEOF));
}
/** Returns a new {@link NkStyleToggle} instance allocated with {@link BufferUtils}. */
public static NkStyleToggle create() {
return new NkStyleToggle(BufferUtils.createByteBuffer(SIZEOF));
}
/** Returns a new {@link NkStyleToggle} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
public static NkStyleToggle create(long address) {
return address == NULL ? null : new NkStyleToggle(address, null);
}
/**
* Returns a new {@link NkStyleToggle.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer malloc(int capacity) {
return create(nmemAlloc(capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link NkStyleToggle.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer calloc(int capacity) {
return create(nmemCalloc(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link NkStyleToggle.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static Buffer create(int capacity) {
return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF));
}
/**
* Create a {@link NkStyleToggle.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static Buffer create(long address, int capacity) {
return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
}
// -----------------------------------
/** Returns a new {@link NkStyleToggle} instance allocated on the thread-local {@link MemoryStack}. */
public static NkStyleToggle mallocStack() {
return mallocStack(stackGet());
}
/** Returns a new {@link NkStyleToggle} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
public static NkStyleToggle callocStack() {
return callocStack(stackGet());
}
/**
* Returns a new {@link NkStyleToggle} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static NkStyleToggle mallocStack(MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@link NkStyleToggle} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static NkStyleToggle callocStack(MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link NkStyleToggle.Buffer} instance allocated on the thread-local {@link MemoryStack}.
*
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity) {
return mallocStack(capacity, stackGet());
}
/**
* Returns a new {@link NkStyleToggle.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
*
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity) {
return callocStack(capacity, stackGet());
}
/**
* Returns a new {@link NkStyleToggle.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity, MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link NkStyleToggle.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity, MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #normal}. */
public static NkStyleItem nnormal(long struct) { return NkStyleItem.create(struct + NkStyleToggle.NORMAL); }
/** Unsafe version of {@link #hover}. */
public static NkStyleItem nhover(long struct) { return NkStyleItem.create(struct + NkStyleToggle.HOVER); }
/** Unsafe version of {@link #active}. */
public static NkStyleItem nactive(long struct) { return NkStyleItem.create(struct + NkStyleToggle.ACTIVE); }
/** Unsafe version of {@link #border_color}. */
public static NkColor nborder_color(long struct) { return NkColor.create(struct + NkStyleToggle.BORDER_COLOR); }
/** Unsafe version of {@link #cursor_normal}. */
public static NkStyleItem ncursor_normal(long struct) { return NkStyleItem.create(struct + NkStyleToggle.CURSOR_NORMAL); }
/** Unsafe version of {@link #cursor_hover}. */
public static NkStyleItem ncursor_hover(long struct) { return NkStyleItem.create(struct + NkStyleToggle.CURSOR_HOVER); }
/** Unsafe version of {@link #text_normal}. */
public static NkColor ntext_normal(long struct) { return NkColor.create(struct + NkStyleToggle.TEXT_NORMAL); }
/** Unsafe version of {@link #text_hover}. */
public static NkColor ntext_hover(long struct) { return NkColor.create(struct + NkStyleToggle.TEXT_HOVER); }
/** Unsafe version of {@link #text_active}. */
public static NkColor ntext_active(long struct) { return NkColor.create(struct + NkStyleToggle.TEXT_ACTIVE); }
/** Unsafe version of {@link #text_background}. */
public static NkColor ntext_background(long struct) { return NkColor.create(struct + NkStyleToggle.TEXT_BACKGROUND); }
/** Unsafe version of {@link #text_alignment}. */
public static int ntext_alignment(long struct) { return memGetInt(struct + NkStyleToggle.TEXT_ALIGNMENT); }
/** Unsafe version of {@link #padding}. */
public static NkVec2 npadding(long struct) { return NkVec2.create(struct + NkStyleToggle.PADDING); }
/** Unsafe version of {@link #touch_padding}. */
public static NkVec2 ntouch_padding(long struct) { return NkVec2.create(struct + NkStyleToggle.TOUCH_PADDING); }
/** Unsafe version of {@link #spacing}. */
public static float nspacing(long struct) { return memGetFloat(struct + NkStyleToggle.SPACING); }
/** Unsafe version of {@link #border}. */
public static float nborder(long struct) { return memGetFloat(struct + NkStyleToggle.BORDER); }
/** Unsafe version of {@link #userdata}. */
public static NkHandle nuserdata(long struct) { return NkHandle.create(struct + NkStyleToggle.USERDATA); }
/** Unsafe version of {@link #draw_begin}. */
public static long ndraw_begin(long struct) { return memGetAddress(struct + NkStyleToggle.DRAW_BEGIN); }
/** Unsafe version of {@link #draw_end}. */
public static long ndraw_end(long struct) { return memGetAddress(struct + NkStyleToggle.DRAW_END); }
/** Unsafe version of {@link #normal(NkStyleItem) normal}. */
public static void nnormal(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleToggle.NORMAL, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #hover(NkStyleItem) hover}. */
public static void nhover(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleToggle.HOVER, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #active(NkStyleItem) active}. */
public static void nactive(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleToggle.ACTIVE, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #border_color(NkColor) border_color}. */
public static void nborder_color(long struct, NkColor value) { memCopy(value.address(), struct + NkStyleToggle.BORDER_COLOR, NkColor.SIZEOF); }
/** Unsafe version of {@link #cursor_normal(NkStyleItem) cursor_normal}. */
public static void ncursor_normal(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleToggle.CURSOR_NORMAL, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #cursor_hover(NkStyleItem) cursor_hover}. */
public static void ncursor_hover(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleToggle.CURSOR_HOVER, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #text_normal(NkColor) text_normal}. */
public static void ntext_normal(long struct, NkColor value) { memCopy(value.address(), struct + NkStyleToggle.TEXT_NORMAL, NkColor.SIZEOF); }
/** Unsafe version of {@link #text_hover(NkColor) text_hover}. */
public static void ntext_hover(long struct, NkColor value) { memCopy(value.address(), struct + NkStyleToggle.TEXT_HOVER, NkColor.SIZEOF); }
/** Unsafe version of {@link #text_active(NkColor) text_active}. */
public static void ntext_active(long struct, NkColor value) { memCopy(value.address(), struct + NkStyleToggle.TEXT_ACTIVE, NkColor.SIZEOF); }
/** Unsafe version of {@link #text_background(NkColor) text_background}. */
public static void ntext_background(long struct, NkColor value) { memCopy(value.address(), struct + NkStyleToggle.TEXT_BACKGROUND, NkColor.SIZEOF); }
/** Unsafe version of {@link #text_alignment(int) text_alignment}. */
public static void ntext_alignment(long struct, int value) { memPutInt(struct + NkStyleToggle.TEXT_ALIGNMENT, value); }
/** Unsafe version of {@link #padding(NkVec2) padding}. */
public static void npadding(long struct, NkVec2 value) { memCopy(value.address(), struct + NkStyleToggle.PADDING, NkVec2.SIZEOF); }
/** Unsafe version of {@link #touch_padding(NkVec2) touch_padding}. */
public static void ntouch_padding(long struct, NkVec2 value) { memCopy(value.address(), struct + NkStyleToggle.TOUCH_PADDING, NkVec2.SIZEOF); }
/** Unsafe version of {@link #spacing(float) spacing}. */
public static void nspacing(long struct, float value) { memPutFloat(struct + NkStyleToggle.SPACING, value); }
/** Unsafe version of {@link #border(float) border}. */
public static void nborder(long struct, float value) { memPutFloat(struct + NkStyleToggle.BORDER, value); }
/** Unsafe version of {@link #userdata(NkHandle) userdata}. */
public static void nuserdata(long struct, NkHandle value) { memCopy(value.address(), struct + NkStyleToggle.USERDATA, NkHandle.SIZEOF); }
/** Unsafe version of {@link #draw_begin(NkDrawBeginCallbackI) draw_begin}. */
public static void ndraw_begin(long struct, long value) { memPutAddress(struct + NkStyleToggle.DRAW_BEGIN, value); }
/** Unsafe version of {@link #draw_end(NkDrawEndCallbackI) draw_end}. */
public static void ndraw_end(long struct, long value) { memPutAddress(struct + NkStyleToggle.DRAW_END, value); }
// -----------------------------------
/** An array of {@link NkStyleToggle} structs. */
public static class Buffer extends StructBuffer<NkStyleToggle, Buffer> implements NativeResource {
/**
* Creates a new {@link NkStyleToggle.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link NkStyleToggle#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
return new Buffer(address, container, mark, pos, lim, cap);
}
@Override
protected NkStyleToggle newInstance(long address) {
return new NkStyleToggle(address, container);
}
@Override
protected int sizeof() {
return SIZEOF;
}
/** Returns a {@link NkStyleItem} view of the {@code normal} field. */
public NkStyleItem normal() { return NkStyleToggle.nnormal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code hover} field. */
public NkStyleItem hover() { return NkStyleToggle.nhover(address()); }
/** Returns a {@link NkStyleItem} view of the {@code active} field. */
public NkStyleItem active() { return NkStyleToggle.nactive(address()); }
/** Returns a {@link NkColor} view of the {@code border_color} field. */
public NkColor border_color() { return NkStyleToggle.nborder_color(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_normal} field. */
public NkStyleItem cursor_normal() { return NkStyleToggle.ncursor_normal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_hover} field. */
public NkStyleItem cursor_hover() { return NkStyleToggle.ncursor_hover(address()); }
/** Returns a {@link NkColor} view of the {@code text_normal} field. */
public NkColor text_normal() { return NkStyleToggle.ntext_normal(address()); }
/** Returns a {@link NkColor} view of the {@code text_hover} field. */
public NkColor text_hover() { return NkStyleToggle.ntext_hover(address()); }
/** Returns a {@link NkColor} view of the {@code text_active} field. */
public NkColor text_active() { return NkStyleToggle.ntext_active(address()); }
/** Returns a {@link NkColor} view of the {@code text_background} field. */
public NkColor text_background() { return NkStyleToggle.ntext_background(address()); }
/** Returns the value of the {@code text_alignment} field. */
public int text_alignment() { return NkStyleToggle.ntext_alignment(address()); }
/** Returns a {@link NkVec2} view of the {@code padding} field. */
public NkVec2 padding() { return NkStyleToggle.npadding(address()); }
/** Returns a {@link NkVec2} view of the {@code touch_padding} field. */
public NkVec2 touch_padding() { return NkStyleToggle.ntouch_padding(address()); }
/** Returns the value of the {@code spacing} field. */
public float spacing() { return NkStyleToggle.nspacing(address()); }
/** Returns the value of the {@code border} field. */
public float border() { return NkStyleToggle.nborder(address()); }
/** Returns a {@link NkHandle} view of the {@code userdata} field. */
public NkHandle userdata() { return NkStyleToggle.nuserdata(address()); }
/** Returns the {@code NkDrawBeginCallback} instance at the {@code draw_begin} field. */
public NkDrawBeginCallback draw_begin() { return NkDrawBeginCallback.create(NkStyleToggle.ndraw_begin(address())); }
/** Returns the {@code NkDrawEndCallback} instance at the {@code draw_end} field. */
public NkDrawEndCallback draw_end() { return NkDrawEndCallback.create(NkStyleToggle.ndraw_end(address())); }
/** Copies the specified {@link NkStyleItem} to the {@code normal} field. */
public NkStyleToggle.Buffer normal(NkStyleItem value) { NkStyleToggle.nnormal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code hover} field. */
public NkStyleToggle.Buffer hover(NkStyleItem value) { NkStyleToggle.nhover(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code active} field. */
public NkStyleToggle.Buffer active(NkStyleItem value) { NkStyleToggle.nactive(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code border_color} field. */
public NkStyleToggle.Buffer border_color(NkColor value) { NkStyleToggle.nborder_color(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_normal} field. */
public NkStyleToggle.Buffer cursor_normal(NkStyleItem value) { NkStyleToggle.ncursor_normal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_hover} field. */
public NkStyleToggle.Buffer cursor_hover(NkStyleItem value) { NkStyleToggle.ncursor_hover(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code text_normal} field. */
public NkStyleToggle.Buffer text_normal(NkColor value) { NkStyleToggle.ntext_normal(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code text_hover} field. */
public NkStyleToggle.Buffer text_hover(NkColor value) { NkStyleToggle.ntext_hover(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code text_active} field. */
public NkStyleToggle.Buffer text_active(NkColor value) { NkStyleToggle.ntext_active(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code text_background} field. */
public NkStyleToggle.Buffer text_background(NkColor value) { NkStyleToggle.ntext_background(address(), value); return this; }
/** Sets the specified value to the {@code text_alignment} field. */
public NkStyleToggle.Buffer text_alignment(int value) { NkStyleToggle.ntext_alignment(address(), value); return this; }
/** Copies the specified {@link NkVec2} to the {@code padding} field. */
public NkStyleToggle.Buffer padding(NkVec2 value) { NkStyleToggle.npadding(address(), value); return this; }
/** Copies the specified {@link NkVec2} to the {@code touch_padding} field. */
public NkStyleToggle.Buffer touch_padding(NkVec2 value) { NkStyleToggle.ntouch_padding(address(), value); return this; }
/** Sets the specified value to the {@code spacing} field. */
public NkStyleToggle.Buffer spacing(float value) { NkStyleToggle.nspacing(address(), value); return this; }
/** Sets the specified value to the {@code border} field. */
public NkStyleToggle.Buffer border(float value) { NkStyleToggle.nborder(address(), value); return this; }
/** Copies the specified {@link NkHandle} to the {@code userdata} field. */
public NkStyleToggle.Buffer userdata(NkHandle value) { NkStyleToggle.nuserdata(address(), value); return this; }
/** Sets the address of the specified {@link NkDrawBeginCallbackI} to the {@code draw_begin} field. */
public NkStyleToggle.Buffer draw_begin(NkDrawBeginCallbackI value) { NkStyleToggle.ndraw_begin(address(), addressSafe(value)); return this; }
/** Sets the address of the specified {@link NkDrawEndCallbackI} to the {@code draw_end} field. */
public NkStyleToggle.Buffer draw_end(NkDrawEndCallbackI value) { NkStyleToggle.ndraw_end(address(), addressSafe(value)); return this; }
}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opengl;
/**
* Native bindings to the <a href="http://www.opengl.org/registry/specs/EXT/blend_subtract.txt">EXT_blend_subtract</a> extension.
*
* <p>Two additional blending equations are specified using the interface defined by <a href="http://www.opengl.org/registry/specs/EXT/blend_minmax.link.txt">EXT_blend_minmax.link</a>. These equations are similar to the default
* blending equation, but produce the difference of its left and right hand sides, rather than the sum. Image differences are useful in many image
* processing applications.</p>
*
* <p>Promoted to core in {@link GL14 OpenGL 1.4}.</p>
*/
public final class EXTBlendSubtract {
/** Accepted by the {@code mode} parameter of BlendEquationEXT. */
public static final int
GL_FUNC_SUBTRACT_EXT = 0x800A,
GL_FUNC_REVERSE_SUBTRACT_EXT = 0x800B;
private EXTBlendSubtract() {}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.nuklear;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* <h3>Layout</h3>
*
* <pre><code>struct nk_image {
{@link NkHandle nk_handle} handle;
unsigned short w;
unsigned short h;
unsigned short region[4];
}</code></pre>
*/
public class NkImage extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
HANDLE,
W,
H,
REGION;
static {
Layout layout = __struct(
__member(NkHandle.SIZEOF, NkHandle.ALIGNOF),
__member(2),
__member(2),
__array(2, 4)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
HANDLE = layout.offsetof(0);
W = layout.offsetof(1);
H = layout.offsetof(2);
REGION = layout.offsetof(3);
}
NkImage(long address, ByteBuffer container) {
super(address, container);
}
/**
* Creates a {@link NkImage} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public NkImage(ByteBuffer container) {
this(memAddress(container), checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** Returns a {@link NkHandle} view of the {@code handle} field. */
public NkHandle handle() { return nhandle(address()); }
/** Returns the value of the {@code w} field. */
public short w() { return nw(address()); }
/** Returns the value of the {@code h} field. */
public short h() { return nh(address()); }
/** Returns a {@link ShortBuffer} view of the {@code region} field. */
public ShortBuffer region() { return nregion(address()); }
/** Returns the value at the specified index of the {@code region} field. */
public short region(int index) { return nregion(address(), index); }
/** Copies the specified {@link NkHandle} to the {@code handle} field. */
public NkImage handle(NkHandle value) { nhandle(address(), value); return this; }
/** Sets the specified value to the {@code w} field. */
public NkImage w(short value) { nw(address(), value); return this; }
/** Sets the specified value to the {@code h} field. */
public NkImage h(short value) { nh(address(), value); return this; }
/** Copies the specified {@link ShortBuffer} to the {@code region} field. */
public NkImage region(ShortBuffer value) { nregion(address(), value); return this; }
/** Sets the specified value at the specified index of the {@code region} field. */
public NkImage region(int index, short value) { nregion(address(), index, value); return this; }
/** Unsafe version of {@link #set(NkImage) set}. */
public NkImage nset(long struct) {
memCopy(struct, address(), SIZEOF);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public NkImage set(NkImage src) {
return nset(src.address());
}
// -----------------------------------
/** Returns a new {@link NkImage} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static NkImage malloc() {
return create(nmemAlloc(SIZEOF));
}
/** Returns a new {@link NkImage} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static NkImage calloc() {
return create(nmemCalloc(1, SIZEOF));
}
/** Returns a new {@link NkImage} instance allocated with {@link BufferUtils}. */
public static NkImage create() {
return new NkImage(BufferUtils.createByteBuffer(SIZEOF));
}
/** Returns a new {@link NkImage} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
public static NkImage create(long address) {
return address == NULL ? null : new NkImage(address, null);
}
/**
* Returns a new {@link NkImage.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer malloc(int capacity) {
return create(nmemAlloc(capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link NkImage.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer calloc(int capacity) {
return create(nmemCalloc(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link NkImage.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static Buffer create(int capacity) {
return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF));
}
/**
* Create a {@link NkImage.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static Buffer create(long address, int capacity) {
return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
}
// -----------------------------------
/** Returns a new {@link NkImage} instance allocated on the thread-local {@link MemoryStack}. */
public static NkImage mallocStack() {
return mallocStack(stackGet());
}
/** Returns a new {@link NkImage} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
public static NkImage callocStack() {
return callocStack(stackGet());
}
/**
* Returns a new {@link NkImage} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static NkImage mallocStack(MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@link NkImage} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static NkImage callocStack(MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link NkImage.Buffer} instance allocated on the thread-local {@link MemoryStack}.
*
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity) {
return mallocStack(capacity, stackGet());
}
/**
* Returns a new {@link NkImage.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
*
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity) {
return callocStack(capacity, stackGet());
}
/**
* Returns a new {@link NkImage.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity, MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link NkImage.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity, MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #handle}. */
public static NkHandle nhandle(long struct) { return NkHandle.create(struct + NkImage.HANDLE); }
/** Unsafe version of {@link #w}. */
public static short nw(long struct) { return memGetShort(struct + NkImage.W); }
/** Unsafe version of {@link #h}. */
public static short nh(long struct) { return memGetShort(struct + NkImage.H); }
/** Unsafe version of {@link #region}. */
public static ShortBuffer nregion(long struct) {
return memShortBuffer(struct + NkImage.REGION, 4);
}
/** Unsafe version of {@link #region(int) region}. */
public static short nregion(long struct, int index) { return memGetShort(struct + NkImage.REGION + index * 2); }
/** Unsafe version of {@link #handle(NkHandle) handle}. */
public static void nhandle(long struct, NkHandle value) { memCopy(value.address(), struct + NkImage.HANDLE, NkHandle.SIZEOF); }
/** Unsafe version of {@link #w(short) w}. */
public static void nw(long struct, short value) { memPutShort(struct + NkImage.W, value); }
/** Unsafe version of {@link #h(short) h}. */
public static void nh(long struct, short value) { memPutShort(struct + NkImage.H, value); }
/** Unsafe version of {@link #region(ShortBuffer) region}. */
public static void nregion(long struct, ShortBuffer value) {
if ( CHECKS ) checkBufferGT(value, 4);
memCopy(memAddress(value), struct + NkImage.REGION, value.remaining() * 2);
}
/** Unsafe version of {@link #region(int, short) region}. */
public static void nregion(long struct, int index, short value) { memPutShort(struct + NkImage.REGION + index * 2, value); }
// -----------------------------------
/** An array of {@link NkImage} structs. */
public static class Buffer extends StructBuffer<NkImage, Buffer> implements NativeResource {
/**
* Creates a new {@link NkImage.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link NkImage#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
return new Buffer(address, container, mark, pos, lim, cap);
}
@Override
protected NkImage newInstance(long address) {
return new NkImage(address, container);
}
@Override
protected int sizeof() {
return SIZEOF;
}
/** Returns a {@link NkHandle} view of the {@code handle} field. */
public NkHandle handle() { return NkImage.nhandle(address()); }
/** Returns the value of the {@code w} field. */
public short w() { return NkImage.nw(address()); }
/** Returns the value of the {@code h} field. */
public short h() { return NkImage.nh(address()); }
/** Returns a {@link ShortBuffer} view of the {@code region} field. */
public ShortBuffer region() { return NkImage.nregion(address()); }
/** Returns the value at the specified index of the {@code region} field. */
public short region(int index) { return NkImage.nregion(address(), index); }
/** Copies the specified {@link NkHandle} to the {@code handle} field. */
public NkImage.Buffer handle(NkHandle value) { NkImage.nhandle(address(), value); return this; }
/** Sets the specified value to the {@code w} field. */
public NkImage.Buffer w(short value) { NkImage.nw(address(), value); return this; }
/** Sets the specified value to the {@code h} field. */
public NkImage.Buffer h(short value) { NkImage.nh(address(), value); return this; }
/** Copies the specified {@link ShortBuffer} to the {@code region} field. */
public NkImage.Buffer region(ShortBuffer value) { NkImage.nregion(address(), value); return this; }
/** Sets the specified value at the specified index of the {@code region} field. */
public NkImage.Buffer region(int index, short value) { NkImage.nregion(address(), index, value); return this; }
}
}<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
#include "dynload.h"
EXTERN_C_ENTER
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_dyncall_DynLoad_ndlLoadLibrary(JNIEnv *__env, jclass clazz, jlong libpathAddress) {
const char *libpath = (const char *)(intptr_t)libpathAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)dlLoadLibrary(libpath);
}
JNIEXPORT void JNICALL Java_org_lwjgl_system_dyncall_DynLoad_ndlFreeLibrary(JNIEnv *__env, jclass clazz, jlong pLibAddress) {
DLLib *pLib = (DLLib *)(intptr_t)pLibAddress;
UNUSED_PARAMS(__env, clazz)
dlFreeLibrary(pLib);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_dyncall_DynLoad_ndlFindSymbol(JNIEnv *__env, jclass clazz, jlong pLibAddress, jlong pSymbolNameAddress) {
DLLib *pLib = (DLLib *)(intptr_t)pLibAddress;
const char *pSymbolName = (const char *)(intptr_t)pSymbolNameAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)dlFindSymbol(pLib, pSymbolName);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_dyncall_DynLoad_ndlSymsInit(JNIEnv *__env, jclass clazz, jlong libPathAddress) {
const char *libPath = (const char *)(intptr_t)libPathAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)dlSymsInit(libPath);
}
JNIEXPORT void JNICALL Java_org_lwjgl_system_dyncall_DynLoad_ndlSymsCleanup(JNIEnv *__env, jclass clazz, jlong pSymsAddress) {
DLSyms *pSyms = (DLSyms *)(intptr_t)pSymsAddress;
UNUSED_PARAMS(__env, clazz)
dlSymsCleanup(pSyms);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_system_dyncall_DynLoad_ndlSymsCount(JNIEnv *__env, jclass clazz, jlong pSymsAddress) {
DLSyms *pSyms = (DLSyms *)(intptr_t)pSymsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)dlSymsCount(pSyms);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_dyncall_DynLoad_ndlSymsName(JNIEnv *__env, jclass clazz, jlong pSymsAddress, jint index) {
DLSyms *pSyms = (DLSyms *)(intptr_t)pSymsAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)dlSymsName(pSyms, index);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_system_dyncall_DynLoad_ndlSymsNameFromValue(JNIEnv *__env, jclass clazz, jlong pSymsAddress, jlong valueAddress) {
DLSyms *pSyms = (DLSyms *)(intptr_t)pSymsAddress;
void *value = (void *)(intptr_t)valueAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)dlSymsNameFromValue(pSyms, value);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#ifdef LWJGL_LINUX
#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
#include "common_tools.h"
DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4711 4738))
#endif
#define NK_PRIVATE
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_COMMAND_USERDATA
#ifdef LWJGL_WINDOWS
#define NK_BUTTON_TRIGGER_ON_RELEASE
#endif
#define NK_ASSERT(expr)
#define NK_IMPLEMENTATION
#define NK_MEMSET memset
#define NK_MEMCOPY memcpy
#define NK_SQRT sqrt
#define NK_SIN sinf
#define NK_COS cosf
#include <math.h>
#include <string.h>
#include "nuklear.h"
typedef float(*nk_value_getter)(void* user, int index);
typedef void(*nk_item_getter)(void*, int, const char**);
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1init_1fixed(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong memoryAddress, jlong size, jlong fontAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
void *memory = (void *)(intptr_t)memoryAddress;
const struct nk_user_font *font = (const struct nk_user_font *)(intptr_t)fontAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_init_fixed(ctx, memory, (nk_size)size, font);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1init_1custom(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong cmdsAddress, jlong poolAddress, jlong fontAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_buffer *cmds = (struct nk_buffer *)(intptr_t)cmdsAddress;
struct nk_buffer *pool = (struct nk_buffer *)(intptr_t)poolAddress;
const struct nk_user_font *font = (const struct nk_user_font *)(intptr_t)fontAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_init_custom(ctx, cmds, pool, font);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1init(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong allocatorAddress, jlong fontAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_allocator *allocator = (struct nk_allocator *)(intptr_t)allocatorAddress;
const struct nk_user_font *font = (const struct nk_user_font *)(intptr_t)fontAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_init(ctx, allocator, font);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1clear(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_clear(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1free(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_free(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1set_1user_1data(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong handleAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
nk_handle *handle = (nk_handle *)(intptr_t)handleAddress;
UNUSED_PARAMS(__env, clazz)
nk_set_user_data(ctx, *handle);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong panelAddress, jlong titleAddress, jlong boundsAddress, jint flags) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *panel = (struct nk_panel *)(intptr_t)panelAddress;
const char *title = (const char *)(intptr_t)titleAddress;
struct nk_rect *bounds = (struct nk_rect *)(intptr_t)boundsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_begin(ctx, panel, title, *bounds, flags);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1begin_1titled(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong panelAddress, jlong nameAddress, jlong titleAddress, jlong boundsAddress, jint flags) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *panel = (struct nk_panel *)(intptr_t)panelAddress;
const char *name = (const char *)(intptr_t)nameAddress;
const char *title = (const char *)(intptr_t)titleAddress;
struct nk_rect *bounds = (struct nk_rect *)(intptr_t)boundsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_begin_titled(ctx, panel, name, title, *bounds, flags);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_end(ctx);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1find(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_window_find(ctx, name);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1bounds(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
const struct nk_context *ctx = (const struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_window_get_bounds(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1position(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
const struct nk_context *ctx = (const struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_window_get_position(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1size(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
const struct nk_context *ctx = (const struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_window_get_size(ctx);
}
JNIEXPORT jfloat JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1width(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
const struct nk_context *ctx = (const struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jfloat)nk_window_get_width(ctx);
}
JNIEXPORT jfloat JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1height(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
const struct nk_context *ctx = (const struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jfloat)nk_window_get_height(ctx);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1panel(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_window_get_panel(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1content_1region(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_window_get_content_region(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1content_1region_1min(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_window_get_content_region_min(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1content_1region_1max(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_window_get_content_region_max(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1content_1region_1size(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_window_get_content_region_size(ctx);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1get_1canvas(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_window_get_canvas(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1has_1focus(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
const struct nk_context *ctx = (const struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_window_has_focus(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1is_1collapsed(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_window_is_collapsed(ctx, name);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1is_1closed(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_window_is_closed(ctx, name);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1is_1hidden(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_window_is_hidden(ctx, name);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1is_1active(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_window_is_active(ctx, name);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1is_1hovered(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_window_is_hovered(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1is_1any_1hovered(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_window_is_any_hovered(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1item_1is_1any_1active(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_item_is_any_active(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1set_1bounds(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong boundsAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_rect *bounds = (struct nk_rect *)(intptr_t)boundsAddress;
UNUSED_PARAMS(__env, clazz)
nk_window_set_bounds(ctx, *bounds);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1set_1position(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong positionAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_vec2 *position = (struct nk_vec2 *)(intptr_t)positionAddress;
UNUSED_PARAMS(__env, clazz)
nk_window_set_position(ctx, *position);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1set_1size(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
nk_window_set_size(ctx, *size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1set_1focus(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
nk_window_set_focus(ctx, name);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1close(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
nk_window_close(ctx, name);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1collapse(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jint c) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
nk_window_collapse(ctx, name, c);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1window_1show(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jint s) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
nk_window_show(ctx, name, s);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1row_1dynamic(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloat height, jint cols) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_layout_row_dynamic(ctx, height, cols);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1row_1static(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloat height, jint item_width, jint cols) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_layout_row_static(ctx, height, item_width, cols);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1row_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint fmt, jfloat row_height, jint cols) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_layout_row_begin(ctx, fmt, row_height, cols);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1row_1push(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloat value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_layout_row_push(ctx, value);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1row_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_layout_row_end(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1row__JIFIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint fmt, jfloat height, jint cols, jlong ratioAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const float *ratio = (const float *)(intptr_t)ratioAddress;
UNUSED_PARAMS(__env, clazz)
nk_layout_row(ctx, fmt, height, cols, ratio);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1space_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint fmt, jfloat height, jint widget_count) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_layout_space_begin(ctx, fmt, height, widget_count);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1space_1push(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong rectAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
UNUSED_PARAMS(__env, clazz)
nk_layout_space_push(ctx, *rect);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1space_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_layout_space_end(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1space_1bounds(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_layout_space_bounds(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1space_1to_1screen(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong retAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_vec2 *ret = (struct nk_vec2 *)(intptr_t)retAddress;
UNUSED_PARAMS(__env, clazz)
*ret = nk_layout_space_to_screen(ctx, *ret);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1space_1to_1local(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong retAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_vec2 *ret = (struct nk_vec2 *)(intptr_t)retAddress;
UNUSED_PARAMS(__env, clazz)
*ret = nk_layout_space_to_local(ctx, *ret);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1space_1rect_1to_1screen(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong retAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_rect *ret = (struct nk_rect *)(intptr_t)retAddress;
UNUSED_PARAMS(__env, clazz)
*ret = nk_layout_space_rect_to_screen(ctx, *ret);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1space_1rect_1to_1local(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong retAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_rect *ret = (struct nk_rect *)(intptr_t)retAddress;
UNUSED_PARAMS(__env, clazz)
*ret = nk_layout_space_rect_to_local(ctx, *ret);
}
JNIEXPORT jfloat JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1ratio_1from_1pixel(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloat pixel_width) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jfloat)nk_layout_ratio_from_pixel(ctx, pixel_width);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1group_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong titleAddress, jint flags) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *title = (const char *)(intptr_t)titleAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_group_begin(ctx, layout, title, flags);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1group_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_group_end(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1tree_1push_1hashed(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint type, jlong titleAddress, jint initial_state, jlong hashAddress, jint len, jint seed) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *title = (const char *)(intptr_t)titleAddress;
const char *hash = (const char *)(intptr_t)hashAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_tree_push_hashed(ctx, type, title, initial_state, hash, len, seed);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1tree_1image_1push_1hashed(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint type, jlong imgAddress, jlong titleAddress, jint initial_state, jlong hashAddress, jint len, jint seed) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *title = (const char *)(intptr_t)titleAddress;
const char *hash = (const char *)(intptr_t)hashAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_tree_image_push_hashed(ctx, type, *img, title, initial_state, hash, len, seed);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1tree_1pop(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_tree_pop(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
nk_text(ctx, str, len, alignment);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1text_1colored(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jint alignment, jlong colorAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_text_colored(ctx, str, len, alignment, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1text_1wrap(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
nk_text_wrap(ctx, str, len);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1text_1wrap_1colored(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jlong colorAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_text_wrap_colored(ctx, str, len, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint align) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
nk_label(ctx, str, align);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1label_1colored(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint align, jlong colorAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_label_colored(ctx, str, align, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1label_1wrap(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
nk_label_wrap(ctx, str);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1label_1colored_1wrap(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jlong colorAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_label_colored_wrap(ctx, str, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1image(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
UNUSED_PARAMS(__env, clazz)
nk_image(ctx, *img);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong titleAddress, jint len) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *title = (const char *)(intptr_t)titleAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_text(ctx, title, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong titleAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *title = (const char *)(intptr_t)titleAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_label(ctx, title);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1color(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong colorAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_color(ctx, *color);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1symbol(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint symbol) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_symbol(ctx, symbol);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1image(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_image(ctx, *img);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1symbol_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint symbol, jlong textAddress, jint text_alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_symbol_label(ctx, symbol, text, text_alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1symbol_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint symbol, jlong textAddress, jint len, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_symbol_text(ctx, symbol, text, len, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1image_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong textAddress, jint text_alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_image_label(ctx, *img, text, text_alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1image_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong textAddress, jint len, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_image_text(ctx, *img, text, len, alignment);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1set_1behavior(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint behavior) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_button_set_behavior(ctx, behavior);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1push_1behavior(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint behavior) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_push_behavior(ctx, behavior);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1button_1pop_1behavior(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_button_pop_behavior(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1check_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint active) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_check_label(ctx, str, active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1check_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jint active) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_check_text(ctx, str, len, active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1check_1flags_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint flags, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_check_flags_label(ctx, str, flags, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1check_1flags_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jint flags, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_check_flags_text(ctx, str, len, flags, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1label__JJJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jlong activeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
int *active = (int *)(intptr_t)activeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_checkbox_label(ctx, str, active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1text__JJIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jlong activeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
int *active = (int *)(intptr_t)activeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_checkbox_text(ctx, str, len, active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1flags_1label__JJJI(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jlong flagsAddress, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
unsigned int *flags = (unsigned int *)(intptr_t)flagsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_checkbox_flags_label(ctx, str, flags, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1flags_1text__JJIJI(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jlong flagsAddress, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
unsigned int *flags = (unsigned int *)(intptr_t)flagsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_checkbox_flags_text(ctx, str, len, flags, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1radio_1label__JJJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jlong activeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
int *active = (int *)(intptr_t)activeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_radio_label(ctx, str, active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1radio_1text__JJIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jlong activeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
int *active = (int *)(intptr_t)activeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_radio_text(ctx, str, len, active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1option_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint active) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_option_label(ctx, str, active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1option_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jint active) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_option_text(ctx, str, len, active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1label__JJIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint align, jlong valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
int *value = (int *)(intptr_t)valueAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_selectable_label(ctx, str, align, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1text__JJIIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jint align, jlong valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
int *value = (int *)(intptr_t)valueAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_selectable_text(ctx, str, len, align, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1image_1label__JJJIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong strAddress, jint align, jlong valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *str = (const char *)(intptr_t)strAddress;
int *value = (int *)(intptr_t)valueAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_selectable_image_label(ctx, *img, str, align, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1image_1text__JJJIIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong strAddress, jint len, jint align, jlong valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *str = (const char *)(intptr_t)strAddress;
int *value = (int *)(intptr_t)valueAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_selectable_image_text(ctx, *img, str, len, align, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1select_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint align, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_select_label(ctx, str, align, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1select_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jint align, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_select_text(ctx, str, len, align, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1select_1image_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong strAddress, jint align, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_select_image_label(ctx, *img, str, align, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1select_1image_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong strAddress, jint len, jint align, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_select_image_text(ctx, *img, str, len, align, value);
}
JNIEXPORT jfloat JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1slide_1float(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloat min, jfloat val, jfloat max, jfloat step) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jfloat)nk_slide_float(ctx, min, val, max, step);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1slide_1int(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint min, jint val, jint max, jint step) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_slide_int(ctx, min, val, max, step);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1slider_1float__JFJFF(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloat min, jlong valAddress, jfloat max, jfloat step) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
float *val = (float *)(intptr_t)valAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_slider_float(ctx, min, val, max, step);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1slider_1int__JIJII(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint min, jlong valAddress, jint max, jint step) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
int *val = (int *)(intptr_t)valAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_slider_int(ctx, min, val, max, step);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1progress(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong curAddress, jlong max, jint modifyable) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
nk_size *cur = (nk_size *)(intptr_t)curAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_progress(ctx, cur, (nk_size)max, modifyable);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1prog(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong cur, jlong max, jint modifyable) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)nk_prog(ctx, (nk_size)cur, (nk_size)max, modifyable);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1picker(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong colorAddress, jint fmt) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
*color = nk_color_picker(ctx, *color, fmt);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1pick(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong colorAddress, jint fmt) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_color_pick(ctx, color, fmt);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1property_1int__JJIJIIF(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jint min, jlong valAddress, jint max, jint step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
int *val = (int *)(intptr_t)valAddress;
UNUSED_PARAMS(__env, clazz)
nk_property_int(ctx, name, min, val, max, step, inc_per_pixel);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1property_1float__JJFJFFF(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jfloat min, jlong valAddress, jfloat max, jfloat step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
float *val = (float *)(intptr_t)valAddress;
UNUSED_PARAMS(__env, clazz)
nk_property_float(ctx, name, min, val, max, step, inc_per_pixel);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1property_1double__JJDJDDF(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jdouble min, jlong valAddress, jdouble max, jdouble step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
double *val = (double *)(intptr_t)valAddress;
UNUSED_PARAMS(__env, clazz)
nk_property_double(ctx, name, min, val, max, step, inc_per_pixel);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1propertyi(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jint min, jint val, jint max, jint step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_propertyi(ctx, name, min, val, max, step, inc_per_pixel);
}
JNIEXPORT jfloat JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1propertyf(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jfloat min, jfloat val, jfloat max, jfloat step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
return (jfloat)nk_propertyf(ctx, name, min, val, max, step, inc_per_pixel);
}
JNIEXPORT jdouble JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1propertyd(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jdouble min, jdouble val, jdouble max, jdouble step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAMS(__env, clazz)
return (jdouble)nk_propertyd(ctx, name, min, val, max, step, inc_per_pixel);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1edit_1string__JIJJIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint flags, jlong memoryAddress, jlong lenAddress, jint max, jlong filterAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
char *memory = (char *)(intptr_t)memoryAddress;
int *len = (int *)(intptr_t)lenAddress;
nk_plugin_filter filter = (nk_plugin_filter)(intptr_t)filterAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_edit_string(ctx, flags, memory, len, max, filter);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1edit_1buffer(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint flags, jlong editAddress, jlong filterAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_text_edit *edit = (struct nk_text_edit *)(intptr_t)editAddress;
nk_plugin_filter filter = (nk_plugin_filter)(intptr_t)filterAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_edit_buffer(ctx, flags, edit, filter);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1edit_1string_1zero_1terminated(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint flags, jlong bufferAddress, jint max, jlong filterAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
char *buffer = (char *)(intptr_t)bufferAddress;
nk_plugin_filter filter = (nk_plugin_filter)(intptr_t)filterAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_edit_string_zero_terminated(ctx, flags, buffer, max, filter);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1chart_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint type, jint num, jfloat min, jfloat max) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_chart_begin(ctx, type, num, min, max);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1chart_1begin_1colored(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint type, jlong colorAddress, jlong activeAddress, jint num, jfloat min, jfloat max) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
struct nk_color *active = (struct nk_color *)(intptr_t)activeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_chart_begin_colored(ctx, type, *color, *active, num, min, max);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1chart_1add_1slot(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint type, jint count, jfloat min_value, jfloat max_value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_chart_add_slot(ctx, type, count, min_value, max_value);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1chart_1add_1slot_1colored(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint type, jlong colorAddress, jlong activeAddress, jint count, jfloat min_value, jfloat max_value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
struct nk_color *active = (struct nk_color *)(intptr_t)activeAddress;
UNUSED_PARAMS(__env, clazz)
nk_chart_add_slot_colored(ctx, type, *color, *active, count, min_value, max_value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1chart_1push(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloat value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_chart_push(ctx, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1chart_1push_1slot(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloat value, jint slot) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_chart_push_slot(ctx, value, slot);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1chart_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_chart_end(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1plot__JIJII(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint type, jlong valuesAddress, jint count, jint offset) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const float *values = (const float *)(intptr_t)valuesAddress;
UNUSED_PARAMS(__env, clazz)
nk_plot(ctx, type, values, count, offset);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1plot_1function(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint type, jlong userdataAddress, jlong value_getterAddress, jint count, jint offset) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
void *userdata = (void *)(intptr_t)userdataAddress;
nk_value_getter value_getter = (nk_value_getter)(intptr_t)value_getterAddress;
UNUSED_PARAMS(__env, clazz)
nk_plot_function(ctx, type, userdata, value_getter, count, offset);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1popup_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jint type, jlong titleAddress, jint flags, jlong rectAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *title = (const char *)(intptr_t)titleAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_popup_begin(ctx, layout, type, title, flags, *rect);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1popup_1close(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_popup_close(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1popup_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_popup_end(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong itemsAddress, jint count, jint selected, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char **items = (const char **)(intptr_t)itemsAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo(ctx, items, count, selected, item_height, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1separator(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong items_separated_by_separatorAddress, jint separator, jint selected, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *items_separated_by_separator = (const char *)(intptr_t)items_separated_by_separatorAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_separator(ctx, items_separated_by_separator, separator, selected, count, item_height, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1string(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong items_separated_by_zerosAddress, jint selected, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *items_separated_by_zeros = (const char *)(intptr_t)items_separated_by_zerosAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_string(ctx, items_separated_by_zeros, selected, count, item_height, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1callback(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong item_getterAddress, jlong userdataAddress, jint selected, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
nk_item_getter item_getter = (nk_item_getter)(intptr_t)item_getterAddress;
void *userdata = (void *)(intptr_t)userdataAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_callback(ctx, item_getter, userdata, selected, count, item_height, *size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combobox__JJIJIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong itemsAddress, jint count, jlong selectedAddress, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char **items = (const char **)(intptr_t)itemsAddress;
int *selected = (int *)(intptr_t)selectedAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
nk_combobox(ctx, items, count, selected, item_height, *size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combobox_1string__JJJIIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong items_separated_by_zerosAddress, jlong selectedAddress, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *items_separated_by_zeros = (const char *)(intptr_t)items_separated_by_zerosAddress;
int *selected = (int *)(intptr_t)selectedAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
nk_combobox_string(ctx, items_separated_by_zeros, selected, count, item_height, *size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combobox_1separator__JJIJIIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong items_separated_by_separatorAddress, jint separator, jlong selectedAddress, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *items_separated_by_separator = (const char *)(intptr_t)items_separated_by_separatorAddress;
int *selected = (int *)(intptr_t)selectedAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
nk_combobox_separator(ctx, items_separated_by_separator, separator, selected, count, item_height, *size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combobox_1callback__JJJJIIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong item_getterAddress, jlong userdataAddress, jlong selectedAddress, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
nk_item_getter item_getter = (nk_item_getter)(intptr_t)item_getterAddress;
void *userdata = (void *)(intptr_t)userdataAddress;
int *selected = (int *)(intptr_t)selectedAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
nk_combobox_callback(ctx, item_getter, userdata, selected, count, item_height, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1begin_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong selectedAddress, jint len, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *selected = (const char *)(intptr_t)selectedAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_begin_text(ctx, layout, selected, len, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1begin_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong selectedAddress, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *selected = (const char *)(intptr_t)selectedAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_begin_label(ctx, layout, selected, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1begin_1color(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong colorAddress, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_begin_color(ctx, layout, *color, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1begin_1symbol(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jint symbol, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_begin_symbol(ctx, layout, symbol, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1begin_1symbol_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong selectedAddress, jint symbol, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *selected = (const char *)(intptr_t)selectedAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_begin_symbol_label(ctx, layout, selected, symbol, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1begin_1symbol_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong selectedAddress, jint len, jint symbol, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *selected = (const char *)(intptr_t)selectedAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_begin_symbol_text(ctx, layout, selected, len, symbol, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1begin_1image(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong imgAddress, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_begin_image(ctx, layout, *img, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1begin_1image_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong selectedAddress, jlong imgAddress, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *selected = (const char *)(intptr_t)selectedAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_begin_image_label(ctx, layout, selected, *img, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1begin_1image_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong selectedAddress, jint len, jlong imgAddress, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *selected = (const char *)(intptr_t)selectedAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_begin_image_text(ctx, layout, selected, len, *img, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1item_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong textAddress, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_item_label(ctx, text, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1item_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong textAddress, jint len, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_item_text(ctx, text, len, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1item_1image_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong textAddress, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_item_image_label(ctx, *img, text, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1item_1image_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong textAddress, jint len, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_item_image_text(ctx, *img, text, len, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1item_1symbol_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint symbol, jlong textAddress, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_item_symbol_label(ctx, symbol, text, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1item_1symbol_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint symbol, jlong textAddress, jint len, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_combo_item_symbol_text(ctx, symbol, text, len, alignment);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1close(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_combo_close(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combo_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_combo_end(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1contextual_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jint flags, jlong sizeAddress, jlong trigger_boundsAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
struct nk_rect *trigger_bounds = (struct nk_rect *)(intptr_t)trigger_boundsAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_contextual_begin(ctx, layout, flags, *size, *trigger_bounds);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1contextual_1item_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong textAddress, jint len, jint align) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_contextual_item_text(ctx, text, len, align);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1contextual_1item_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong textAddress, jint align) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_contextual_item_label(ctx, text, align);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1contextual_1item_1image_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong textAddress, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_contextual_item_image_label(ctx, *img, text, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1contextual_1item_1image_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong textAddress, jint len, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_contextual_item_image_text(ctx, *img, text, len, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1contextual_1item_1symbol_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint symbol, jlong textAddress, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_contextual_item_symbol_label(ctx, symbol, text, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1contextual_1item_1symbol_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint symbol, jlong textAddress, jint len, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_contextual_item_symbol_text(ctx, symbol, text, len, alignment);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1contextual_1close(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_contextual_close(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1contextual_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_contextual_end(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1tooltip(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong textAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
nk_tooltip(ctx, text);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1tooltip_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jfloat width) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_tooltip_begin(ctx, layout, width);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1tooltip_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_tooltip_end(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menubar_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_menubar_begin(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menubar_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_menubar_end(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1begin_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong textAddress, jint len, jint align, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *text = (const char *)(intptr_t)textAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_begin_text(ctx, layout, text, len, align, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1begin_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong textAddress, jint align, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *text = (const char *)(intptr_t)textAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_begin_label(ctx, layout, text, align, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1begin_1image(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong textAddress, jlong imgAddress, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *text = (const char *)(intptr_t)textAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_begin_image(ctx, layout, text, *img, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1begin_1image_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong textAddress, jint len, jint align, jlong imgAddress, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *text = (const char *)(intptr_t)textAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_begin_image_text(ctx, layout, text, len, align, *img, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1begin_1image_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong textAddress, jint align, jlong imgAddress, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *text = (const char *)(intptr_t)textAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_begin_image_label(ctx, layout, text, align, *img, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1begin_1symbol(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong textAddress, jint symbol, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *text = (const char *)(intptr_t)textAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_begin_symbol(ctx, layout, text, symbol, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1begin_1symbol_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong textAddress, jint len, jint align, jint symbol, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *text = (const char *)(intptr_t)textAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_begin_symbol_text(ctx, layout, text, len, align, symbol, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1begin_1symbol_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong layoutAddress, jlong textAddress, jint align, jint symbol, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_panel *layout = (struct nk_panel *)(intptr_t)layoutAddress;
const char *text = (const char *)(intptr_t)textAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_begin_symbol_label(ctx, layout, text, align, symbol, *size);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1item_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong textAddress, jint len, jint align) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_item_text(ctx, text, len, align);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1item_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong textAddress, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_item_label(ctx, text, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1item_1image_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong textAddress, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_item_image_label(ctx, *img, text, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1item_1image_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong textAddress, jint len, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_item_image_text(ctx, *img, text, len, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1item_1symbol_1text(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint symbol, jlong textAddress, jint len, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_item_symbol_text(ctx, symbol, text, len, alignment);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1item_1symbol_1label(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint symbol, jlong textAddress, jint alignment) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_menu_item_symbol_label(ctx, symbol, text, alignment);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1close(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_menu_close(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1menu_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_menu_end(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1convert(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong cmdsAddress, jlong verticesAddress, jlong elementsAddress, jlong configAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_buffer *cmds = (struct nk_buffer *)(intptr_t)cmdsAddress;
struct nk_buffer *vertices = (struct nk_buffer *)(intptr_t)verticesAddress;
struct nk_buffer *elements = (struct nk_buffer *)(intptr_t)elementsAddress;
const struct nk_convert_config *config = (const struct nk_convert_config *)(intptr_t)configAddress;
UNUSED_PARAMS(__env, clazz)
nk_convert(ctx, cmds, vertices, elements, config);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_input_begin(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1motion(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint x, jint y) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_input_motion(ctx, x, y);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1key(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint key, jint down) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_input_key(ctx, key, down);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1button(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint id, jint x, jint y, jint down) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_input_button(ctx, id, x, y, down);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1scroll(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloat y) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_input_scroll(ctx, y);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1glyph(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong glyphAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
char *glyph = (char *)(intptr_t)glyphAddress;
UNUSED_PARAMS(__env, clazz)
nk_input_glyph(ctx, glyph);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1unicode(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint unicode) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_input_unicode(ctx, unicode);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_input_end(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1default(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_style_default(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1from_1table(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong tableAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const struct nk_color *table = (const struct nk_color *)(intptr_t)tableAddress;
UNUSED_PARAMS(__env, clazz)
nk_style_from_table(ctx, table);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1load_1cursor(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint style, jlong cursorAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_cursor *cursor = (struct nk_cursor *)(intptr_t)cursorAddress;
UNUSED_PARAMS(__env, clazz)
nk_style_load_cursor(ctx, style, cursor);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1load_1all_1cursors(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong cursorsAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_cursor *cursors = (struct nk_cursor *)(intptr_t)cursorsAddress;
UNUSED_PARAMS(__env, clazz)
nk_style_load_all_cursors(ctx, cursors);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1get_1color_1by_1name(JNIEnv *__env, jclass clazz, jint c) {
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_style_get_color_by_name(c);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1set_1font(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong fontAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const struct nk_user_font *font = (const struct nk_user_font *)(intptr_t)fontAddress;
UNUSED_PARAMS(__env, clazz)
nk_style_set_font(ctx, font);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1set_1cursor(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint style) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_set_cursor(ctx, style);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1show_1cursor(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_style_show_cursor(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1hide_1cursor(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_style_hide_cursor(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1push_1font(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong fontAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_user_font *font = (struct nk_user_font *)(intptr_t)fontAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_push_font(ctx, font);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1push_1float__JJF(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong addressAddress, jfloat value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
float *address = (float *)(intptr_t)addressAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_push_float(ctx, address, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1push_1vec2(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong addressAddress, jlong valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_vec2 *address = (struct nk_vec2 *)(intptr_t)addressAddress;
struct nk_vec2 *value = (struct nk_vec2 *)(intptr_t)valueAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_push_vec2(ctx, address, *value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1push_1style_1item(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong addressAddress, jlong valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_style_item *address = (struct nk_style_item *)(intptr_t)addressAddress;
struct nk_style_item *value = (struct nk_style_item *)(intptr_t)valueAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_push_style_item(ctx, address, *value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1push_1flags__JJI(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong addressAddress, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
nk_flags *address = (nk_flags *)(intptr_t)addressAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_push_flags(ctx, address, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1push_1color(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong addressAddress, jlong valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_color *address = (struct nk_color *)(intptr_t)addressAddress;
struct nk_color *value = (struct nk_color *)(intptr_t)valueAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_push_color(ctx, address, *value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1pop_1font(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_pop_font(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1pop_1float(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_pop_float(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1pop_1vec2(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_pop_vec2(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1pop_1style_1item(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_pop_style_item(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1pop_1flags(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_pop_flags(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1pop_1color(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_style_pop_color(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1widget_1bounds(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_widget_bounds(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1widget_1position(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_widget_position(ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1widget_1size(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong __result) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_widget_size(ctx);
}
JNIEXPORT jfloat JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1widget_1width(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jfloat)nk_widget_width(ctx);
}
JNIEXPORT jfloat JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1widget_1height(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jfloat)nk_widget_height(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1widget_1is_1hovered(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_widget_is_hovered(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1widget_1is_1mouse_1clicked(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint btn) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_widget_is_mouse_clicked(ctx, btn);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1widget_1has_1mouse_1click_1down(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint btn, jint down) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_widget_has_mouse_click_down(ctx, btn, down);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1spacing(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint cols) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
nk_spacing(ctx, cols);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1widget(JNIEnv *__env, jclass clazz, jlong boundsAddress, jlong ctxAddress) {
struct nk_rect *bounds = (struct nk_rect *)(intptr_t)boundsAddress;
const struct nk_context *ctx = (const struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_widget(bounds, ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1widget_1fitting(JNIEnv *__env, jclass clazz, jlong boundsAddress, jlong ctxAddress, jlong item_paddingAddress) {
struct nk_rect *bounds = (struct nk_rect *)(intptr_t)boundsAddress;
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_vec2 *item_padding = (struct nk_vec2 *)(intptr_t)item_paddingAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_widget_fitting(bounds, ctx, *item_padding);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgb(JNIEnv *__env, jclass clazz, jint r, jint g, jint b, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgb(r, g, b);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgb_1iv__J(JNIEnv *__env, jclass clazz, jlong rgbAddress, jlong __result) {
const int *rgb = (const int *)(intptr_t)rgbAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgb_iv(rgb);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgb_1bv(JNIEnv *__env, jclass clazz, jlong rgbAddress, jlong __result) {
const nk_byte *rgb = (const nk_byte *)(intptr_t)rgbAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgb_bv(rgb);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgb_1f(JNIEnv *__env, jclass clazz, jfloat r, jfloat g, jfloat b, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgb_f(r, g, b);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgb_1fv__J(JNIEnv *__env, jclass clazz, jlong rgbAddress, jlong __result) {
const float *rgb = (const float *)(intptr_t)rgbAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgb_fv(rgb);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgb_1hex(JNIEnv *__env, jclass clazz, jlong rgbAddress, jlong __result) {
const char *rgb = (const char *)(intptr_t)rgbAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgb_hex(rgb);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgba(JNIEnv *__env, jclass clazz, jint r, jint g, jint b, jint a, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgba(r, g, b, a);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgba_1u32(JNIEnv *__env, jclass clazz, jint in, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgba_u32(in);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgba_1iv__J(JNIEnv *__env, jclass clazz, jlong rgbaAddress, jlong __result) {
const int *rgba = (const int *)(intptr_t)rgbaAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgba_iv(rgba);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgba_1bv(JNIEnv *__env, jclass clazz, jlong rgbaAddress, jlong __result) {
const nk_byte *rgba = (const nk_byte *)(intptr_t)rgbaAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgba_bv(rgba);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgba_1f(JNIEnv *__env, jclass clazz, jfloat r, jfloat g, jfloat b, jfloat a, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgba_f(r, g, b, a);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgba_1fv__J(JNIEnv *__env, jclass clazz, jlong rgbaAddress, jlong __result) {
const float *rgba = (const float *)(intptr_t)rgbaAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgba_fv(rgba);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgba_1hex(JNIEnv *__env, jclass clazz, jlong rgbaAddress, jlong __result) {
const char *rgba = (const char *)(intptr_t)rgbaAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgba_hex(rgba);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsv(JNIEnv *__env, jclass clazz, jint h, jint s, jint v, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsv(h, s, v);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsv_1iv__J(JNIEnv *__env, jclass clazz, jlong hsvAddress, jlong __result) {
const int *hsv = (const int *)(intptr_t)hsvAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsv_iv(hsv);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsv_1bv(JNIEnv *__env, jclass clazz, jlong hsvAddress, jlong __result) {
const nk_byte *hsv = (const nk_byte *)(intptr_t)hsvAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsv_bv(hsv);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsv_1f(JNIEnv *__env, jclass clazz, jfloat h, jfloat s, jfloat v, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsv_f(h, s, v);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsv_1fv__J(JNIEnv *__env, jclass clazz, jlong hsvAddress, jlong __result) {
const float *hsv = (const float *)(intptr_t)hsvAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsv_fv(hsv);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsva(JNIEnv *__env, jclass clazz, jint h, jint s, jint v, jint a, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsva(h, s, v, a);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsva_1iv__J(JNIEnv *__env, jclass clazz, jlong hsvaAddress, jlong __result) {
const int *hsva = (const int *)(intptr_t)hsvaAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsva_iv(hsva);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsva_1bv(JNIEnv *__env, jclass clazz, jlong hsvaAddress, jlong __result) {
const nk_byte *hsva = (const nk_byte *)(intptr_t)hsvaAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsva_bv(hsva);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsva_1f(JNIEnv *__env, jclass clazz, jfloat h, jfloat s, jfloat v, jfloat a, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsva_f(h, s, v, a);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsva_1fv__J(JNIEnv *__env, jclass clazz, jlong hsvaAddress, jlong __result) {
const float *hsva = (const float *)(intptr_t)hsvaAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsva_fv(hsva);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1f__JJJJJ(JNIEnv *__env, jclass clazz, jlong rAddress, jlong gAddress, jlong bAddress, jlong aAddress, jlong colorAddress) {
float *r = (float *)(intptr_t)rAddress;
float *g = (float *)(intptr_t)gAddress;
float *b = (float *)(intptr_t)bAddress;
float *a = (float *)(intptr_t)aAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_f(r, g, b, a, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1fv__JJ(JNIEnv *__env, jclass clazz, jlong rgba_outAddress, jlong colorAddress) {
float *rgba_out = (float *)(intptr_t)rgba_outAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_fv(rgba_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1d__JJJJJ(JNIEnv *__env, jclass clazz, jlong rAddress, jlong gAddress, jlong bAddress, jlong aAddress, jlong colorAddress) {
double *r = (double *)(intptr_t)rAddress;
double *g = (double *)(intptr_t)gAddress;
double *b = (double *)(intptr_t)bAddress;
double *a = (double *)(intptr_t)aAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_d(r, g, b, a, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1dv__JJ(JNIEnv *__env, jclass clazz, jlong rgba_outAddress, jlong colorAddress) {
double *rgba_out = (double *)(intptr_t)rgba_outAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_dv(rgba_out, *color);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1u32(JNIEnv *__env, jclass clazz, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_color_u32(*color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hex_1rgba(JNIEnv *__env, jclass clazz, jlong outputAddress, jlong colorAddress) {
char *output = (char *)(intptr_t)outputAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hex_rgba(output, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hex_1rgb(JNIEnv *__env, jclass clazz, jlong outputAddress, jlong colorAddress) {
char *output = (char *)(intptr_t)outputAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hex_rgb(output, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1i__JJJJ(JNIEnv *__env, jclass clazz, jlong out_hAddress, jlong out_sAddress, jlong out_vAddress, jlong colorAddress) {
int *out_h = (int *)(intptr_t)out_hAddress;
int *out_s = (int *)(intptr_t)out_sAddress;
int *out_v = (int *)(intptr_t)out_vAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsv_i(out_h, out_s, out_v, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1b(JNIEnv *__env, jclass clazz, jlong out_hAddress, jlong out_sAddress, jlong out_vAddress, jlong colorAddress) {
nk_byte *out_h = (nk_byte *)(intptr_t)out_hAddress;
nk_byte *out_s = (nk_byte *)(intptr_t)out_sAddress;
nk_byte *out_v = (nk_byte *)(intptr_t)out_vAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsv_b(out_h, out_s, out_v, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1iv__JJ(JNIEnv *__env, jclass clazz, jlong hsv_outAddress, jlong colorAddress) {
int *hsv_out = (int *)(intptr_t)hsv_outAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsv_iv(hsv_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1bv(JNIEnv *__env, jclass clazz, jlong hsv_outAddress, jlong colorAddress) {
nk_byte *hsv_out = (nk_byte *)(intptr_t)hsv_outAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsv_bv(hsv_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1f__JJJJ(JNIEnv *__env, jclass clazz, jlong out_hAddress, jlong out_sAddress, jlong out_vAddress, jlong colorAddress) {
float *out_h = (float *)(intptr_t)out_hAddress;
float *out_s = (float *)(intptr_t)out_sAddress;
float *out_v = (float *)(intptr_t)out_vAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsv_f(out_h, out_s, out_v, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1fv__JJ(JNIEnv *__env, jclass clazz, jlong hsv_outAddress, jlong colorAddress) {
float *hsv_out = (float *)(intptr_t)hsv_outAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsv_fv(hsv_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1i__JJJJJ(JNIEnv *__env, jclass clazz, jlong hAddress, jlong sAddress, jlong vAddress, jlong aAddress, jlong colorAddress) {
int *h = (int *)(intptr_t)hAddress;
int *s = (int *)(intptr_t)sAddress;
int *v = (int *)(intptr_t)vAddress;
int *a = (int *)(intptr_t)aAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsva_i(h, s, v, a, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1b(JNIEnv *__env, jclass clazz, jlong hAddress, jlong sAddress, jlong vAddress, jlong aAddress, jlong colorAddress) {
nk_byte *h = (nk_byte *)(intptr_t)hAddress;
nk_byte *s = (nk_byte *)(intptr_t)sAddress;
nk_byte *v = (nk_byte *)(intptr_t)vAddress;
nk_byte *a = (nk_byte *)(intptr_t)aAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsva_b(h, s, v, a, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1iv__JJ(JNIEnv *__env, jclass clazz, jlong hsva_outAddress, jlong colorAddress) {
int *hsva_out = (int *)(intptr_t)hsva_outAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsva_iv(hsva_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1bv(JNIEnv *__env, jclass clazz, jlong hsva_outAddress, jlong colorAddress) {
nk_byte *hsva_out = (nk_byte *)(intptr_t)hsva_outAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsva_bv(hsva_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1f__JJJJJ(JNIEnv *__env, jclass clazz, jlong out_hAddress, jlong out_sAddress, jlong out_vAddress, jlong out_aAddress, jlong colorAddress) {
float *out_h = (float *)(intptr_t)out_hAddress;
float *out_s = (float *)(intptr_t)out_sAddress;
float *out_v = (float *)(intptr_t)out_vAddress;
float *out_a = (float *)(intptr_t)out_aAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsva_f(out_h, out_s, out_v, out_a, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1fv__JJ(JNIEnv *__env, jclass clazz, jlong hsva_outAddress, jlong colorAddress) {
float *hsva_out = (float *)(intptr_t)hsva_outAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_color_hsva_fv(hsva_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1handle_1ptr(JNIEnv *__env, jclass clazz, jlong ptrAddress, jlong __result) {
void *ptr = (void *)(intptr_t)ptrAddress;
UNUSED_PARAMS(__env, clazz)
*((nk_handle*)(intptr_t)__result) = nk_handle_ptr(ptr);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1handle_1id(JNIEnv *__env, jclass clazz, jint id, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((nk_handle*)(intptr_t)__result) = nk_handle_id(id);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1image_1handle(JNIEnv *__env, jclass clazz, jlong handleAddress, jlong __result) {
nk_handle *handle = (nk_handle *)(intptr_t)handleAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_image*)(intptr_t)__result) = nk_image_handle(*handle);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1image_1ptr(JNIEnv *__env, jclass clazz, jlong ptrAddress, jlong __result) {
void *ptr = (void *)(intptr_t)ptrAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_image*)(intptr_t)__result) = nk_image_ptr(ptr);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1image_1id(JNIEnv *__env, jclass clazz, jint id, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_image*)(intptr_t)__result) = nk_image_id(id);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1image_1is_1subimage(JNIEnv *__env, jclass clazz, jlong imgAddress) {
const struct nk_image *img = (const struct nk_image *)(intptr_t)imgAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_image_is_subimage(img);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1subimage_1ptr(JNIEnv *__env, jclass clazz, jlong ptrAddress, jshort w, jshort h, jlong sub_regionAddress, jlong __result) {
void *ptr = (void *)(intptr_t)ptrAddress;
struct nk_rect *sub_region = (struct nk_rect *)(intptr_t)sub_regionAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_image*)(intptr_t)__result) = nk_subimage_ptr(ptr, w, h, *sub_region);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1subimage_1id(JNIEnv *__env, jclass clazz, jint id, jshort w, jshort h, jlong sub_regionAddress, jlong __result) {
struct nk_rect *sub_region = (struct nk_rect *)(intptr_t)sub_regionAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_image*)(intptr_t)__result) = nk_subimage_id(id, w, h, *sub_region);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1subimage_1handle(JNIEnv *__env, jclass clazz, jlong handleAddress, jshort w, jshort h, jlong sub_regionAddress, jlong __result) {
nk_handle *handle = (nk_handle *)(intptr_t)handleAddress;
struct nk_rect *sub_region = (struct nk_rect *)(intptr_t)sub_regionAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_image*)(intptr_t)__result) = nk_subimage_handle(*handle, w, h, *sub_region);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1murmur_1hash(JNIEnv *__env, jclass clazz, jlong keyAddress, jint len, jint seed) {
const void *key = (const void *)(intptr_t)keyAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_murmur_hash(key, len, seed);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1triangle_1from_1direction(JNIEnv *__env, jclass clazz, jlong resultAddress, jlong rAddress, jfloat pad_x, jfloat pad_y, jint direction) {
struct nk_vec2 *result = (struct nk_vec2 *)(intptr_t)resultAddress;
struct nk_rect *r = (struct nk_rect *)(intptr_t)rAddress;
UNUSED_PARAMS(__env, clazz)
nk_triangle_from_direction(result, *r, pad_x, pad_y, direction);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1vec2(JNIEnv *__env, jclass clazz, jfloat x, jfloat y, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_vec2(x, y);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1vec2i(JNIEnv *__env, jclass clazz, jint x, jint y, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_vec2i(x, y);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1vec2v__J(JNIEnv *__env, jclass clazz, jlong xyAddress, jlong __result) {
const float *xy = (const float *)(intptr_t)xyAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_vec2v(xy);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1vec2iv__J(JNIEnv *__env, jclass clazz, jlong xyAddress, jlong __result) {
const int *xy = (const int *)(intptr_t)xyAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_vec2iv(xy);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1get_1null_1rect(JNIEnv *__env, jclass clazz, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_get_null_rect();
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rect(JNIEnv *__env, jclass clazz, jfloat x, jfloat y, jfloat w, jfloat h, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_rect(x, y, w, h);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1recti(JNIEnv *__env, jclass clazz, jint x, jint y, jint w, jint h, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_recti(x, y, w, h);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1recta(JNIEnv *__env, jclass clazz, jlong posAddress, jlong sizeAddress, jlong __result) {
struct nk_vec2 *pos = (struct nk_vec2 *)(intptr_t)posAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_recta(*pos, *size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rectv__J(JNIEnv *__env, jclass clazz, jlong xywhAddress, jlong __result) {
const float *xywh = (const float *)(intptr_t)xywhAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_rectv(xywh);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rectiv__J(JNIEnv *__env, jclass clazz, jlong xywhAddress, jlong __result) {
const int *xywh = (const int *)(intptr_t)xywhAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_rectiv(xywh);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rect_1pos(JNIEnv *__env, jclass clazz, jlong rAddress, jlong __result) {
struct nk_rect *r = (struct nk_rect *)(intptr_t)rAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_rect_pos(*r);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rect_1size(JNIEnv *__env, jclass clazz, jlong rAddress, jlong __result) {
struct nk_rect *r = (struct nk_rect *)(intptr_t)rAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_rect_size(*r);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1strlen(JNIEnv *__env, jclass clazz, jlong strAddress) {
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_strlen(str);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stricmp(JNIEnv *__env, jclass clazz, jlong s1Address, jlong s2Address) {
const char *s1 = (const char *)(intptr_t)s1Address;
const char *s2 = (const char *)(intptr_t)s2Address;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_stricmp(s1, s2);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stricmpn(JNIEnv *__env, jclass clazz, jlong s1Address, jlong s2Address, jint n) {
const char *s1 = (const char *)(intptr_t)s1Address;
const char *s2 = (const char *)(intptr_t)s2Address;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_stricmpn(s1, s2, n);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1strtoi(JNIEnv *__env, jclass clazz, jlong strAddress, jlong endptrAddress) {
const char *str = (const char *)(intptr_t)strAddress;
char **endptr = (char **)(intptr_t)endptrAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_strtoi(str, endptr);
}
JNIEXPORT jfloat JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1strtof(JNIEnv *__env, jclass clazz, jlong strAddress, jlong endptrAddress) {
const char *str = (const char *)(intptr_t)strAddress;
char **endptr = (char **)(intptr_t)endptrAddress;
UNUSED_PARAMS(__env, clazz)
return (jfloat)nk_strtof(str, endptr);
}
JNIEXPORT jdouble JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1strtod(JNIEnv *__env, jclass clazz, jlong strAddress, jlong endptrAddress) {
const char *str = (const char *)(intptr_t)strAddress;
char **endptr = (char **)(intptr_t)endptrAddress;
UNUSED_PARAMS(__env, clazz)
return (jdouble)nk_strtod(str, endptr);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1strfilter(JNIEnv *__env, jclass clazz, jlong strAddress, jlong regexpAddress) {
const char *str = (const char *)(intptr_t)strAddress;
const char *regexp = (const char *)(intptr_t)regexpAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_strfilter(str, regexp);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1strmatch_1fuzzy_1string__JJJ(JNIEnv *__env, jclass clazz, jlong strAddress, jlong patternAddress, jlong out_scoreAddress) {
const char *str = (const char *)(intptr_t)strAddress;
const char *pattern = (const char *)(intptr_t)patternAddress;
int *out_score = (int *)(intptr_t)out_scoreAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_strmatch_fuzzy_string(str, pattern, out_score);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1strmatch_1fuzzy_1text__JIJJ(JNIEnv *__env, jclass clazz, jlong txtAddress, jint txt_len, jlong patternAddress, jlong out_scoreAddress) {
const char *txt = (const char *)(intptr_t)txtAddress;
const char *pattern = (const char *)(intptr_t)patternAddress;
int *out_score = (int *)(intptr_t)out_scoreAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_strmatch_fuzzy_text(txt, txt_len, pattern, out_score);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1utf_1decode__JJI(JNIEnv *__env, jclass clazz, jlong cAddress, jlong uAddress, jint clen) {
const char *c = (const char *)(intptr_t)cAddress;
nk_rune *u = (nk_rune *)(intptr_t)uAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_utf_decode(c, u, clen);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1utf_1encode(JNIEnv *__env, jclass clazz, jint u, jlong cAddress, jint clen) {
char *c = (char *)(intptr_t)cAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_utf_encode(u, c, clen);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1utf_1len(JNIEnv *__env, jclass clazz, jlong strAddress, jint byte_len) {
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_utf_len(str, byte_len);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1utf_1at__JIIJJ(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint length, jint index, jlong unicodeAddress, jlong lenAddress) {
const char *buffer = (const char *)(intptr_t)bufferAddress;
nk_rune *unicode = (nk_rune *)(intptr_t)unicodeAddress;
int *len = (int *)(intptr_t)lenAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_utf_at(buffer, length, index, unicode, len);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1init(JNIEnv *__env, jclass clazz, jlong bufferAddress, jlong allocatorAddress, jlong size) {
struct nk_buffer *buffer = (struct nk_buffer *)(intptr_t)bufferAddress;
const struct nk_allocator *allocator = (const struct nk_allocator *)(intptr_t)allocatorAddress;
UNUSED_PARAMS(__env, clazz)
nk_buffer_init(buffer, allocator, (nk_size)size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1init_1fixed(JNIEnv *__env, jclass clazz, jlong bufferAddress, jlong memoryAddress, jlong size) {
struct nk_buffer *buffer = (struct nk_buffer *)(intptr_t)bufferAddress;
void *memory = (void *)(intptr_t)memoryAddress;
UNUSED_PARAMS(__env, clazz)
nk_buffer_init_fixed(buffer, memory, (nk_size)size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1info(JNIEnv *__env, jclass clazz, jlong statusAddress, jlong bufferAddress) {
struct nk_memory_status *status = (struct nk_memory_status *)(intptr_t)statusAddress;
struct nk_buffer *buffer = (struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
nk_buffer_info(status, buffer);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1push(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint type, jlong memoryAddress, jlong size, jlong align) {
struct nk_buffer *buffer = (struct nk_buffer *)(intptr_t)bufferAddress;
const void *memory = (const void *)(intptr_t)memoryAddress;
UNUSED_PARAMS(__env, clazz)
nk_buffer_push(buffer, type, memory, (nk_size)size, (nk_size)align);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1mark(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint type) {
struct nk_buffer *buffer = (struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
nk_buffer_mark(buffer, type);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1reset(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint type) {
struct nk_buffer *buffer = (struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
nk_buffer_reset(buffer, type);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1clear(JNIEnv *__env, jclass clazz, jlong bufferAddress) {
struct nk_buffer *buffer = (struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
nk_buffer_clear(buffer);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1free(JNIEnv *__env, jclass clazz, jlong bufferAddress) {
struct nk_buffer *buffer = (struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
nk_buffer_free(buffer);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1memory(JNIEnv *__env, jclass clazz, jlong bufferAddress) {
struct nk_buffer *buffer = (struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_buffer_memory(buffer);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1memory_1const(JNIEnv *__env, jclass clazz, jlong bufferAddress) {
const struct nk_buffer *buffer = (const struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_buffer_memory_const(buffer);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1buffer_1total(JNIEnv *__env, jclass clazz, jlong bufferAddress) {
struct nk_buffer *buffer = (struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)nk_buffer_total(buffer);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1init(JNIEnv *__env, jclass clazz, jlong strAddress, jlong allocatorAddress, jlong size) {
struct nk_str *str = (struct nk_str *)(intptr_t)strAddress;
const struct nk_allocator *allocator = (const struct nk_allocator *)(intptr_t)allocatorAddress;
UNUSED_PARAMS(__env, clazz)
nk_str_init(str, allocator, (nk_size)size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1init_1fixed(JNIEnv *__env, jclass clazz, jlong strAddress, jlong memoryAddress, jlong size) {
struct nk_str *str = (struct nk_str *)(intptr_t)strAddress;
void *memory = (void *)(intptr_t)memoryAddress;
UNUSED_PARAMS(__env, clazz)
nk_str_init_fixed(str, memory, (nk_size)size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1clear(JNIEnv *__env, jclass clazz, jlong strAddress) {
struct nk_str *str = (struct nk_str *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
nk_str_clear(str);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1free(JNIEnv *__env, jclass clazz, jlong strAddress) {
struct nk_str *str = (struct nk_str *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
nk_str_free(str);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1append_1text_1char(JNIEnv *__env, jclass clazz, jlong sAddress, jlong strAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_append_text_char(s, str, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1append_1str_1char(JNIEnv *__env, jclass clazz, jlong sAddress, jlong strAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_append_str_char(s, str);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1append_1text_1utf8(JNIEnv *__env, jclass clazz, jlong sAddress, jlong strAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_append_text_utf8(s, str, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1append_1str_1utf8(JNIEnv *__env, jclass clazz, jlong sAddress, jlong strAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_append_str_utf8(s, str);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1append_1text_1runes__JJI(JNIEnv *__env, jclass clazz, jlong sAddress, jlong runesAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const nk_rune *runes = (const nk_rune *)(intptr_t)runesAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_append_text_runes(s, runes, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1append_1str_1runes__JJ(JNIEnv *__env, jclass clazz, jlong sAddress, jlong runesAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const nk_rune *runes = (const nk_rune *)(intptr_t)runesAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_append_str_runes(s, runes);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1at_1char(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jlong strAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_insert_at_char(s, pos, str, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1at_1rune(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jlong strAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_insert_at_rune(s, pos, str, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1text_1char(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jlong strAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_insert_text_char(s, pos, str, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1str_1char(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jlong strAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_insert_str_char(s, pos, str);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1text_1utf8(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jlong strAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_insert_text_utf8(s, pos, str, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1str_1utf8(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jlong strAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_insert_str_utf8(s, pos, str);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1text_1runes__JIJI(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jlong runesAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const nk_rune *runes = (const nk_rune *)(intptr_t)runesAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_insert_text_runes(s, pos, runes, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1str_1runes__JIJ(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jlong runesAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
const nk_rune *runes = (const nk_rune *)(intptr_t)runesAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_insert_str_runes(s, pos, runes);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1remove_1chars(JNIEnv *__env, jclass clazz, jlong sAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAMS(__env, clazz)
nk_str_remove_chars(s, len);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1remove_1runes(JNIEnv *__env, jclass clazz, jlong strAddress, jint len) {
struct nk_str *str = (struct nk_str *)(intptr_t)strAddress;
UNUSED_PARAMS(__env, clazz)
nk_str_remove_runes(str, len);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1delete_1chars(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAMS(__env, clazz)
nk_str_delete_chars(s, pos, len);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1delete_1runes(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAMS(__env, clazz)
nk_str_delete_runes(s, pos, len);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1at_1char(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_str_at_char(s, pos);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1at_1rune__JIJJ(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jlong unicodeAddress, jlong lenAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
nk_rune *unicode = (nk_rune *)(intptr_t)unicodeAddress;
int *len = (int *)(intptr_t)lenAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_str_at_rune(s, pos, unicode, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1rune_1at(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos) {
const struct nk_str *s = (const struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_rune_at(s, pos);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1at_1char_1const(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos) {
const struct nk_str *s = (const struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_str_at_char_const(s, pos);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1at_1const__JIJJ(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jlong unicodeAddress, jlong lenAddress) {
const struct nk_str *s = (const struct nk_str *)(intptr_t)sAddress;
nk_rune *unicode = (nk_rune *)(intptr_t)unicodeAddress;
int *len = (int *)(intptr_t)lenAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_str_at_const(s, pos, unicode, len);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1get(JNIEnv *__env, jclass clazz, jlong sAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_str_get(s);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1get_1const(JNIEnv *__env, jclass clazz, jlong sAddress) {
const struct nk_str *s = (const struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk_str_get_const(s);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1len(JNIEnv *__env, jclass clazz, jlong sAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_len(s);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1len_1char(JNIEnv *__env, jclass clazz, jlong sAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_str_len_char(s);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1filter_1default(JNIEnv *__env, jclass clazz, jlong editAddress, jint unicode) {
const struct nk_text_edit *edit = (const struct nk_text_edit *)(intptr_t)editAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_filter_default(edit, unicode);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1filter_1ascii(JNIEnv *__env, jclass clazz, jlong editAddress, jint unicode) {
const struct nk_text_edit *edit = (const struct nk_text_edit *)(intptr_t)editAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_filter_ascii(edit, unicode);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1filter_1float(JNIEnv *__env, jclass clazz, jlong editAddress, jint unicode) {
const struct nk_text_edit *edit = (const struct nk_text_edit *)(intptr_t)editAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_filter_float(edit, unicode);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1filter_1decimal(JNIEnv *__env, jclass clazz, jlong editAddress, jint unicode) {
const struct nk_text_edit *edit = (const struct nk_text_edit *)(intptr_t)editAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_filter_decimal(edit, unicode);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1filter_1hex(JNIEnv *__env, jclass clazz, jlong editAddress, jint unicode) {
const struct nk_text_edit *edit = (const struct nk_text_edit *)(intptr_t)editAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_filter_hex(edit, unicode);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1filter_1oct(JNIEnv *__env, jclass clazz, jlong editAddress, jint unicode) {
const struct nk_text_edit *edit = (const struct nk_text_edit *)(intptr_t)editAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_filter_oct(edit, unicode);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1filter_1binary(JNIEnv *__env, jclass clazz, jlong editAddress, jint unicode) {
const struct nk_text_edit *edit = (const struct nk_text_edit *)(intptr_t)editAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_filter_binary(edit, unicode);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1init(JNIEnv *__env, jclass clazz, jlong boxAddress, jlong allocatorAddress, jlong size) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
struct nk_allocator *allocator = (struct nk_allocator *)(intptr_t)allocatorAddress;
UNUSED_PARAMS(__env, clazz)
nk_textedit_init(box, allocator, (nk_size)size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1init_1fixed(JNIEnv *__env, jclass clazz, jlong boxAddress, jlong memoryAddress, jlong size) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
void *memory = (void *)(intptr_t)memoryAddress;
UNUSED_PARAMS(__env, clazz)
nk_textedit_init_fixed(box, memory, (nk_size)size);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1free(JNIEnv *__env, jclass clazz, jlong boxAddress) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
UNUSED_PARAMS(__env, clazz)
nk_textedit_free(box);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1text(JNIEnv *__env, jclass clazz, jlong boxAddress, jlong textAddress, jint total_len) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
const char *text = (const char *)(intptr_t)textAddress;
UNUSED_PARAMS(__env, clazz)
nk_textedit_text(box, text, total_len);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1delete(JNIEnv *__env, jclass clazz, jlong boxAddress, jint where, jint len) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
UNUSED_PARAMS(__env, clazz)
nk_textedit_delete(box, where, len);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1delete_1selection(JNIEnv *__env, jclass clazz, jlong boxAddress) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
UNUSED_PARAMS(__env, clazz)
nk_textedit_delete_selection(box);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1select_1all(JNIEnv *__env, jclass clazz, jlong boxAddress) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
UNUSED_PARAMS(__env, clazz)
nk_textedit_select_all(box);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1cut(JNIEnv *__env, jclass clazz, jlong boxAddress) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_textedit_cut(box);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1paste(JNIEnv *__env, jclass clazz, jlong boxAddress, jlong ctextAddress, jint len) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
const char *ctext = (const char *)(intptr_t)ctextAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_textedit_paste(box, ctext, len);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1undo(JNIEnv *__env, jclass clazz, jlong boxAddress) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
UNUSED_PARAMS(__env, clazz)
nk_textedit_undo(box);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1textedit_1redo(JNIEnv *__env, jclass clazz, jlong boxAddress) {
struct nk_text_edit *box = (struct nk_text_edit *)(intptr_t)boxAddress;
UNUSED_PARAMS(__env, clazz)
nk_textedit_redo(box);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1line(JNIEnv *__env, jclass clazz, jlong bAddress, jfloat x0, jfloat y0, jfloat x1, jfloat y1, jfloat line_thickness, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_stroke_line(b, x0, y0, x1, y1, line_thickness, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1curve(JNIEnv *__env, jclass clazz, jlong bAddress, jfloat ax, jfloat ay, jfloat ctrl0x, jfloat ctrl0y, jfloat ctrl1x, jfloat ctrl1y, jfloat bx, jfloat by, jfloat line_thickness, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_stroke_curve(b, ax, ay, ctrl0x, ctrl0y, ctrl1x, ctrl1y, bx, by, line_thickness, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1rect(JNIEnv *__env, jclass clazz, jlong bAddress, jlong rectAddress, jfloat rounding, jfloat line_thickness, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_stroke_rect(b, *rect, rounding, line_thickness, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1circle(JNIEnv *__env, jclass clazz, jlong bAddress, jlong rectAddress, jfloat line_thickness, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_stroke_circle(b, *rect, line_thickness, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1arc(JNIEnv *__env, jclass clazz, jlong bAddress, jfloat cx, jfloat cy, jfloat radius, jfloat a_min, jfloat a_max, jfloat line_thickness, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_stroke_arc(b, cx, cy, radius, a_min, a_max, line_thickness, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1triangle(JNIEnv *__env, jclass clazz, jlong bAddress, jfloat x0, jfloat y0, jfloat x1, jfloat y1, jfloat x2, jfloat y2, jfloat line_thichness, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_stroke_triangle(b, x0, y0, x1, y1, x2, y2, line_thichness, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1polyline__JJIFJ(JNIEnv *__env, jclass clazz, jlong bAddress, jlong pointsAddress, jint point_count, jfloat line_thickness, jlong colAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
float *points = (float *)(intptr_t)pointsAddress;
struct nk_color *col = (struct nk_color *)(intptr_t)colAddress;
UNUSED_PARAMS(__env, clazz)
nk_stroke_polyline(b, points, point_count, line_thickness, *col);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1polygon__JJIFJ(JNIEnv *__env, jclass clazz, jlong bAddress, jlong pointsAddress, jint point_count, jfloat line_thickness, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
float *points = (float *)(intptr_t)pointsAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_stroke_polygon(b, points, point_count, line_thickness, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1fill_1rect(JNIEnv *__env, jclass clazz, jlong bAddress, jlong rectAddress, jfloat rounding, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_fill_rect(b, *rect, rounding, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1fill_1rect_1multi_1color(JNIEnv *__env, jclass clazz, jlong bAddress, jlong rectAddress, jlong leftAddress, jlong topAddress, jlong rightAddress, jlong bottomAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
struct nk_color *left = (struct nk_color *)(intptr_t)leftAddress;
struct nk_color *top = (struct nk_color *)(intptr_t)topAddress;
struct nk_color *right = (struct nk_color *)(intptr_t)rightAddress;
struct nk_color *bottom = (struct nk_color *)(intptr_t)bottomAddress;
UNUSED_PARAMS(__env, clazz)
nk_fill_rect_multi_color(b, *rect, *left, *top, *right, *bottom);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1fill_1circle(JNIEnv *__env, jclass clazz, jlong bAddress, jlong rectAddress, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_fill_circle(b, *rect, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1fill_1arc(JNIEnv *__env, jclass clazz, jlong bAddress, jfloat cx, jfloat cy, jfloat radius, jfloat a_min, jfloat a_max, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_fill_arc(b, cx, cy, radius, a_min, a_max, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1fill_1triangle(JNIEnv *__env, jclass clazz, jlong bAddress, jfloat x0, jfloat y0, jfloat x1, jfloat y1, jfloat x2, jfloat y2, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_fill_triangle(b, x0, y0, x1, y1, x2, y2, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1fill_1polygon__JJIJ(JNIEnv *__env, jclass clazz, jlong bAddress, jlong pointsAddress, jint point_count, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
float *points = (float *)(intptr_t)pointsAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_fill_polygon(b, points, point_count, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1push_1scissor(JNIEnv *__env, jclass clazz, jlong bAddress, jlong rectAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
UNUSED_PARAMS(__env, clazz)
nk_push_scissor(b, *rect);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1image(JNIEnv *__env, jclass clazz, jlong bAddress, jlong rectAddress, jlong imgAddress, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
const struct nk_image *img = (const struct nk_image *)(intptr_t)imgAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_image(b, *rect, img, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1text(JNIEnv *__env, jclass clazz, jlong bAddress, jlong rectAddress, jlong stringAddress, jint length, jlong fontAddress, jlong bgAddress, jlong fgAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
const char *string = (const char *)(intptr_t)stringAddress;
const struct nk_user_font *font = (const struct nk_user_font *)(intptr_t)fontAddress;
struct nk_color *bg = (struct nk_color *)(intptr_t)bgAddress;
struct nk_color *fg = (struct nk_color *)(intptr_t)fgAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_text(b, *rect, string, length, font, *bg, *fg);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1_1next(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong cmdAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const struct nk_command *cmd = (const struct nk_command *)(intptr_t)cmdAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk__next(ctx, cmd);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk__begin(ctx);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1has_1mouse_1click(JNIEnv *__env, jclass clazz, jlong iAddress, jint id) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_has_mouse_click(i, id);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1has_1mouse_1click_1in_1rect(JNIEnv *__env, jclass clazz, jlong iAddress, jint id, jlong rectAddress) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_has_mouse_click_in_rect(i, id, *rect);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1has_1mouse_1click_1down_1in_1rect(JNIEnv *__env, jclass clazz, jlong iAddress, jint id, jlong rectAddress, jint down) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_has_mouse_click_down_in_rect(i, id, *rect, down);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1is_1mouse_1click_1in_1rect(JNIEnv *__env, jclass clazz, jlong iAddress, jint id, jlong rectAddress) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_is_mouse_click_in_rect(i, id, *rect);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1is_1mouse_1click_1down_1in_1rect(JNIEnv *__env, jclass clazz, jlong iAddress, jint id, jlong bAddress, jint down) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
struct nk_rect *b = (struct nk_rect *)(intptr_t)bAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_is_mouse_click_down_in_rect(i, id, *b, down);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1any_1mouse_1click_1in_1rect(JNIEnv *__env, jclass clazz, jlong iAddress, jlong rectAddress) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_any_mouse_click_in_rect(i, *rect);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1is_1mouse_1prev_1hovering_1rect(JNIEnv *__env, jclass clazz, jlong iAddress, jlong rectAddress) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_is_mouse_prev_hovering_rect(i, *rect);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1is_1mouse_1hovering_1rect(JNIEnv *__env, jclass clazz, jlong iAddress, jlong rectAddress) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_is_mouse_hovering_rect(i, *rect);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1mouse_1clicked(JNIEnv *__env, jclass clazz, jlong iAddress, jint id, jlong rectAddress) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_mouse_clicked(i, id, *rect);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1is_1mouse_1down(JNIEnv *__env, jclass clazz, jlong iAddress, jint id) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_is_mouse_down(i, id);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1is_1mouse_1pressed(JNIEnv *__env, jclass clazz, jlong iAddress, jint id) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_is_mouse_pressed(i, id);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1is_1mouse_1released(JNIEnv *__env, jclass clazz, jlong iAddress, jint id) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_is_mouse_released(i, id);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1is_1key_1pressed(JNIEnv *__env, jclass clazz, jlong iAddress, jint key) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_is_key_pressed(i, key);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1is_1key_1released(JNIEnv *__env, jclass clazz, jlong iAddress, jint key) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_is_key_released(i, key);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1input_1is_1key_1down(JNIEnv *__env, jclass clazz, jlong iAddress, jint key) {
const struct nk_input *i = (const struct nk_input *)(intptr_t)iAddress;
UNUSED_PARAMS(__env, clazz)
return (jint)nk_input_is_key_down(i, key);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1init(JNIEnv *__env, jclass clazz, jlong listAddress) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_init(list);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1setup(JNIEnv *__env, jclass clazz, jlong canvasAddress, jlong configAddress, jlong cmdsAddress, jlong verticesAddress, jlong elementsAddress) {
struct nk_draw_list *canvas = (struct nk_draw_list *)(intptr_t)canvasAddress;
const struct nk_convert_config *config = (const struct nk_convert_config *)(intptr_t)configAddress;
struct nk_buffer *cmds = (struct nk_buffer *)(intptr_t)cmdsAddress;
struct nk_buffer *vertices = (struct nk_buffer *)(intptr_t)verticesAddress;
struct nk_buffer *elements = (struct nk_buffer *)(intptr_t)elementsAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_setup(canvas, config, cmds, vertices, elements);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1clear(JNIEnv *__env, jclass clazz, jlong listAddress) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_clear(list);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1_1draw_1list_1begin(JNIEnv *__env, jclass clazz, jlong listAddress, jlong bufferAddress) {
const struct nk_draw_list *list = (const struct nk_draw_list *)(intptr_t)listAddress;
const struct nk_buffer *buffer = (const struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk__draw_list_begin(list, buffer);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1_1draw_1list_1next(JNIEnv *__env, jclass clazz, jlong cmdAddress, jlong bufferAddress, jlong listAddress) {
const struct nk_draw_command *cmd = (const struct nk_draw_command *)(intptr_t)cmdAddress;
const struct nk_buffer *buffer = (const struct nk_buffer *)(intptr_t)bufferAddress;
const struct nk_draw_list *list = (const struct nk_draw_list *)(intptr_t)listAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk__draw_list_next(cmd, buffer, list);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1_1draw_1begin(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong bufferAddress) {
const struct nk_context *ctx = (const struct nk_context *)(intptr_t)ctxAddress;
const struct nk_buffer *buffer = (const struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk__draw_begin(ctx, buffer);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1_1draw_1end(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong bufferAddress) {
const struct nk_context *ctx = (const struct nk_context *)(intptr_t)ctxAddress;
const struct nk_buffer *buffer = (const struct nk_buffer *)(intptr_t)bufferAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk__draw_end(ctx, buffer);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1_1draw_1next(JNIEnv *__env, jclass clazz, jlong cmdAddress, jlong bufferAddress, jlong ctxAddress) {
const struct nk_draw_command *cmd = (const struct nk_draw_command *)(intptr_t)cmdAddress;
const struct nk_buffer *buffer = (const struct nk_buffer *)(intptr_t)bufferAddress;
const struct nk_context *ctx = (const struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAMS(__env, clazz)
return (jlong)(intptr_t)nk__draw_next(cmd, buffer, ctx);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1path_1clear(JNIEnv *__env, jclass clazz, jlong listAddress) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_path_clear(list);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1path_1line_1to(JNIEnv *__env, jclass clazz, jlong listAddress, jlong posAddress) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *pos = (struct nk_vec2 *)(intptr_t)posAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_path_line_to(list, *pos);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1path_1arc_1to_1fast(JNIEnv *__env, jclass clazz, jlong listAddress, jlong centerAddress, jfloat radius, jint a_min, jint a_max) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *center = (struct nk_vec2 *)(intptr_t)centerAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_path_arc_to_fast(list, *center, radius, a_min, a_max);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1path_1arc_1to(JNIEnv *__env, jclass clazz, jlong listAddress, jlong centerAddress, jfloat radius, jfloat a_min, jfloat a_max, jint segments) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *center = (struct nk_vec2 *)(intptr_t)centerAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_path_arc_to(list, *center, radius, a_min, a_max, segments);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1path_1rect_1to(JNIEnv *__env, jclass clazz, jlong listAddress, jlong aAddress, jlong bAddress, jfloat rounding) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *a = (struct nk_vec2 *)(intptr_t)aAddress;
struct nk_vec2 *b = (struct nk_vec2 *)(intptr_t)bAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_path_rect_to(list, *a, *b, rounding);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1path_1curve_1to(JNIEnv *__env, jclass clazz, jlong listAddress, jlong p2Address, jlong p3Address, jlong p4Address, jint num_segments) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *p2 = (struct nk_vec2 *)(intptr_t)p2Address;
struct nk_vec2 *p3 = (struct nk_vec2 *)(intptr_t)p3Address;
struct nk_vec2 *p4 = (struct nk_vec2 *)(intptr_t)p4Address;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_path_curve_to(list, *p2, *p3, *p4, num_segments);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1path_1fill(JNIEnv *__env, jclass clazz, jlong listAddress, jlong colorAddress) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_path_fill(list, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1path_1stroke(JNIEnv *__env, jclass clazz, jlong listAddress, jlong colorAddress, jint closed, jfloat thickness) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_path_stroke(list, *color, closed, thickness);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1stroke_1line(JNIEnv *__env, jclass clazz, jlong listAddress, jlong aAddress, jlong bAddress, jlong colorAddress, jfloat thickness) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *a = (struct nk_vec2 *)(intptr_t)aAddress;
struct nk_vec2 *b = (struct nk_vec2 *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_stroke_line(list, *a, *b, *color, thickness);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1stroke_1rect(JNIEnv *__env, jclass clazz, jlong listAddress, jlong rectAddress, jlong colorAddress, jfloat rounding, jfloat thickness) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_stroke_rect(list, *rect, *color, rounding, thickness);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1stroke_1triangle(JNIEnv *__env, jclass clazz, jlong listAddress, jlong aAddress, jlong bAddress, jlong cAddress, jlong colorAddress, jfloat thickness) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *a = (struct nk_vec2 *)(intptr_t)aAddress;
struct nk_vec2 *b = (struct nk_vec2 *)(intptr_t)bAddress;
struct nk_vec2 *c = (struct nk_vec2 *)(intptr_t)cAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_stroke_triangle(list, *a, *b, *c, *color, thickness);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1stroke_1circle(JNIEnv *__env, jclass clazz, jlong listAddress, jlong centerAddress, jfloat radius, jlong colorAddress, jint segs, jfloat thickness) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *center = (struct nk_vec2 *)(intptr_t)centerAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_stroke_circle(list, *center, radius, *color, segs, thickness);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1stroke_1curve(JNIEnv *__env, jclass clazz, jlong listAddress, jlong p0Address, jlong cp0Address, jlong cp1Address, jlong p1Address, jlong colorAddress, jint segments, jfloat thickness) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *p0 = (struct nk_vec2 *)(intptr_t)p0Address;
struct nk_vec2 *cp0 = (struct nk_vec2 *)(intptr_t)cp0Address;
struct nk_vec2 *cp1 = (struct nk_vec2 *)(intptr_t)cp1Address;
struct nk_vec2 *p1 = (struct nk_vec2 *)(intptr_t)p1Address;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_stroke_curve(list, *p0, *cp0, *cp1, *p1, *color, segments, thickness);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1stroke_1poly_1line(JNIEnv *__env, jclass clazz, jlong listAddress, jlong pntsAddress, jint cnt, jlong colorAddress, jint closed, jfloat thickness, jint aliasing) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
const struct nk_vec2 *pnts = (const struct nk_vec2 *)(intptr_t)pntsAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_stroke_poly_line(list, pnts, cnt, *color, closed, thickness, aliasing);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1fill_1rect(JNIEnv *__env, jclass clazz, jlong listAddress, jlong rectAddress, jlong colorAddress, jfloat rounding) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_fill_rect(list, *rect, *color, rounding);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1fill_1rect_1multi_1color(JNIEnv *__env, jclass clazz, jlong listAddress, jlong rectAddress, jlong leftAddress, jlong topAddress, jlong rightAddress, jlong bottomAddress) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
struct nk_color *left = (struct nk_color *)(intptr_t)leftAddress;
struct nk_color *top = (struct nk_color *)(intptr_t)topAddress;
struct nk_color *right = (struct nk_color *)(intptr_t)rightAddress;
struct nk_color *bottom = (struct nk_color *)(intptr_t)bottomAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_fill_rect_multi_color(list, *rect, *left, *top, *right, *bottom);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1fill_1triangle(JNIEnv *__env, jclass clazz, jlong listAddress, jlong aAddress, jlong bAddress, jlong cAddress, jlong colorAddress) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *a = (struct nk_vec2 *)(intptr_t)aAddress;
struct nk_vec2 *b = (struct nk_vec2 *)(intptr_t)bAddress;
struct nk_vec2 *c = (struct nk_vec2 *)(intptr_t)cAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_fill_triangle(list, *a, *b, *c, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1fill_1circle(JNIEnv *__env, jclass clazz, jlong listAddress, jlong centerAddress, jfloat radius, jlong colAddress, jint segs) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_vec2 *center = (struct nk_vec2 *)(intptr_t)centerAddress;
struct nk_color *col = (struct nk_color *)(intptr_t)colAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_fill_circle(list, *center, radius, *col, segs);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1fill_1poly_1convex(JNIEnv *__env, jclass clazz, jlong listAddress, jlong pointsAddress, jint count, jlong colorAddress, jint aliasing) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
const struct nk_vec2 *points = (const struct nk_vec2 *)(intptr_t)pointsAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_fill_poly_convex(list, points, count, *color, aliasing);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1add_1image(JNIEnv *__env, jclass clazz, jlong listAddress, jlong textureAddress, jlong rectAddress, jlong colorAddress) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
struct nk_image *texture = (struct nk_image *)(intptr_t)textureAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_add_image(list, *texture, *rect, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1add_1text(JNIEnv *__env, jclass clazz, jlong listAddress, jlong fontAddress, jlong rectAddress, jlong textAddress, jint len, jfloat font_height, jlong colorAddress) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
const struct nk_user_font *font = (const struct nk_user_font *)(intptr_t)fontAddress;
struct nk_rect *rect = (struct nk_rect *)(intptr_t)rectAddress;
const char *text = (const char *)(intptr_t)textAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_add_text(list, font, *rect, text, len, font_height, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1draw_1list_1push_1userdata(JNIEnv *__env, jclass clazz, jlong listAddress, jlong userdataAddress) {
struct nk_draw_list *list = (struct nk_draw_list *)(intptr_t)listAddress;
nk_handle *userdata = (nk_handle *)(intptr_t)userdataAddress;
UNUSED_PARAMS(__env, clazz)
nk_draw_list_push_userdata(list, *userdata);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1item_1image(JNIEnv *__env, jclass clazz, jlong imgAddress, jlong __result) {
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_style_item*)(intptr_t)__result) = nk_style_item_image(*img);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1item_1color(JNIEnv *__env, jclass clazz, jlong colorAddress, jlong __result) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAMS(__env, clazz)
*((struct nk_style_item*)(intptr_t)__result) = nk_style_item_color(*color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1item_1hide(JNIEnv *__env, jclass clazz, jlong __result) {
UNUSED_PARAMS(__env, clazz)
*((struct nk_style_item*)(intptr_t)__result) = nk_style_item_hide();
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1layout_1row__JIFI_3F(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint fmt, jfloat height, jint cols, jfloatArray ratioAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
jfloat *ratio = (*__env)->GetPrimitiveArrayCritical(__env, ratioAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_layout_row(ctx, fmt, height, cols, (const float *)ratio);
(*__env)->ReleasePrimitiveArrayCritical(__env, ratioAddress, ratio, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1layout_1row__JIFI_3F(jlong ctxAddress, jint fmt, jfloat height, jint cols, jint ratio__length, jfloat* ratio) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAM(ratio__length)
nk_layout_row(ctx, fmt, height, cols, (const float *)ratio);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1label__JJ_3I(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jintArray activeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
jint __result;
jint *active = (*__env)->GetPrimitiveArrayCritical(__env, activeAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_checkbox_label(ctx, str, (int *)active);
(*__env)->ReleasePrimitiveArrayCritical(__env, activeAddress, active, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1label__JJ_3I(jlong ctxAddress, jlong strAddress, jint active__length, jint* active) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAM(active__length)
return (jint)nk_checkbox_label(ctx, str, (int *)active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1text__JJI_3I(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jintArray activeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
jint __result;
jint *active = (*__env)->GetPrimitiveArrayCritical(__env, activeAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_checkbox_text(ctx, str, len, (int *)active);
(*__env)->ReleasePrimitiveArrayCritical(__env, activeAddress, active, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1text__JJI_3I(jlong ctxAddress, jlong strAddress, jint len, jint active__length, jint* active) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAM(active__length)
return (jint)nk_checkbox_text(ctx, str, len, (int *)active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1flags_1label__JJ_3II(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jintArray flagsAddress, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
jint __result;
jint *flags = (*__env)->GetPrimitiveArrayCritical(__env, flagsAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_checkbox_flags_label(ctx, str, (unsigned int *)flags, value);
(*__env)->ReleasePrimitiveArrayCritical(__env, flagsAddress, flags, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1flags_1label__JJ_3II(jlong ctxAddress, jlong strAddress, jint flags__length, jint* flags, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAM(flags__length)
return (jint)nk_checkbox_flags_label(ctx, str, (unsigned int *)flags, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1flags_1text__JJI_3II(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jintArray flagsAddress, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
jint __result;
jint *flags = (*__env)->GetPrimitiveArrayCritical(__env, flagsAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_checkbox_flags_text(ctx, str, len, (unsigned int *)flags, value);
(*__env)->ReleasePrimitiveArrayCritical(__env, flagsAddress, flags, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1checkbox_1flags_1text__JJI_3II(jlong ctxAddress, jlong strAddress, jint len, jint flags__length, jint* flags, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAM(flags__length)
return (jint)nk_checkbox_flags_text(ctx, str, len, (unsigned int *)flags, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1radio_1label__JJ_3I(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jintArray activeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
jint __result;
jint *active = (*__env)->GetPrimitiveArrayCritical(__env, activeAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_radio_label(ctx, str, (int *)active);
(*__env)->ReleasePrimitiveArrayCritical(__env, activeAddress, active, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1radio_1label__JJ_3I(jlong ctxAddress, jlong strAddress, jint active__length, jint* active) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAM(active__length)
return (jint)nk_radio_label(ctx, str, (int *)active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1radio_1text__JJI_3I(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jintArray activeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
jint __result;
jint *active = (*__env)->GetPrimitiveArrayCritical(__env, activeAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_radio_text(ctx, str, len, (int *)active);
(*__env)->ReleasePrimitiveArrayCritical(__env, activeAddress, active, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1radio_1text__JJI_3I(jlong ctxAddress, jlong strAddress, jint len, jint active__length, jint* active) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAM(active__length)
return (jint)nk_radio_text(ctx, str, len, (int *)active);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1label__JJI_3I(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint align, jintArray valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
jint __result;
jint *value = (*__env)->GetPrimitiveArrayCritical(__env, valueAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_selectable_label(ctx, str, align, (int *)value);
(*__env)->ReleasePrimitiveArrayCritical(__env, valueAddress, value, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1label__JJI_3I(jlong ctxAddress, jlong strAddress, jint align, jint value__length, jint* value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAM(value__length)
return (jint)nk_selectable_label(ctx, str, align, (int *)value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1text__JJII_3I(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong strAddress, jint len, jint align, jintArray valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
jint __result;
jint *value = (*__env)->GetPrimitiveArrayCritical(__env, valueAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_selectable_text(ctx, str, len, align, (int *)value);
(*__env)->ReleasePrimitiveArrayCritical(__env, valueAddress, value, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1text__JJII_3I(jlong ctxAddress, jlong strAddress, jint len, jint align, jint value__length, jint* value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAM(value__length)
return (jint)nk_selectable_text(ctx, str, len, align, (int *)value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1image_1label__JJJI_3I(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong strAddress, jint align, jintArray valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *str = (const char *)(intptr_t)strAddress;
jint __result;
jint *value = (*__env)->GetPrimitiveArrayCritical(__env, valueAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_selectable_image_label(ctx, *img, str, align, (int *)value);
(*__env)->ReleasePrimitiveArrayCritical(__env, valueAddress, value, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1image_1label__JJJI_3I(jlong ctxAddress, jlong imgAddress, jlong strAddress, jint align, jint value__length, jint* value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAM(value__length)
return (jint)nk_selectable_image_label(ctx, *img, str, align, (int *)value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1image_1text__JJJII_3I(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong imgAddress, jlong strAddress, jint len, jint align, jintArray valueAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *str = (const char *)(intptr_t)strAddress;
jint __result;
jint *value = (*__env)->GetPrimitiveArrayCritical(__env, valueAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_selectable_image_text(ctx, *img, str, len, align, (int *)value);
(*__env)->ReleasePrimitiveArrayCritical(__env, valueAddress, value, 0);
return __result;
}
#ifdef LWJGL_WINDOWS
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1selectable_1image_1text__JJJII_3I(jlong ctxAddress, jlong imgAddress, jlong strAddress, jint len, jint align, jint value__length, jint* value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
struct nk_image *img = (struct nk_image *)(intptr_t)imgAddress;
const char *str = (const char *)(intptr_t)strAddress;
UNUSED_PARAM(value__length)
return (jint)nk_selectable_image_text(ctx, *img, str, len, align, (int *)value);
}
#endif
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1slider_1float__JF_3FFF(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloat min, jfloatArray valAddress, jfloat max, jfloat step) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
jint __result;
jfloat *val = (*__env)->GetPrimitiveArrayCritical(__env, valAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_slider_float(ctx, min, (float *)val, max, step);
(*__env)->ReleasePrimitiveArrayCritical(__env, valAddress, val, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1slider_1float__JF_3FFF(jlong ctxAddress, jfloat min, jint val__length, jfloat* val, jfloat max, jfloat step) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAM(val__length)
return (jint)nk_slider_float(ctx, min, (float *)val, max, step);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1slider_1int__JI_3III(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint min, jintArray valAddress, jint max, jint step) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
jint __result;
jint *val = (*__env)->GetPrimitiveArrayCritical(__env, valAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_slider_int(ctx, min, (int *)val, max, step);
(*__env)->ReleasePrimitiveArrayCritical(__env, valAddress, val, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1slider_1int__JI_3III(jlong ctxAddress, jint min, jint val__length, jint* val, jint max, jint step) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAM(val__length)
return (jint)nk_slider_int(ctx, min, (int *)val, max, step);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1property_1int__JJI_3IIIF(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jint min, jintArray valAddress, jint max, jint step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
jint *val = (*__env)->GetPrimitiveArrayCritical(__env, valAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_property_int(ctx, name, min, (int *)val, max, step, inc_per_pixel);
(*__env)->ReleasePrimitiveArrayCritical(__env, valAddress, val, 0);
}
#ifdef LWJGL_WINDOWS
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1property_1int__JJI_3IIIF(jlong ctxAddress, jlong nameAddress, jint min, jint val__length, jint* val, jint max, jint step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAM(val__length)
nk_property_int(ctx, name, min, (int *)val, max, step, inc_per_pixel);
}
#endif
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1property_1float__JJF_3FFFF(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jfloat min, jfloatArray valAddress, jfloat max, jfloat step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
jfloat *val = (*__env)->GetPrimitiveArrayCritical(__env, valAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_property_float(ctx, name, min, (float *)val, max, step, inc_per_pixel);
(*__env)->ReleasePrimitiveArrayCritical(__env, valAddress, val, 0);
}
#ifdef LWJGL_WINDOWS
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1property_1float__JJF_3FFFF(jlong ctxAddress, jlong nameAddress, jfloat min, jint val__length, jfloat* val, jfloat max, jfloat step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAM(val__length)
nk_property_float(ctx, name, min, (float *)val, max, step, inc_per_pixel);
}
#endif
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1property_1double__JJD_3DDDF(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong nameAddress, jdouble min, jdoubleArray valAddress, jdouble max, jdouble step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
jdouble *val = (*__env)->GetPrimitiveArrayCritical(__env, valAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_property_double(ctx, name, min, (double *)val, max, step, inc_per_pixel);
(*__env)->ReleasePrimitiveArrayCritical(__env, valAddress, val, 0);
}
#ifdef LWJGL_WINDOWS
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1property_1double__JJD_3DDDF(jlong ctxAddress, jlong nameAddress, jdouble min, jint val__length, jdouble* val, jdouble max, jdouble step, jfloat inc_per_pixel) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *name = (const char *)(intptr_t)nameAddress;
UNUSED_PARAM(val__length)
nk_property_double(ctx, name, min, (double *)val, max, step, inc_per_pixel);
}
#endif
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1edit_1string__JIJ_3IIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint flags, jlong memoryAddress, jintArray lenAddress, jint max, jlong filterAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
char *memory = (char *)(intptr_t)memoryAddress;
nk_plugin_filter filter = (nk_plugin_filter)(intptr_t)filterAddress;
jint __result;
jint *len = (*__env)->GetPrimitiveArrayCritical(__env, lenAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_edit_string(ctx, flags, memory, (int *)len, max, filter);
(*__env)->ReleasePrimitiveArrayCritical(__env, lenAddress, len, 0);
return __result;
}
#ifdef LWJGL_WINDOWS
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1edit_1string__JIJ_3IIJ(jlong ctxAddress, jint flags, jlong memoryAddress, jint len__length, jint* len, jint max, jlong filterAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
char *memory = (char *)(intptr_t)memoryAddress;
nk_plugin_filter filter = (nk_plugin_filter)(intptr_t)filterAddress;
UNUSED_PARAM(len__length)
return (jint)nk_edit_string(ctx, flags, memory, (int *)len, max, filter);
}
#endif
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1plot__JI_3FII(JNIEnv *__env, jclass clazz, jlong ctxAddress, jint type, jfloatArray valuesAddress, jint count, jint offset) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
jfloat *values = (*__env)->GetPrimitiveArrayCritical(__env, valuesAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_plot(ctx, type, (const float *)values, count, offset);
(*__env)->ReleasePrimitiveArrayCritical(__env, valuesAddress, values, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1plot__JI_3FII(jlong ctxAddress, jint type, jint values__length, jfloat* values, jint count, jint offset) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAM(values__length)
nk_plot(ctx, type, (const float *)values, count, offset);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combobox__JJI_3IIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong itemsAddress, jint count, jintArray selectedAddress, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char **items = (const char **)(intptr_t)itemsAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
jint *selected = (*__env)->GetPrimitiveArrayCritical(__env, selectedAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_combobox(ctx, items, count, (int *)selected, item_height, *size);
(*__env)->ReleasePrimitiveArrayCritical(__env, selectedAddress, selected, 0);
}
#ifdef LWJGL_WINDOWS
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1combobox__JJI_3IIJ(jlong ctxAddress, jlong itemsAddress, jint count, jint selected__length, jint* selected, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char **items = (const char **)(intptr_t)itemsAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAM(selected__length)
nk_combobox(ctx, items, count, (int *)selected, item_height, *size);
}
#endif
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combobox_1string__JJ_3IIIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong items_separated_by_zerosAddress, jintArray selectedAddress, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *items_separated_by_zeros = (const char *)(intptr_t)items_separated_by_zerosAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
jint *selected = (*__env)->GetPrimitiveArrayCritical(__env, selectedAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_combobox_string(ctx, items_separated_by_zeros, (int *)selected, count, item_height, *size);
(*__env)->ReleasePrimitiveArrayCritical(__env, selectedAddress, selected, 0);
}
#ifdef LWJGL_WINDOWS
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1combobox_1string__JJ_3IIIJ(jlong ctxAddress, jlong items_separated_by_zerosAddress, jint selected__length, jint* selected, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *items_separated_by_zeros = (const char *)(intptr_t)items_separated_by_zerosAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAM(selected__length)
nk_combobox_string(ctx, items_separated_by_zeros, (int *)selected, count, item_height, *size);
}
#endif
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combobox_1separator__JJI_3IIIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong items_separated_by_separatorAddress, jint separator, jintArray selectedAddress, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *items_separated_by_separator = (const char *)(intptr_t)items_separated_by_separatorAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
jint *selected = (*__env)->GetPrimitiveArrayCritical(__env, selectedAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_combobox_separator(ctx, items_separated_by_separator, separator, (int *)selected, count, item_height, *size);
(*__env)->ReleasePrimitiveArrayCritical(__env, selectedAddress, selected, 0);
}
#ifdef LWJGL_WINDOWS
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1combobox_1separator__JJI_3IIIJ(jlong ctxAddress, jlong items_separated_by_separatorAddress, jint separator, jint selected__length, jint* selected, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
const char *items_separated_by_separator = (const char *)(intptr_t)items_separated_by_separatorAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAM(selected__length)
nk_combobox_separator(ctx, items_separated_by_separator, separator, (int *)selected, count, item_height, *size);
}
#endif
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1combobox_1callback__JJJ_3IIIJ(JNIEnv *__env, jclass clazz, jlong ctxAddress, jlong item_getterAddress, jlong userdataAddress, jintArray selectedAddress, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
nk_item_getter item_getter = (nk_item_getter)(intptr_t)item_getterAddress;
void *userdata = (void *)(intptr_t)userdataAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
jint *selected = (*__env)->GetPrimitiveArrayCritical(__env, selectedAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_combobox_callback(ctx, item_getter, userdata, (int *)selected, count, item_height, *size);
(*__env)->ReleasePrimitiveArrayCritical(__env, selectedAddress, selected, 0);
}
#ifdef LWJGL_WINDOWS
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1combobox_1callback__JJJ_3IIIJ(jlong ctxAddress, jlong item_getterAddress, jlong userdataAddress, jint selected__length, jint* selected, jint count, jint item_height, jlong sizeAddress) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
nk_item_getter item_getter = (nk_item_getter)(intptr_t)item_getterAddress;
void *userdata = (void *)(intptr_t)userdataAddress;
struct nk_vec2 *size = (struct nk_vec2 *)(intptr_t)sizeAddress;
UNUSED_PARAM(selected__length)
nk_combobox_callback(ctx, item_getter, userdata, (int *)selected, count, item_height, *size);
}
#endif
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1push_1float__J_3FF(JNIEnv *__env, jclass clazz, jlong ctxAddress, jfloatArray addressAddress, jfloat value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
jint __result;
jfloat *address = (*__env)->GetPrimitiveArrayCritical(__env, addressAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_style_push_float(ctx, (float *)address, value);
(*__env)->ReleasePrimitiveArrayCritical(__env, addressAddress, address, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1style_1push_1float__J_3FF(jlong ctxAddress, jint address__length, jfloat* address, jfloat value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAM(address__length)
return (jint)nk_style_push_float(ctx, (float *)address, value);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1style_1push_1flags__J_3II(JNIEnv *__env, jclass clazz, jlong ctxAddress, jintArray addressAddress, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
jint __result;
jint *address = (*__env)->GetPrimitiveArrayCritical(__env, addressAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_style_push_flags(ctx, (nk_flags *)address, value);
(*__env)->ReleasePrimitiveArrayCritical(__env, addressAddress, address, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1style_1push_1flags__J_3II(jlong ctxAddress, jint address__length, jint* address, jint value) {
struct nk_context *ctx = (struct nk_context *)(intptr_t)ctxAddress;
UNUSED_PARAM(address__length)
return (jint)nk_style_push_flags(ctx, (nk_flags *)address, value);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgb_1iv___3I(JNIEnv *__env, jclass clazz, jintArray rgbAddress, jlong __result) {
jint *rgb = (*__env)->GetPrimitiveArrayCritical(__env, rgbAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgb_iv((const int *)rgb);
(*__env)->ReleasePrimitiveArrayCritical(__env, rgbAddress, rgb, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1rgb_1iv___3I(jint rgb__length, jint* rgb, jlong __result) {
UNUSED_PARAM(rgb__length)
*((struct nk_color*)(intptr_t)__result) = nk_rgb_iv((const int *)rgb);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgb_1fv___3F(JNIEnv *__env, jclass clazz, jfloatArray rgbAddress, jlong __result) {
jfloat *rgb = (*__env)->GetPrimitiveArrayCritical(__env, rgbAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgb_fv((const float *)rgb);
(*__env)->ReleasePrimitiveArrayCritical(__env, rgbAddress, rgb, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1rgb_1fv___3F(jint rgb__length, jfloat* rgb, jlong __result) {
UNUSED_PARAM(rgb__length)
*((struct nk_color*)(intptr_t)__result) = nk_rgb_fv((const float *)rgb);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgba_1iv___3I(JNIEnv *__env, jclass clazz, jintArray rgbaAddress, jlong __result) {
jint *rgba = (*__env)->GetPrimitiveArrayCritical(__env, rgbaAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgba_iv((const int *)rgba);
(*__env)->ReleasePrimitiveArrayCritical(__env, rgbaAddress, rgba, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1rgba_1iv___3I(jint rgba__length, jint* rgba, jlong __result) {
UNUSED_PARAM(rgba__length)
*((struct nk_color*)(intptr_t)__result) = nk_rgba_iv((const int *)rgba);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rgba_1fv___3F(JNIEnv *__env, jclass clazz, jfloatArray rgbaAddress, jlong __result) {
jfloat *rgba = (*__env)->GetPrimitiveArrayCritical(__env, rgbaAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_rgba_fv((const float *)rgba);
(*__env)->ReleasePrimitiveArrayCritical(__env, rgbaAddress, rgba, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1rgba_1fv___3F(jint rgba__length, jfloat* rgba, jlong __result) {
UNUSED_PARAM(rgba__length)
*((struct nk_color*)(intptr_t)__result) = nk_rgba_fv((const float *)rgba);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsv_1iv___3I(JNIEnv *__env, jclass clazz, jintArray hsvAddress, jlong __result) {
jint *hsv = (*__env)->GetPrimitiveArrayCritical(__env, hsvAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsv_iv((const int *)hsv);
(*__env)->ReleasePrimitiveArrayCritical(__env, hsvAddress, hsv, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1hsv_1iv___3I(jint hsv__length, jint* hsv, jlong __result) {
UNUSED_PARAM(hsv__length)
*((struct nk_color*)(intptr_t)__result) = nk_hsv_iv((const int *)hsv);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsv_1fv___3F(JNIEnv *__env, jclass clazz, jfloatArray hsvAddress, jlong __result) {
jfloat *hsv = (*__env)->GetPrimitiveArrayCritical(__env, hsvAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsv_fv((const float *)hsv);
(*__env)->ReleasePrimitiveArrayCritical(__env, hsvAddress, hsv, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1hsv_1fv___3F(jint hsv__length, jfloat* hsv, jlong __result) {
UNUSED_PARAM(hsv__length)
*((struct nk_color*)(intptr_t)__result) = nk_hsv_fv((const float *)hsv);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsva_1iv___3I(JNIEnv *__env, jclass clazz, jintArray hsvaAddress, jlong __result) {
jint *hsva = (*__env)->GetPrimitiveArrayCritical(__env, hsvaAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsva_iv((const int *)hsva);
(*__env)->ReleasePrimitiveArrayCritical(__env, hsvaAddress, hsva, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1hsva_1iv___3I(jint hsva__length, jint* hsva, jlong __result) {
UNUSED_PARAM(hsva__length)
*((struct nk_color*)(intptr_t)__result) = nk_hsva_iv((const int *)hsva);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1hsva_1fv___3F(JNIEnv *__env, jclass clazz, jfloatArray hsvaAddress, jlong __result) {
jfloat *hsva = (*__env)->GetPrimitiveArrayCritical(__env, hsvaAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_color*)(intptr_t)__result) = nk_hsva_fv((const float *)hsva);
(*__env)->ReleasePrimitiveArrayCritical(__env, hsvaAddress, hsva, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1hsva_1fv___3F(jint hsva__length, jfloat* hsva, jlong __result) {
UNUSED_PARAM(hsva__length)
*((struct nk_color*)(intptr_t)__result) = nk_hsva_fv((const float *)hsva);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1f___3F_3F_3F_3FJ(JNIEnv *__env, jclass clazz, jfloatArray rAddress, jfloatArray gAddress, jfloatArray bAddress, jfloatArray aAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jfloat *r = (*__env)->GetPrimitiveArrayCritical(__env, rAddress, 0);
jfloat *g = (*__env)->GetPrimitiveArrayCritical(__env, gAddress, 0);
jfloat *b = (*__env)->GetPrimitiveArrayCritical(__env, bAddress, 0);
jfloat *a = (*__env)->GetPrimitiveArrayCritical(__env, aAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_f((float *)r, (float *)g, (float *)b, (float *)a, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, aAddress, a, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, bAddress, b, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, gAddress, g, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, rAddress, r, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1f___3F_3F_3F_3FJ(jint r__length, jfloat* r, jint g__length, jfloat* g, jint b__length, jfloat* b, jint a__length, jfloat* a, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(r__length)
UNUSED_PARAM(g__length)
UNUSED_PARAM(b__length)
UNUSED_PARAM(a__length)
nk_color_f((float *)r, (float *)g, (float *)b, (float *)a, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1fv___3FJ(JNIEnv *__env, jclass clazz, jfloatArray rgba_outAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jfloat *rgba_out = (*__env)->GetPrimitiveArrayCritical(__env, rgba_outAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_fv((float *)rgba_out, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, rgba_outAddress, rgba_out, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1fv___3FJ(jint rgba_out__length, jfloat* rgba_out, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(rgba_out__length)
nk_color_fv((float *)rgba_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1d___3D_3D_3D_3DJ(JNIEnv *__env, jclass clazz, jdoubleArray rAddress, jdoubleArray gAddress, jdoubleArray bAddress, jdoubleArray aAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jdouble *r = (*__env)->GetPrimitiveArrayCritical(__env, rAddress, 0);
jdouble *g = (*__env)->GetPrimitiveArrayCritical(__env, gAddress, 0);
jdouble *b = (*__env)->GetPrimitiveArrayCritical(__env, bAddress, 0);
jdouble *a = (*__env)->GetPrimitiveArrayCritical(__env, aAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_d((double *)r, (double *)g, (double *)b, (double *)a, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, aAddress, a, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, bAddress, b, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, gAddress, g, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, rAddress, r, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1d___3D_3D_3D_3DJ(jint r__length, jdouble* r, jint g__length, jdouble* g, jint b__length, jdouble* b, jint a__length, jdouble* a, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(r__length)
UNUSED_PARAM(g__length)
UNUSED_PARAM(b__length)
UNUSED_PARAM(a__length)
nk_color_d((double *)r, (double *)g, (double *)b, (double *)a, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1dv___3DJ(JNIEnv *__env, jclass clazz, jdoubleArray rgba_outAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jdouble *rgba_out = (*__env)->GetPrimitiveArrayCritical(__env, rgba_outAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_dv((double *)rgba_out, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, rgba_outAddress, rgba_out, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1dv___3DJ(jint rgba_out__length, jdouble* rgba_out, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(rgba_out__length)
nk_color_dv((double *)rgba_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1i___3I_3I_3IJ(JNIEnv *__env, jclass clazz, jintArray out_hAddress, jintArray out_sAddress, jintArray out_vAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jint *out_h = (*__env)->GetPrimitiveArrayCritical(__env, out_hAddress, 0);
jint *out_s = (*__env)->GetPrimitiveArrayCritical(__env, out_sAddress, 0);
jint *out_v = (*__env)->GetPrimitiveArrayCritical(__env, out_vAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_hsv_i((int *)out_h, (int *)out_s, (int *)out_v, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_vAddress, out_v, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_sAddress, out_s, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_hAddress, out_h, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1i___3I_3I_3IJ(jint out_h__length, jint* out_h, jint out_s__length, jint* out_s, jint out_v__length, jint* out_v, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(out_h__length)
UNUSED_PARAM(out_s__length)
UNUSED_PARAM(out_v__length)
nk_color_hsv_i((int *)out_h, (int *)out_s, (int *)out_v, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1iv___3IJ(JNIEnv *__env, jclass clazz, jintArray hsv_outAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jint *hsv_out = (*__env)->GetPrimitiveArrayCritical(__env, hsv_outAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_hsv_iv((int *)hsv_out, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, hsv_outAddress, hsv_out, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1iv___3IJ(jint hsv_out__length, jint* hsv_out, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(hsv_out__length)
nk_color_hsv_iv((int *)hsv_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1f___3F_3F_3FJ(JNIEnv *__env, jclass clazz, jfloatArray out_hAddress, jfloatArray out_sAddress, jfloatArray out_vAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jfloat *out_h = (*__env)->GetPrimitiveArrayCritical(__env, out_hAddress, 0);
jfloat *out_s = (*__env)->GetPrimitiveArrayCritical(__env, out_sAddress, 0);
jfloat *out_v = (*__env)->GetPrimitiveArrayCritical(__env, out_vAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_hsv_f((float *)out_h, (float *)out_s, (float *)out_v, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_vAddress, out_v, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_sAddress, out_s, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_hAddress, out_h, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1f___3F_3F_3FJ(jint out_h__length, jfloat* out_h, jint out_s__length, jfloat* out_s, jint out_v__length, jfloat* out_v, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(out_h__length)
UNUSED_PARAM(out_s__length)
UNUSED_PARAM(out_v__length)
nk_color_hsv_f((float *)out_h, (float *)out_s, (float *)out_v, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1fv___3FJ(JNIEnv *__env, jclass clazz, jfloatArray hsv_outAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jfloat *hsv_out = (*__env)->GetPrimitiveArrayCritical(__env, hsv_outAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_hsv_fv((float *)hsv_out, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, hsv_outAddress, hsv_out, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsv_1fv___3FJ(jint hsv_out__length, jfloat* hsv_out, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(hsv_out__length)
nk_color_hsv_fv((float *)hsv_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1i___3I_3I_3I_3IJ(JNIEnv *__env, jclass clazz, jintArray hAddress, jintArray sAddress, jintArray vAddress, jintArray aAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jint *h = (*__env)->GetPrimitiveArrayCritical(__env, hAddress, 0);
jint *s = (*__env)->GetPrimitiveArrayCritical(__env, sAddress, 0);
jint *v = (*__env)->GetPrimitiveArrayCritical(__env, vAddress, 0);
jint *a = (*__env)->GetPrimitiveArrayCritical(__env, aAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_hsva_i((int *)h, (int *)s, (int *)v, (int *)a, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, aAddress, a, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, vAddress, v, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, sAddress, s, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, hAddress, h, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1i___3I_3I_3I_3IJ(jint h__length, jint* h, jint s__length, jint* s, jint v__length, jint* v, jint a__length, jint* a, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(h__length)
UNUSED_PARAM(s__length)
UNUSED_PARAM(v__length)
UNUSED_PARAM(a__length)
nk_color_hsva_i((int *)h, (int *)s, (int *)v, (int *)a, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1iv___3IJ(JNIEnv *__env, jclass clazz, jintArray hsva_outAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jint *hsva_out = (*__env)->GetPrimitiveArrayCritical(__env, hsva_outAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_hsva_iv((int *)hsva_out, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, hsva_outAddress, hsva_out, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1iv___3IJ(jint hsva_out__length, jint* hsva_out, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(hsva_out__length)
nk_color_hsva_iv((int *)hsva_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1f___3F_3F_3F_3FJ(JNIEnv *__env, jclass clazz, jfloatArray out_hAddress, jfloatArray out_sAddress, jfloatArray out_vAddress, jfloatArray out_aAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jfloat *out_h = (*__env)->GetPrimitiveArrayCritical(__env, out_hAddress, 0);
jfloat *out_s = (*__env)->GetPrimitiveArrayCritical(__env, out_sAddress, 0);
jfloat *out_v = (*__env)->GetPrimitiveArrayCritical(__env, out_vAddress, 0);
jfloat *out_a = (*__env)->GetPrimitiveArrayCritical(__env, out_aAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_hsva_f((float *)out_h, (float *)out_s, (float *)out_v, (float *)out_a, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_aAddress, out_a, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_vAddress, out_v, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_sAddress, out_s, 0);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_hAddress, out_h, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1f___3F_3F_3F_3FJ(jint out_h__length, jfloat* out_h, jint out_s__length, jfloat* out_s, jint out_v__length, jfloat* out_v, jint out_a__length, jfloat* out_a, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(out_h__length)
UNUSED_PARAM(out_s__length)
UNUSED_PARAM(out_v__length)
UNUSED_PARAM(out_a__length)
nk_color_hsva_f((float *)out_h, (float *)out_s, (float *)out_v, (float *)out_a, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1fv___3FJ(JNIEnv *__env, jclass clazz, jfloatArray hsva_outAddress, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jfloat *hsva_out = (*__env)->GetPrimitiveArrayCritical(__env, hsva_outAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_color_hsva_fv((float *)hsva_out, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, hsva_outAddress, hsva_out, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1color_1hsva_1fv___3FJ(jint hsva_out__length, jfloat* hsva_out, jlong colorAddress) {
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(hsva_out__length)
nk_color_hsva_fv((float *)hsva_out, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1vec2v___3F(JNIEnv *__env, jclass clazz, jfloatArray xyAddress, jlong __result) {
jfloat *xy = (*__env)->GetPrimitiveArrayCritical(__env, xyAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_vec2v((const float *)xy);
(*__env)->ReleasePrimitiveArrayCritical(__env, xyAddress, xy, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1vec2v___3F(jint xy__length, jfloat* xy, jlong __result) {
UNUSED_PARAM(xy__length)
*((struct nk_vec2*)(intptr_t)__result) = nk_vec2v((const float *)xy);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1vec2iv___3I(JNIEnv *__env, jclass clazz, jintArray xyAddress, jlong __result) {
jint *xy = (*__env)->GetPrimitiveArrayCritical(__env, xyAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_vec2*)(intptr_t)__result) = nk_vec2iv((const int *)xy);
(*__env)->ReleasePrimitiveArrayCritical(__env, xyAddress, xy, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1vec2iv___3I(jint xy__length, jint* xy, jlong __result) {
UNUSED_PARAM(xy__length)
*((struct nk_vec2*)(intptr_t)__result) = nk_vec2iv((const int *)xy);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rectv___3F(JNIEnv *__env, jclass clazz, jfloatArray xywhAddress, jlong __result) {
jfloat *xywh = (*__env)->GetPrimitiveArrayCritical(__env, xywhAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_rectv((const float *)xywh);
(*__env)->ReleasePrimitiveArrayCritical(__env, xywhAddress, xywh, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1rectv___3F(jint xywh__length, jfloat* xywh, jlong __result) {
UNUSED_PARAM(xywh__length)
*((struct nk_rect*)(intptr_t)__result) = nk_rectv((const float *)xywh);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1rectiv___3I(JNIEnv *__env, jclass clazz, jintArray xywhAddress, jlong __result) {
jint *xywh = (*__env)->GetPrimitiveArrayCritical(__env, xywhAddress, 0);
UNUSED_PARAMS(__env, clazz)
*((struct nk_rect*)(intptr_t)__result) = nk_rectiv((const int *)xywh);
(*__env)->ReleasePrimitiveArrayCritical(__env, xywhAddress, xywh, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1rectiv___3I(jint xywh__length, jint* xywh, jlong __result) {
UNUSED_PARAM(xywh__length)
*((struct nk_rect*)(intptr_t)__result) = nk_rectiv((const int *)xywh);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1strmatch_1fuzzy_1string__JJ_3I(JNIEnv *__env, jclass clazz, jlong strAddress, jlong patternAddress, jintArray out_scoreAddress) {
const char *str = (const char *)(intptr_t)strAddress;
const char *pattern = (const char *)(intptr_t)patternAddress;
jint __result;
jint *out_score = (*__env)->GetPrimitiveArrayCritical(__env, out_scoreAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_strmatch_fuzzy_string(str, pattern, (int *)out_score);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_scoreAddress, out_score, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1strmatch_1fuzzy_1string__JJ_3I(jlong strAddress, jlong patternAddress, jint out_score__length, jint* out_score) {
const char *str = (const char *)(intptr_t)strAddress;
const char *pattern = (const char *)(intptr_t)patternAddress;
UNUSED_PARAM(out_score__length)
return (jint)nk_strmatch_fuzzy_string(str, pattern, (int *)out_score);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1strmatch_1fuzzy_1text__JIJ_3I(JNIEnv *__env, jclass clazz, jlong txtAddress, jint txt_len, jlong patternAddress, jintArray out_scoreAddress) {
const char *txt = (const char *)(intptr_t)txtAddress;
const char *pattern = (const char *)(intptr_t)patternAddress;
jint __result;
jint *out_score = (*__env)->GetPrimitiveArrayCritical(__env, out_scoreAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_strmatch_fuzzy_text(txt, txt_len, pattern, (int *)out_score);
(*__env)->ReleasePrimitiveArrayCritical(__env, out_scoreAddress, out_score, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1strmatch_1fuzzy_1text__JIJ_3I(jlong txtAddress, jint txt_len, jlong patternAddress, jint out_score__length, jint* out_score) {
const char *txt = (const char *)(intptr_t)txtAddress;
const char *pattern = (const char *)(intptr_t)patternAddress;
UNUSED_PARAM(out_score__length)
return (jint)nk_strmatch_fuzzy_text(txt, txt_len, pattern, (int *)out_score);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1utf_1decode__J_3II(JNIEnv *__env, jclass clazz, jlong cAddress, jintArray uAddress, jint clen) {
const char *c = (const char *)(intptr_t)cAddress;
jint __result;
jint *u = (*__env)->GetPrimitiveArrayCritical(__env, uAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_utf_decode(c, (nk_rune *)u, clen);
(*__env)->ReleasePrimitiveArrayCritical(__env, uAddress, u, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1utf_1decode__J_3II(jlong cAddress, jint u__length, jint* u, jint clen) {
const char *c = (const char *)(intptr_t)cAddress;
UNUSED_PARAM(u__length)
return (jint)nk_utf_decode(c, (nk_rune *)u, clen);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1utf_1at__JII_3IJ(JNIEnv *__env, jclass clazz, jlong bufferAddress, jint length, jint index, jintArray unicodeAddress, jlong lenAddress) {
const char *buffer = (const char *)(intptr_t)bufferAddress;
int *len = (int *)(intptr_t)lenAddress;
jlong __result;
jint *unicode = (*__env)->GetPrimitiveArrayCritical(__env, unicodeAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jlong)(intptr_t)nk_utf_at(buffer, length, index, (nk_rune *)unicode, len);
(*__env)->ReleasePrimitiveArrayCritical(__env, unicodeAddress, unicode, 0);
return __result;
}
JNIEXPORT jlong JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1utf_1at__JII_3IJ(jlong bufferAddress, jint length, jint index, jint unicode__length, jint* unicode, jlong lenAddress) {
const char *buffer = (const char *)(intptr_t)bufferAddress;
int *len = (int *)(intptr_t)lenAddress;
UNUSED_PARAM(unicode__length)
return (jlong)(intptr_t)nk_utf_at(buffer, length, index, (nk_rune *)unicode, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1append_1text_1runes__J_3II(JNIEnv *__env, jclass clazz, jlong sAddress, jintArray runesAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
jint __result;
jint *runes = (*__env)->GetPrimitiveArrayCritical(__env, runesAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_str_append_text_runes(s, (const nk_rune *)runes, len);
(*__env)->ReleasePrimitiveArrayCritical(__env, runesAddress, runes, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1str_1append_1text_1runes__J_3II(jlong sAddress, jint runes__length, jint* runes, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAM(runes__length)
return (jint)nk_str_append_text_runes(s, (const nk_rune *)runes, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1append_1str_1runes__J_3I(JNIEnv *__env, jclass clazz, jlong sAddress, jintArray runesAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
jint __result;
jint *runes = (*__env)->GetPrimitiveArrayCritical(__env, runesAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_str_append_str_runes(s, (const nk_rune *)runes);
(*__env)->ReleasePrimitiveArrayCritical(__env, runesAddress, runes, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1str_1append_1str_1runes__J_3I(jlong sAddress, jint runes__length, jint* runes) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAM(runes__length)
return (jint)nk_str_append_str_runes(s, (const nk_rune *)runes);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1text_1runes__JI_3II(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jintArray runesAddress, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
jint __result;
jint *runes = (*__env)->GetPrimitiveArrayCritical(__env, runesAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_str_insert_text_runes(s, pos, (const nk_rune *)runes, len);
(*__env)->ReleasePrimitiveArrayCritical(__env, runesAddress, runes, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1text_1runes__JI_3II(jlong sAddress, jint pos, jint runes__length, jint* runes, jint len) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAM(runes__length)
return (jint)nk_str_insert_text_runes(s, pos, (const nk_rune *)runes, len);
}
JNIEXPORT jint JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1str_1runes__JI_3I(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jintArray runesAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
jint __result;
jint *runes = (*__env)->GetPrimitiveArrayCritical(__env, runesAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jint)nk_str_insert_str_runes(s, pos, (const nk_rune *)runes);
(*__env)->ReleasePrimitiveArrayCritical(__env, runesAddress, runes, 0);
return __result;
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1str_1insert_1str_1runes__JI_3I(jlong sAddress, jint pos, jint runes__length, jint* runes) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
UNUSED_PARAM(runes__length)
return (jint)nk_str_insert_str_runes(s, pos, (const nk_rune *)runes);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1at_1rune__JI_3IJ(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jintArray unicodeAddress, jlong lenAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
int *len = (int *)(intptr_t)lenAddress;
jlong __result;
jint *unicode = (*__env)->GetPrimitiveArrayCritical(__env, unicodeAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jlong)(intptr_t)nk_str_at_rune(s, pos, (nk_rune *)unicode, len);
(*__env)->ReleasePrimitiveArrayCritical(__env, unicodeAddress, unicode, 0);
return __result;
}
JNIEXPORT jlong JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1str_1at_1rune__JI_3IJ(jlong sAddress, jint pos, jint unicode__length, jint* unicode, jlong lenAddress) {
struct nk_str *s = (struct nk_str *)(intptr_t)sAddress;
int *len = (int *)(intptr_t)lenAddress;
UNUSED_PARAM(unicode__length)
return (jlong)(intptr_t)nk_str_at_rune(s, pos, (nk_rune *)unicode, len);
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1str_1at_1const__JI_3IJ(JNIEnv *__env, jclass clazz, jlong sAddress, jint pos, jintArray unicodeAddress, jlong lenAddress) {
const struct nk_str *s = (const struct nk_str *)(intptr_t)sAddress;
int *len = (int *)(intptr_t)lenAddress;
jlong __result;
jint *unicode = (*__env)->GetPrimitiveArrayCritical(__env, unicodeAddress, 0);
UNUSED_PARAMS(__env, clazz)
__result = (jlong)(intptr_t)nk_str_at_const(s, pos, (nk_rune *)unicode, len);
(*__env)->ReleasePrimitiveArrayCritical(__env, unicodeAddress, unicode, 0);
return __result;
}
JNIEXPORT jlong JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1str_1at_1const__JI_3IJ(jlong sAddress, jint pos, jint unicode__length, jint* unicode, jlong lenAddress) {
const struct nk_str *s = (const struct nk_str *)(intptr_t)sAddress;
int *len = (int *)(intptr_t)lenAddress;
UNUSED_PARAM(unicode__length)
return (jlong)(intptr_t)nk_str_at_const(s, pos, (nk_rune *)unicode, len);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1polyline__J_3FIFJ(JNIEnv *__env, jclass clazz, jlong bAddress, jfloatArray pointsAddress, jint point_count, jfloat line_thickness, jlong colAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *col = (struct nk_color *)(intptr_t)colAddress;
jfloat *points = (*__env)->GetPrimitiveArrayCritical(__env, pointsAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_stroke_polyline(b, (float *)points, point_count, line_thickness, *col);
(*__env)->ReleasePrimitiveArrayCritical(__env, pointsAddress, points, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1polyline__J_3FIFJ(jlong bAddress, jint points__length, jfloat* points, jint point_count, jfloat line_thickness, jlong colAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *col = (struct nk_color *)(intptr_t)colAddress;
UNUSED_PARAM(points__length)
nk_stroke_polyline(b, (float *)points, point_count, line_thickness, *col);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1polygon__J_3FIFJ(JNIEnv *__env, jclass clazz, jlong bAddress, jfloatArray pointsAddress, jint point_count, jfloat line_thickness, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jfloat *points = (*__env)->GetPrimitiveArrayCritical(__env, pointsAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_stroke_polygon(b, (float *)points, point_count, line_thickness, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, pointsAddress, points, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1stroke_1polygon__J_3FIFJ(jlong bAddress, jint points__length, jfloat* points, jint point_count, jfloat line_thickness, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(points__length)
nk_stroke_polygon(b, (float *)points, point_count, line_thickness, *color);
}
JNIEXPORT void JNICALL Java_org_lwjgl_nuklear_Nuklear_nnk_1fill_1polygon__J_3FIJ(JNIEnv *__env, jclass clazz, jlong bAddress, jfloatArray pointsAddress, jint point_count, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
jfloat *points = (*__env)->GetPrimitiveArrayCritical(__env, pointsAddress, 0);
UNUSED_PARAMS(__env, clazz)
nk_fill_polygon(b, (float *)points, point_count, *color);
(*__env)->ReleasePrimitiveArrayCritical(__env, pointsAddress, points, 0);
}
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_nuklear_Nuklear_nnk_1fill_1polygon__J_3FIJ(jlong bAddress, jint points__length, jfloat* points, jint point_count, jlong colorAddress) {
struct nk_command_buffer *b = (struct nk_command_buffer *)(intptr_t)bAddress;
struct nk_color *color = (struct nk_color *)(intptr_t)colorAddress;
UNUSED_PARAM(points__length)
nk_fill_polygon(b, (float *)points, point_count, *color);
}
EXTERN_C_EXIT
<file_sep>/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4701 4702 4711 4738))
#endif
#define STB_DXT_IMPLEMENTATION
#include "stb_dxt.h"
ENABLE_WARNINGS()
EXTERN_C_ENTER
JNIEXPORT void JNICALL Java_org_lwjgl_stb_STBDXT_nstb_1compress_1dxt_1block(JNIEnv *__env, jclass clazz, jlong destAddress, jlong srcAddress, jint alpha, jint mode) {
unsigned char *dest = (unsigned char *)(intptr_t)destAddress;
const unsigned char *src = (const unsigned char *)(intptr_t)srcAddress;
UNUSED_PARAMS(__env, clazz)
stb_compress_dxt_block(dest, src, alpha, mode);
}
EXTERN_C_EXIT
| d4ba69b4d251bb7569a4cfed36889f8048918d7b | [
"Java",
"C",
"Markdown"
] | 41 | C | bsmr-java/lwjgl3-generated | ce3a36063cf79a11a729e05c30ec8fb8d60b4185 | 84978a3ceeaab02261d8d78adeae02d917fbb27f |
refs/heads/master | <file_sep>what is next?
- https://spring.io/guides/gs/spring-boot/#scratch
- https://spring.io/guides/gs/spring-boot/
- need to learn more about the endpoints
**NOTE**:
1. Springboot 1.5.x version only works for jdk 1.8.x and below.
<file_sep>package com.jarorwar.springguide.controller.rest;
import java.util.ArrayList;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UsersController {
@GetMapping("/users")
public ArrayList<String> allUsers() {
return new ArrayList<String>();
}
@GetMapping("/hello")
public String hello() {
return "=Greetings from Spring Boot!=";
}
}
| 48167c087ca122420af0dddd7a72aa225609ccea | [
"Markdown",
"Java"
] | 2 | Markdown | marvin-min/spring-boot-guide | 4c08cf1729967533b0bdac6ee143da92453f857b | 0efcc979e5154a5be21aae25b40784bbb466e1cf |
refs/heads/master | <repo_name>johney-barthwal/MERN-Online-Book-Store<file_sep>/src/components/Books.js
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css'
import '../App.css'
import {Input,InputGroup,InputGroupAddon,InputGroupText,Container } from 'reactstrap';
import BookCard from './BookCard';
class Books extends React.Component{
constructor(props){
super(props);
this.state={
searchText:''
}
}
handleSearchChange=(e)=>{
this.setState({
searchText:e.target.value
})
}
searchingFor=(text) =>{
return function(x) {
return x.title.toLowerCase().includes(text.toLowerCase()) || !text;
};
}
render(){
let booksData;
let term=this.state.searchText;
booksData = this.props.books
.filter(this.searchingFor(term))
.map(book => {
return (
<BookCard book={book} cart={this.props.cart} key={book.bookID} addToCart={this.props.addToCart}/>
);
});
let view;
if (booksData.length <= 0 && !term) {
view =<h1>Loading. . .</h1>;
} else if (booksData.length <= 0 && term) {
view = <h1>No Results Found</h1>;
} else { view = booksData }
return (
<div>
<Container style={{marginTop:'80px'}}>
<InputGroup>
<Input placeholder="Type here to search..." onChange={this.handleSearchChange}/>
</InputGroup>
<br />
<div>{view}</div>
</Container>
</div>
);
}
}
export default Books;
<file_sep>/backend/models/book.model.js
const mongoose = require('mongoose');
const BookSchema = new mongoose.Schema({
bookID:{
type:Number,
required:true,
unique:true
},
title:{
type:String,
required:true
},
authors:{
type:String,
required:true
},
average_rating:{
type:Number,
required:true
},
isbn:{
type:String,
required:true
},
language_code:{
type:String,
required:true
},
ratings_count:{
type:Number,
required:true
},
price:{
type:Number,
required:true
}
},
{
timestamps:true
});
module.exports = Book = mongoose.model('book',BookSchema);
<file_sep>/src/components/Cart.js
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css'
import { Row,Col,Table,Container,Button} from 'reactstrap';
class Cart extends React.Component{
render(){
return (
<Container style={{marginTop:'80px'}}>
<Row>
<Col sm="10"><h1><strong>Your Cart</strong></h1></Col>
<Col sm="2"><Button color="warning" style={{border:'2px solid black'}}>PROCEED TO CHECKOUT</Button><br/><br/></Col>
</Row>
<Table border='1'>
<thead>
<tr>
<th>Title</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
{this.props.cart.map((item)=>{
return(
<tr>
<td>{item.title}</td>
<td>
<Row >
<Col sm="2">
<Button className='sm-btn'>+</Button>
</Col>
<Col sm="7" style={{textAlign:'center'}}>{item.qty} added in cart</Col>
<Col sm="2"><Button className='sm-btn'>-</Button></Col>
</Row>
</td>
<td> {item.price}</td>
<td>₹ {item.qty*item.price}</td>
</tr>
)})}
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td><strong>Total cart amount</strong></td>
<td><strong>₹ {this.props.totalAmount}</strong></td>
</tr>
</tfoot>
</Table>
</Container>
);
}
}
export default Cart;
<file_sep>/README.md
# MERN-Online-Book-Store
A Full stack mern web application for ordering books online
<file_sep>/backend/server.js
const express = require("express");
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
app.use(cors())
app.use(express.json());
uri="mongodb://localhost:27017/books";
mongoose.connect(uri,{useNewUrlParser:true,useCreateIndex:true});
const connection = mongoose.connection;
connection.once('open',()=>{console.log("MongoDB successfully connected!!!")});
const booksRouter = require('./routes/books.routes');
app.use('/api/books',booksRouter);
const PORT =process.env.PORT || 5000;
app.listen(PORT,()=>{console.log(`Server is running ar port ${PORT}`)});<file_sep>/src/components/BookCard.js
import React from 'react';
import { Row,Col,Card, Button, CardTitle, CardText } from 'reactstrap';
import StarRatingComponent from 'react-star-rating-component';
class BookCard extends React.Component{
constructor(props) {
super(props);
this.state = {
selectedBook: {},
isAdded: false,
currQty:1
};
}
incrementQty=(BookID,title, price)=>{
this.setState({
currQty:this.state.currQty+1
},function(){
this.addToCart(BookID,title, price);
})
}
addToCart=(BookID,title, price) =>{
this.setState(
{
selectedBook: {
BookID: BookID,
title: title,
price: price,
qty:this.state.currQty
},
isAdded: true
},
function() {
this.props.addToCart(this.state.selectedBook);
}
);
}
render(){
const {bookID,title,authors,price,average_rating} = this.props.book;
const d1 = this.state.isAdded ? null : "none";
const d2 = this.state.isAdded ? "none": null;
const cardColor=["secondary","success","danger","primary","danger","warning","info","light","dark"];
const rand = Math.round(0 + Math.random() * (4 - 0));
return (
<Card body outline color={cardColor[rand]} className='card-style'>
<CardTitle> <strong>{title}</strong></CardTitle>
<CardText>{authors}</CardText>
<strong> ₹ {price}.00</strong>
<StarRatingComponent
name="star"
editing={false}
starCount={5}
value={average_rating}
/>
<Button id={bookID} onClick={this.addToCart.bind(
this,
bookID,
title,
price
)}
style={{display:d2}}>Add to cart
</Button>
<Row style={{display:d1}}>
<Col sm="2">
<Button className='sm-btn' onClick={this.incrementQty.bind(
this,
bookID,
title,
price
)} >+
</Button>
</Col>
<Col sm="7" style={{textAlign:'center'}}> {this.state.currQty} added in cart</Col>
<Col sm="2"><Button className='sm-btn'>-</Button></Col>
</Row>
</Card>
);
}
}
export default BookCard;
<file_sep>/src/App.js
import React from 'react';
import {BrowserRouter as Router ,Route} from 'react-router-dom';
import axios from 'axios'
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css'
import NavbarApp from './components/Navabar';
import Books from './components/Books'
import Cart from './components/Cart'
class App extends React.Component{
constructor(props){
super(props);
this.state={
books:[],
cart:[],
totalItems: 0,
totalAmount:0,
}
}
componentDidMount(){
axios.get('http://localhost:5000/api/books')
.then(res=>this.setState({books:res.data}))
.catch(err=>console.log("Error :"+err));
}
addToCart=(selectedBook) => {
let cartItem = this.state.cart;
let BookID = selectedBook.BookID;
if (this.checkProduct(BookID)) {
let index = cartItem.findIndex(x => x.BookID == BookID);
cartItem[index].qty =selectedBook.qty
this.setState({
cart: cartItem
});
} else {
cartItem.push(selectedBook);
}
this.setState({
cart: cartItem
});
this.sumTotalItems();
this.sumTotalAmount();
}
checkProduct=(BookID) =>{
let cart = this.state.cart;
return cart.some(function(item) {
return item.BookID === BookID;
});
}
sumTotalItems=() =>{
this.setState({
totalItems: this.state.cart.length
});
}
sumTotalAmount=() =>{
let total = 0;
for (var i = 0; i < this.state.cart.length; i++) {
total += this.state.cart[i].price * parseInt(this.state.cart[i].qty);
}
this.setState({
totalAmount: total
});
}
render(){
return (
<Router>
<div className="App">
<NavbarApp totalItems={this.state.totalItems}/>
<Route
path='/' exact
render={(props) => <Books {...props}
books={this.state.books}
cart={this.state.cart}
addToCart={this.addToCart}
removeFromCart={this.removeFromCart} />}
/>
<Route
path='/cart'
render={(props)=><Cart {...props}
cart={this.state.cart}
totalAmount={this.state.totalAmount}
/>}
/>
</div>
</Router>
);
}
}
export default App;
| 9799fb8708b683e5b8678828559b7b31f1f96bb7 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | johney-barthwal/MERN-Online-Book-Store | 3c926fc8622d29e9e40d6fb9956fcf0fc0bb9e7f | dff35c2912486ae2282d10b18e7ea697712ae188 |
refs/heads/master | <file_sep>import "./fixed-data-table.css";
var React = require('react');
var ReactDOM = require('react-dom');
var Axios = require('axios');
const {Table, Column, Cell} = require('fixed-data-table');
var SortTypes = {
ASC: 'ASC',
DESC: 'DESC',
};
function reverseSortDirection(sortDir) {
return sortDir === SortTypes.DESC ? SortTypes.ASC : SortTypes.DESC;
}
class SortHeaderCell extends React.Component {
constructor(props) {
super(props);
this._onSortChange = this._onSortChange.bind(this);
}
render() {
var {sortDir, children, ...props} = this.props;
return (
<Cell {...props}>
<a onClick={this._onSortChange}>
{children} {sortDir ? (sortDir === SortTypes.DESC ? '↓' : '↑') : ''}
</a>
</Cell>
);
}
_onSortChange(e) {
e.preventDefault();
if (this.props.onSortChange) {
this.props.onSortChange(
this.props.columnKey,
this.props.sortDir ?
reverseSortDirection(this.props.sortDir) :
SortTypes.DESC,
this.props.columnName
);
}
}
}
class DataListWrapper {
constructor(indexMap, data) {
this._indexMap = indexMap;
this._data = data;
}
getSize() {
return this._indexMap.length;
}
getObjectAt(index) {
return this._data[this._indexMap[index]];
}
}
const LinkCell = ({rowIndex, data, columnKey, ...props}) => (
<Cell {...props}>
<a href={data.getObjectAt(rowIndex)[columnKey]}>{data.getObjectAt(rowIndex)[columnKey]}</a>
</Cell>
);
const TextCell = ({rowIndex, data, columnKey, ...props}) => (
<Cell {...props}>
{data.getObjectAt(rowIndex)[columnKey]}
</Cell>
);
class ReportTable extends React.Component {
constructor(props) {
super(props);
this.report = {};
this._dataList = [];
this._defaultSortIndexes = [];
this.state = {
filterby: 'companyName',
filterbyColumnName: 'Company Name',
colSortDirs: {},
mock: {},
};
this._onSortChange = this._onSortChange.bind(this);
this._onFilterChange = this._onFilterChange.bind(this);
this._onDropDownChange = this._onDropDownChange.bind(this);
}
_onSortChange(columnKey, sortDir, columnName) {
var sortIndexes = this._defaultSortIndexes.slice();
sortIndexes.sort((indexA, indexB) => {
var valueA = this._dataList[indexA][columnKey];
var valueB = this._dataList[indexB][columnKey];
var sortVal = 0;
if (valueA > valueB) {
sortVal = 1;
}
if (valueA < valueB) {
sortVal = -1;
}
if (sortVal !== 0 && sortDir === SortTypes.ASC) {
sortVal = sortVal * -1;
}
return sortVal;
});
this.setState({
sortedDataList: new DataListWrapper(sortIndexes, this._dataList),
colSortDirs: {
[columnKey]: sortDir,
},
filterby: columnKey,
filterbyColumnName: columnName,
});
}
_onFilterChange(e){
if (!e.target.value) {
this.setState({
sortedDataList: new DataListWrapper(this._defaultSortIndexes.slice(),this._dataList),
});
}
var filterBy = e.target.value.toLowerCase();
var size = this._dataList.length;
var filteredIndexes = [];
for (var index = 0; index < size; index++) {
var searchKey = this._dataList[index][this.state.filterby];
if (searchKey.toLowerCase().indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
if(filteredIndexes.length !== 0){
this.setState({
sortedDataList: new DataListWrapper(filteredIndexes, this._dataList),
});
}
else{
this.setState({
sortedDataList: new DataListWrapper(this._defaultSortIndexes.slice(), this._dataList),
});
}
}
_onDropDownChange(e){
var selectedDate = e.target.value;
this._dataList = this.report.filter(function(obj){return obj.date === selectedDate})[0].list;
this.setState({
sortedDataList: new DataListWrapper(this._defaultSortIndexes.slice(),this._dataList),
});
}
componentWillMount(){
}
componentDidMount(){
console.log("component did mount");
Axios({
method: 'post',
url: 'https://finie.herokuapp.com/api/report',
data: {
customerId: '155295665',
link: 'www.isbank.com.tr',
},
auth: {
username: 'pocUser',
password: '<PASSWORD>'
},
}).then(res => {
var mock = res.data;
var dates = res.data.reportDates;
var reports = res.data.reports;
var size = reports.filter(function(obj){return obj.date === dates[0]})[0].list.length;
var indexes = [];
for (var index = 0; index < size; index++) {
indexes.push(index);
}
this._dataList = reports.filter(function(obj){return obj.date === dates[0]})[0].list;
this._defaultSortIndexes = indexes;
this.report= reports;
this.setState({
sortedDataList: new DataListWrapper(this._defaultSortIndexes.slice(),this._dataList),
reportDates : dates,
});
}).catch(console.log('terrible'));
}
render() {
var {sortedDataList, colSortDirs, filterbyColumnName, reportDates} = this.state;
if(sortedDataList == undefined){
return(<div>The response it not here yet!</div>);
}
else{
return (
<div>
<DropDown id="myDropdown" options={reportDates} handleChange={this._onDropDownChange}/>
<input onChange={this._onFilterChange} placeholder={"Filter by " + filterbyColumnName}/>
<br />
<Table
rowHeight={50}
headerHeight={50}
rowsCount={sortedDataList.getSize()}
width={1500}
height={500}
{...this.props}>
<Column columnKey="companyName"
header={<SortHeaderCell onSortChange={this._onSortChange} sortDir={colSortDirs.companyName} columnName="Company Name">Company Name</SortHeaderCell>}
cell={<TextCell data={sortedDataList} />}
fixed={true}
width={200}
/>
<Column columnKey="funding"
header={<SortHeaderCell onSortChange={this._onSortChange} sortDir={colSortDirs.funding} columnName="Funding Amount">Funding Amount</SortHeaderCell>}
cell={<TextCell data={sortedDataList} />}
fixed={true}
width={200}
/>
<Column columnKey="stage"
header={<SortHeaderCell onSortChange={this._onSortChange} sortDir={colSortDirs.stage} columnName="Stage">Stage</SortHeaderCell>}
cell={<TextCell data={sortedDataList} />}
width={200}
/>
<Column columnKey="lastFundingDate"
header={<SortHeaderCell onSortChange={this._onSortChange} sortDir={colSortDirs.lastFundingDate} columnName="Funding Date">Funding Date</SortHeaderCell>}
cell={<TextCell data={sortedDataList} />}
width={200}
/>
<Column columnKey="location"
header={<SortHeaderCell onSortChange={this._onSortChange} sortDir={colSortDirs.location} columnName="Location">Location</SortHeaderCell>}
cell={<TextCell data={sortedDataList} />}
width={200}
/>
<Column columnKey="category"
header={<SortHeaderCell onSortChange={this._onSortChange} sortDir={colSortDirs.category} columnName="Category">Category</SortHeaderCell>}
cell={<TextCell data={sortedDataList} />}
width={200}
/>
<Column columnKey="website"
header={<Cell>Web Site</Cell>}
cell={<LinkCell data={sortedDataList}/>}
width={300}
/>
</Table>
</div>
);
}
}
}
class DropDown extends React.Component {
render() {
var self = this;
var options = self.props.options.map(function(option) {
return (
<option key={option} value={option}>
{option}
</option>
)
});
return (
<select id={this.props.id}
value={this.props.selected}
onChange={this.props.handleChange}>
{options}
</select>)
}
}
const element = (<div><ReportTable/></div>);
ReactDOM.render(
element,
document.getElementById('root')
);
| a4b189cf170e29d72b6d17cf0c9fd58618316b59 | [
"JavaScript"
] | 1 | JavaScript | baranatmanoglu/MMReport | 59d6e1c0f17fabdd60583d8175f689b8db1f979d | 11d9fa2b86ba1492eaafe2cc6812dc77cf373230 |
refs/heads/master | <repo_name>brunoHoarau/RacketAndBall<file_sep>/README.md
# RacketAndBall
Racket with a ball which bounces on wall and change color, in javascript
<file_sep>/script.js
var dx = 2;
var dy = -2;
var time = setInterval(field,10);
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = "400";
var width = canvas.width ;
canvas.height = "600";
var height = canvas.height ;
var x = 150;
var y = 150;
var ballRadius = 10;
var racketX = width/2;
var racketH = 10;
var racketW = 75;
var racketY = canvas.height-30;
ctx.fillStyle = "#008000";
//écouteur d'évenement
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
//la raquette
function racket() {
ctx.beginPath();
ctx.rect(racketX, racketY, racketW, racketH);
ctx.fill();
ctx.closePath()
}
//la balle
function ball(){
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fill();
ctx.closePath();
};
//Le terrain
function field(){
ctx.clearRect(0,0, width,height);
ball();
racket();
// si x > largeur - rayonball (mur droit) ou si x < à mur gauche
if (x + dx > width - ballRadius || x + dx < 0 + ballRadius){
dx = -dx;
ctx.fillStyle = "#FF0000";
}
// si y > hauteur - rayonball (mur bas) ou si y < à mur haut
if ((y+dy) + ballRadius > height - ballRadius || y +dy<0 + ballRadius){
dy = -dy;
ctx.fillStyle = "#0000FF";
} else if (y + dy > racketY ){ // si supperieur à l'axe y de la racket
if(x + ballRadius > racketX && (x +dy )+ ballRadius < racketX + racketW){ // si x > l'axe x et l'axe x + racket largeur,
dy = -dy;
ctx.fillStyle = "#0000FF";
} else {
alert("Game Over");
location.reload(true);
clearInterval(time);
}
}
x += dx;
y += dy;
} time;
// Quand la touche est pressé
function keyDownHandler(e) {
if(e.key == "Right" || e.key == "ArrowRight") {
right = true;
racketX += 10 ;
}
else if(e.key == "Left" || e.key == "ArrowLeft") {
left = true;
racketX -= 10;
}
}
// Quand la touche cesse d'être préssée
//pour empecher que la raquette continue de bouger toute seule
function keyUpHandler(e) {
if(e.key == "Right" || e.key == "ArrowRight") {
right = false;
}
else if(e.key == "Left" || e.key == "ArrowLeft") {
left = false;
}
}
| 7771beababc6ac3b0c604dc597ef86eee54fb518 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | brunoHoarau/RacketAndBall | 80df05d9bb2d4f204ea5652e5b553320117966ea | 44672a02f0b9819cb3d1640647b848c467113839 |
refs/heads/master | <repo_name>krathman257/DialogEngine<file_sep>/Reader.py
# reads in a file, parses out dialog
# kblack 4/3/2020
import re
from DialogMachine import DialogMachine
class Reader:
def __init__(self):
self.wd = "./" # working directory where file is located
self.cons = {} # dictionary for concepts
self.dm = DialogMachine()
return
def read_in(self, filename):
# function to read in input file
path = self.wd + filename # path to FILE
file = open(path, "r")
return file
def parse_options(self, opts):
opt_list = []
opts = opts.replace("[", "", 1)
opts = opts.replace("]", "", 1)
opts = opts.replace("(", "", 1)
opts = opts.replace(")", "", 1)
opt_prelist = opts.split()
tmp = ""
flag = False
for chunk in opt_prelist:
if chunk.startswith("\""): # starts with quote = multiword
flag = True # raise flag if its a multiword
tmp = chunk.strip("\"") # strip quote
continue
if flag: # still a multiword
tmp = tmp + " " + chunk.strip("\"") # add the sentence chunk
if chunk.endswith("\""):
# reached end of multiword
flag = False
chunk = tmp # chunk collects the assembled word
tmp = "" # tmp is reset
else:
continue
opt_list.append(chunk)
return opt_list
def tknize(self, line):
# from krathman:
# first character = u (rule) -> [[list of string inputs], [list of string outputs], level]
# first character = & (proposal) -> "thing to say"
# first character = ~ (concept declaration) -> [concept name, [list of string definitions]]
dia = re.split(":", line, 1) # splits line at first colon
dia = tuple(dia)
corp = []
cmd = dia[0]
cmd = cmd.strip()
flag = False
if cmd.startswith("u"): # rules require user input
rule = re.split(":", dia[1], 1)
# rule0 = tirgger/input
# rule1 = resp/output
# ensure that lists are parsed as lists
if rule[0].strip().startswith("(["):
trig = self.parse_options(rule[0])
else:
trig = rule[0].strip()
trig = trig.replace(")", "")
trig = trig.replace("(", "")
if trig.startswith("~"): # check if ref to concept
terms = list(self.cons.keys())
if trig.strip("~") in terms:
trig = self.cons[trig.strip("~")]
if rule[1].strip().startswith("["):
resp = self.parse_options(rule[1])
else:
resp = rule[1]
if resp.startswith(" "):
resp = resp.lstrip()
if resp.startswith("~"): # check if ref to concept
terms = list(self.cons.keys())
if resp.strip("~") in terms:
resp = self.cons[resp.strip("~")]
uid = cmd.strip("u")
if type(trig) == type(''):
trig = [trig]
if type(resp) == type(''):
resp = [resp]
if uid.isnumeric():
#return (trig, resp, int(uid))
self.dm.addRule(trig, resp, int(uid))
else:
#return (trig, resp, 0)
self.dm.addRule(trig, resp, 0)
elif cmd.startswith("&"): # proposal\
if flag:
print("No more than one proposal!")
return (None)
#print("Proposal found")
prop = self.parse_options(dia[1])
propStr = ""
for s in range(0, len(prop)):
propStr += prop[s]+" "
#print(propStr)
if not flag:
self.dm.setProposal([propStr])
flag = True
elif cmd.startswith("~"): # concept
concept = cmd.strip("~") # get the concept name
defs = self.parse_options(dia[1])
self.cons[concept] = defs
return (concept, defs)
def parse_lines(self, fname):
if fname is "":
fname = "test.txt"
# breaks down file to lines
try:
file = self.read_in(fname)
pass
except:
print("file not found.")
return
in_lines = file.readlines() # gets all lines in file as a list
# now that we have the lines, we need to clean them
# first, remove all commented lines
lines = []
for line in in_lines:
if re.search("\#.*",
line) is None and line is not "\n" and line is not "": # checks if it matches regex, if not, then add it to list of lines
tmp = line.strip("\n")
lines.append(tmp)
# so now we can assume that lines list only has relevant (non-commented, non-blank) lines in it
log = []
for line in lines:
dia = self.tknize(line)
# todo: something with the dialog
#log.append(dia)
#for i in range(0, len(log)):
# print(log[i])
#print('***')
#return log
read = Reader()
read.parse_lines("script.txt")
#print(read.cons)
read.dm.run()<file_sep>/DialogTest.py
from DialogMachine import DialogMachine
dm = DialogMachine()
dm.setProposal(["I am a FUCKING robot", "Talk to me if you want to live!"])
dm.addRule(["How are you?", "How are you doing?"], ["Pretty good", "Just fine"], 0)
dm.addRule(["Happy?", "Feeling good?"], ["Yep", "Abso-didily-oodily"], 1)
dm.addRule(["Fuck off", "Go fuck yourself"], ["You too!", "That was mean..."], 0)
dm.addRule(["I'm sorry", "That was rude of me"], ["It's OK", "Just be nicer in the future..."], 1)
dm.run()
<file_sep>/Concept.py
import random
class Concept:
def __init__(self, n, w=[]):
self.name = n
self.words = w
#Add word to concept
def addWord(self, w):
if self.words.count(w) == 0:
self.words.append(w)
def getConceptList(self):
return self.words
def getComplexConceptList(self, start, end):
tempArr = []
for i in range(0, len(self.words)):
tempStr = start + self.words[i] + end
tempArr.append(tempStr)
return tempArr
<file_sep>/DialogMachine.py
#krathman
from Proposal import Proposal
from RuleNode import RuleNode
class DialogMachine:
def __init__(self):
self.proposal = False
self.concepts = []
self.rules = [RuleNode("", "", -1)]
pass
#Adds rule, sets parent-child relationship
#given level and previous rules
def addRule(self, i, o, l=0):
rn = RuleNode(i, o, l)
if l > -1:
for p in range(len(self.rules)-1, -1, -1):
if self.rules[p].level == l - 1:
rn.setParent(self.rules[p])
self.rules[p].addSubRule(rn)
break
self.rules.append(rn)
#When building machine, call before any
#addRules if proposal is present
def setProposal(self, p):
self.proposal = True
self.rules[0] = Proposal(p)
#Returns concept with name n
def getConcept(self, n):
for i in range(0, len(self.concepts)):
if self.concepts[i].name == n:
return self.concepts[i]
print('ERR: Concept Not Found')
return None
def printRules(self):
for i in range(0, len(self.rules)):
print(self.rules[i].toString())
#Runs dialog machine
def run(self):
stop = False
currentRule = self.rules[0]
if self.proposal == True:
currentRule.speak()
while not stop:
humanIn = input()
nextRule = currentRule.getNext(humanIn)
if not nextRule == "REPEAT":
currentRule = nextRule
print("\nENDING SCRIPT...")
<file_sep>/RuleNode.py
import random
class RuleNode:
def __init__(self, si, so, l):
self.level = l
self.speechIn = si
self.speechOut = so
self.parentRule = None
self.subRules = []
def addSubRule(self, sr):
self.subRules.append(sr)
def setParent(self, p):
self.parentRule = p
def speak(self):
chosen = self.speechOut[random.randint(0,len(self.speechOut)-1)]
print(chosen)
#Bool, checks if input is a string in speechIn
def checkInput(self, input):
for i in range(0, len(self.speechIn)):
if self.speechIn[i].lower() in input.lower():
return True
return False
#Tries to get next rule given input
def getNext(self, humanIn):
for r in range(0, len(self.subRules)):
if self.subRules[r].checkInput(humanIn):
self.subRules[r].speak()
return self.subRules[r]
if self.parentRule is None:
print("I didn't catch that")
return "REPEAT"
else:
return self.parentRule.getNext(humanIn)
def toString(self):
return "RuleNode: "+str(self.level)+") "+str(self.speechIn)+", "+str(self.speechOut)
def printSubRules(self):
print("SUBRULES OF " + self.toString())
for i in range(0, len(self.subRules)):
print("SUBRULE "+str(i)+") "+self.subRules[i].toString())
def printParents(self):
if self.parentRule is None:
print("PARENT OF " + self.toString() + " IS NONE")
else:
print("PARENT OF " + self.toString() + " IS " + self.parentRule.toString())
| 747fa5ee6acb853f53ea581c7872b5b9b026efdd | [
"Python"
] | 5 | Python | krathman257/DialogEngine | 08e3cb19a40c3661d62825c9311aaa42a3fecffb | 4ab3f90367cde80bb9d10c267307f6419e45dde5 |
refs/heads/master | <repo_name>EPAMKarayeva/Logs<file_sep>/InsertionSort/LogAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InsertionSort
{
class LogAttribute: Attribute
{
}
}
<file_sep>/InsertionSort/ArraySorting.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
namespace InsertionSort
{
public class ArraySorting
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public string TestField;
private int TstField;
public void FillArray(int[] array)
{
Random rand = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(0, 10);
}
}
public void ArrayInsertionSorting(int[] array)
{
try
{
int temp;
var beforeSort = string.Join(" ", array);
for (int i = 1; i < array.Length; i++)
{
for (int j = i; j > 0 && array[j - 1] > array[j]; j--)
{
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
var afterSort = string.Join(" ", array);
var totalBeforeSort = string.Concat("Result before sort:" + " " + beforeSort);
var totalAfterSort = string.Concat("Result after sort:" + " " + afterSort);
var str = string.Concat(totalBeforeSort, totalAfterSort);
logger.Info(str);
}
catch (Exception ex)
{
logger.Warn(ex.Message);
}
}
private void Test()
{
}
}
}
<file_sep>/InsertionSort/WorkWithReflection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace InsertionSort
{
class WorkWithReflection
{
public void ShowAllMethods(Object obj)
{
var type = obj.GetType();
var className = obj.GetType().Name;
Console.WriteLine("Class name:"+className);
Console.WriteLine("Methods:");
MethodInfo[] methodInfoArray = type.GetMethods(BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);
for (int i = 0; i < methodInfoArray.Length; i++)
{
Console.WriteLine(GetSignature(methodInfoArray[i]));
}
}
public string GetSignature(MethodInfo mi)
{
StringBuilder sb = new StringBuilder();
if (mi.IsPrivate)
sb.Append("private ");
if (mi.IsPublic)
sb.Append("public ");
if (mi.IsStatic)
sb.Append("static ");
sb.Append(mi.ReturnType.Name + " ");
sb.Append(mi.Name + "(");
var param = mi.GetParameters().Select(p => String.Format(
"{0} {1}", p.ParameterType.Name, p.Name)).ToArray();
sb.Append(String.Join(", ", param));
sb.Append(")");
return sb.ToString();
}
public void ShowAllFields(Object obj)
{
var type = obj.GetType();
Console.WriteLine("Fields:");
FieldInfo[] fieldInfoArray = type.GetFields(BindingFlags.NonPublic | BindingFlags.Static
| BindingFlags.Instance | BindingFlags.Public);
for (int i = 0; i < fieldInfoArray.Length; i++)
{
Console.WriteLine(GetFieldBody(fieldInfoArray[i]));
}
}
public string GetFieldBody(FieldInfo fieldInfo)
{
StringBuilder sb = new StringBuilder();
if (fieldInfo.IsPrivate)
sb.Append("private ");
if (fieldInfo.IsPublic)
sb.Append("public ");
if (fieldInfo.IsStatic)
sb.Append("static ");
sb.Append(fieldInfo.FieldType.Name + " ");
sb.Append(fieldInfo.Name);
return sb.ToString();
}
}
}
<file_sep>/InsertionSort/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InsertionSort
{
class Program
{
static void Main(string[] args)
{
int [] array = new int[10];
ArraySorting arraySorting = new ArraySorting();
arraySorting.FillArray(array);
Console.WriteLine("Before sort:");
foreach (int item in array)
{
Console.Write(item + " ");
}
arraySorting.ArrayInsertionSorting(array);
Console.WriteLine("\nAfter sort:");
foreach (int item in array)
{
Console.Write(item + " ");
}
Console.WriteLine("\n");
WorkWithReflection refl = new WorkWithReflection();
refl.ShowAllMethods(arraySorting);
refl.ShowAllFields(arraySorting);
Console.ReadKey();
}
}
}
| 4ab63585aebc59f8f9b756aa870314821b6d6209 | [
"C#"
] | 4 | C# | EPAMKarayeva/Logs | a8aee28705d0ceb525a92376a10742e5a3109088 | c4a404ad4917dfcc5a7449799425988146eddc7a |
refs/heads/master | <file_sep>#include <stdio.h>
#include <string.h>
#include "qsort.h"
#include "merge_sort.h"
int main(int argc, char ** argv){
printf("Please input a string to sort:\n");
//printf("testing partition of given array:\n");
char test[100] = {0};
char tmp[100] = {0};
scanf("%s", test);
int len = strlen(test);
strcpy(tmp, test);
printf("%s\n", tmp);
quicksort(tmp, 0, len - 1);
printf("[quick sort] The sorted string is :%s \n", tmp);
strcpy(tmp, test);
printf("%s\n", tmp);
merge_sort(tmp, len);
printf("[merge sort] The sorted string is :%s \n", tmp);
return 0;
}
<file_sep>#ifndef QSORT_H_
#define QSORT_H_
int partition(char input[], int l, int r);
void quicksort(char input[], int l, int r);
#endif
<file_sep>/*
* slist_test.c
*
* Created on: 2012-4-28
* Author: hujin
*/
#include <stdio.h>
#include <string.h>
#include "slist.h"
void slist_print(pointer data) {
printf("%s\n", *(string *)data);
}
int main(int argc, char **argv) {
slist_t * slist = slist_new(string, slist_string_dtor_func);
slist_appends(slist, "hujin");
slist_appends(slist, "bixue");
slist_appends(slist, "11111");
slist_appends(slist, "22222");
slist_appends(slist, "33333");
slist_appends(slist, "44444");
slist_apply(slist, (slist_apply_func_t)slist_print);
printf("\n");
slist_reverse(slist);
slist_apply(slist, (slist_apply_func_t)slist_print);
slist_destroy(slist);
return 0;
}
<file_sep>/*
* bitmap.c
*
* Created on: 2012-4-26
* Author: hujin
*/
#include <stdio.h>
#include <malloc.h>
#include "bitmap.h"
/**
* 创建一个 bitmap 对象
* @param int size 创建 bitmap 的大小
* @param int start bitmap 存储起始元素
* @return bitmap_t
*/
bitmap_t * bitmap_new(int size, int start) {
bitmap_t * ret = malloc(sizeof(bitmap_t));
if(!ret) return NULL;
ret->base = start;
ret->size = (size >> 3) + 1;
ret->bitmap = malloc(ret->size * sizeof(char));
if(!ret->bitmap) {
free(ret);
return NULL;
}
return ret;
}
int bitmap_set(bitmap_t * map, int index) {
int quo = (index - map->base) / 8;
if(quo > map->size) {
return 0;
}
int remainer = (index - map->base) % 8;
map->bitmap[quo] |= 1 << remainer;
return 1;
}
int bitmpa_get(bitmap_t * map, int index) {
int quo = index / 8;
if(quo > map->size) return 0;
unsigned char ret = map->bitmap[quo] & (1 << (index % 8));
return ret > 0 ? 1 : 0;
}
int bitmap_data(bitmap_t * map, int index) {
return map->base + index;
}
void bitmap_free(bitmap_t * map) {
free(map->bitmap);
free(map);
}
<file_sep>/*
* list.h
*
* Created on: 2012-5-8
* Author: hujin
*/
#ifndef LIST_H_
#define LIST_H_
#include "types.h"
typedef struct _list_node {
struct _list_node * prev;
struct _list_node * next;
char data[0];
}list_node_t;
typedef void (*list_dtor_func_t)(pointer data);
typedef void (*list_apply_func_t)(pointer node);
typedef int (*list_compare_func_t)(pointer, pointer);
typedef struct _list{
list_node_t * head;
list_node_t * tail;
int length;
int size;
list_dtor_func_t dtor;
list_node_t * curr;
}list_t;
list_t * _list_new(int size, list_dtor_func_t dtor);
#define list_new(type, dtor) _list_new(sizeof(type), dtor)
bool list_append(list_t * list, pointer data);
bool list_prepend(list_t * list, pointer data);
void list_clear(list_t * list);
void list_destroy(list_t * list);
#endif /* LIST_H_ */
<file_sep>/*
* bigint.h
*
* Created on: 2012-4-12
* Author: hujin
*/
#ifndef BIGINT_H_
#define BIGINT_H_
#include <sys/types.h>
#define BIGINT_MAX_LEN 100
typedef struct{
int len;
int8_t data[BIGINT_MAX_LEN];
}bigint_t;
int8_t ctoi8(char c);
void bigint_assign(bigint_t * p_int, char * in);
void bigint_multiplication(bigint_t a, bigint_t b, bigint_t * ret);
void bigint_to_string(bigint_t integer, char output[]);
void bigint_print(bigint_t integer, char * text) ;
#endif /* BIGINT_H_ */
<file_sep>/*
* slist.c
*
* Created on: 2012-4-28
* Author: hujin
*/
#include <stdio.h>
#include <assert.h>
#include <malloc.h>
#include <string.h>
#include "types.h"
#include "slist.h"
slist_t * _slist_new(int size, slist_dtor_func_t dtor) {
slist_t * ret = malloc(sizeof(slist_t));
assert(ret != NULL);
if(ret == NULL) return NULL;
ret->curr = NULL;
ret->dtor = dtor;
ret->head = NULL;
ret->tail = NULL;
ret->length = 0;
ret->size = size;
return ret;
}
bool slist_append(slist_t * list, pointer data) {
slist_node_t * tmp = malloc(sizeof(slist_node_t) + list->size);
if(!tmp) return false;
tmp->next = NULL;
memcpy(tmp->data, data, list->size);
if(list->tail) {
list->tail->next = tmp;
}else{
list->head = tmp;
list->tail = tmp;
}
list->tail = tmp;
list->length ++;
return true;
}
bool slist_prepend(slist_t * list, pointer data) {
slist_node_t * tmp = malloc(sizeof(slist_node_t) + list->size);
if(!tmp) return false;
tmp->next = list->head;
memcpy(tmp->data, data, list->size);
if(!list->tail) {
list->tail = tmp;
}
list->head = tmp;
list->length ++;
return true;
}
void slist_apply(slist_t * list, slist_apply_func_t apply_func) {
slist_node_t * elem;
for(elem = list->head; elem; elem = elem->next) {
apply_func(elem->data);
}
}
void slist_clear(slist_t * list) {
slist_node_t * curr = list->head, *next;
while(curr) {
next = curr->next;
if(list->dtor) {
list->dtor(curr->data);
}
free(curr);
curr = next;
}
list->head = list->tail = NULL;
list->length = 0;
}
static void slist_print(pointer data) {
printf("node:%s\n", *(string *)data);
}
void slist_reverse_from_node(slist_node_t ** node) {
slist_node_t * left, *curr;
left = *node;
*node = NULL;//初始化一个空的单链表
while(left) {
curr = left;
left = left->next;//从剩余的节点中取出最前面的一个节点
curr->next = *node;//将取出节点的下一个节点设为新建立的单链表
*node = curr;//对新建单链表进行重新赋值,使其成为添加了当前节点的最新单链表
}
}
void slist_reverse(slist_t * list) {
slist_reverse_from_node(&list->head);
}
void slist_string_dtor_func(pointer data) {
string * d = (string *)data;
free(*d);
}
void slist_print_node(slist_node_t *node, slist_apply_func_t func) {
if(node) {
func(node->data);
}
}
<file_sep>/*
* hsort.h
*
* Created on: 2012-4-20
* Author: hujin
*/
#ifndef HSORT_H_
#define HSORT_H_
#define HEAP_SIZE_ALLOC 100
typedef struct _heap{
int size;
int m_size;
char * data;
}heap_t;
#define heap_parent(i) (i >> 1)
#define heap_left(i) (i << 1)
#define heap_right(i) ((i << 1) + 1)
heap_t * heap_new();
void heap_build_max_heap(heap_t * heap);
void heap_max_heapify(heap_t * heap , int i);
void heap_sort(heap_t * heap);
heap_t * heap_ctor(heap_t * heap);
void heap_append(heap_t * heap, char a);
void heap_ajust(heap_t * heap);
void heap_free(heap_t * heap);
#endif /* HSORT_H_ */
<file_sep>/*
* bitmap.h
*
* Created on: 2012-4-26
* Author: hujin
*/
#ifndef BITMAP_H_
#define BITMAP_H_
typedef struct _bitmap{
unsigned char * bitmap;
int size;
int base;
}bitmap_t;
bitmap_t * bitmap_new(int size, int start);
int bitmap_set(bitmap_t * map, int index);
int bitmpa_get(bitmap_t * map, int index);
int bitmap_data(bitmap_t * map, int index);
void bitmap_free(bitmap_t * map);
#endif /* BITMAP_H_ */
<file_sep>/*
* bigint.c
*
* Created on: 2012-4-12
* Author: hujin
*/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "bigint.h"
#include <stdlib.h>
int8_t ctoi8(char c){
return c - '0';
}
char i8toc(int8_t u) {
return u + '0';
}
/*
bigint_t *bigint_new(){
bigint_t *ret = malloc(sizeof(bigint_t));
ret->data = NULL;
ret->len = 0;
return ret;
}
void bigint_alloc(bigint_t * p_int, int len) {
p_int->len = len;
p_int->data = malloc(sizeof(int8_t) * len);
}
void bigint_destroy(bigint_t * p_int) {
if(p_int == NULL) return;
if(p_int->data != NULL) {
free(p_int->data);
}
free(p_int);
}
*/
void bigint_assign(bigint_t * p_int, char * in) {
int i, len;
len = strlen(in);
for(i = len; i>0; i--) {
p_int->data[len - i] = ctoi8(in[i - 1]);
}
p_int->len = len;
}
void bigint_devide(bigint_t orgin, bigint_t * o1, bigint_t * o0) {
int i, new_len;
new_len = orgin.len / 2;
o1->len = o0->len = new_len;
for(i=0; i < new_len; i++){
o0->data[i] = orgin.data[i];
}
for(i = new_len; i < orgin.len; i++){
o1->data[i - new_len] = orgin.data[i];;
}
}
void bigint_plus(bigint_t a, bigint_t b, bigint_t *ret) {
int i, max_len;
max_len = a.len > b.len ? a.len : b.len;
for(i=0; i< max_len ; i++){
ret->data[i] = a.data[i] + b.data[i];
}
ret->len = max_len;
}
void bigint_milus(bigint_t a, bigint_t b, bigint_t *ret) {
int i, max_len;
max_len = a.len > b.len ? a.len : b.len;
for(i=0; i< max_len ; i++){
ret->data[i] = a.data[i] - b.data[i];
}
ret->len = max_len;
}
void bigint_move(bigint_t * integer, int n){
int i;
for(i = integer->len - 1; i>=0; i --){
integer->data[i + n] = integer->data[i];
}
for(i=n - 1; i>=0; i--) {
integer->data[i] = 0;
}
integer->len += n;
}
void bigint_multiplication(bigint_t a, bigint_t b, bigint_t * ret) {
bigint_t a1={0}, a0={0}, b1={0}, b0={0}, c2, c1, c0, tmp1, tmp2;
if(a.len > 1 && a.len == b.len) {
bigint_devide(a, &a1, &a0);
bigint_devide(b, &b1, &b0);
bigint_multiplication(a1, b1, &c2);
bigint_multiplication(a0, b0, &c0);
bigint_plus(a1, a0, &tmp1);
bigint_plus(b1, b0, &tmp2);
bigint_multiplication(tmp1, tmp2, &c1);
bigint_plus(c2, c0, &tmp1);
bigint_milus(c1, tmp1, &c1);
bigint_move(&c2, a.len);
bigint_move(&c1, a.len / 2);
bigint_plus(c2, c1, ret);
bigint_plus(*ret, c0, ret);
}else{
bigint_plus(a, b, ret);
}
}
void bigint_to_string(bigint_t integer, char output[]) {
int i;
for(i=0; i<integer.len; i++) {
printf("%d\n", integer.data[i]);
output[i] = i8toc(integer.data[i]);
}
output[i] = '\0';
}
void bigint_print(bigint_t integer, char * text) {
char output[BIGINT_MAX_LEN];
bigint_to_string(integer, output);
printf("\n%s -- string: %s len:%d\n",text, output, integer.len);
}
<file_sep>/*
* bigint.h
*
* Created on: 2012-4-12
* Author: hujin
*/
#ifndef BIGINT_H_
#define BIGINT_H_
#define BIGINT_MAX_LEN 100
typedef struct{
int len;
int data[BIGINT_MAX_LEN];
int sign;//标志该数的正负
}bigint_t;
void bigint_free(bigint_t * bi);
bigint_t * bigint_new_from_string(char * str);
bigint_t * bigint_add(bigint_t * f, bigint_t * s);
bigint_t * bigint_multi(bigint_t * f, bigint_t * s);
char * bigint_to_string(bigint_t * i);
void bigint_print(bigint_t * i);
#endif /* BIGINT_H_ */
<file_sep>/*
* merge_sort.c
*
* Created on: 2012-4-27
* Author: hujin
*/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define swap(a, b) \
{ \
char tmp;\
tmp = a;\
a = b;\
b = tmp;\
}
void merge(char * arr, int start,int mid, int end) {
if(end - start == 1) {
if (arr[start] > arr[end]) {
swap(arr[start], arr[end]);
}
}else {
int len = end - start + 1; //NOTICE: The len should be end - start + 1 .
char * tmp = malloc(sizeof(char) * len);
int i = start, j = mid + 1, k = 0;
while(i <= mid && j <= end) {
if(arr[i] < arr[j]) {
tmp[k++] = arr[i++];
}else{
tmp[k++] = arr[j++];
}
}
while(i <= mid) {
tmp[k++] = arr[i++];
}
while(j <= end) {
tmp[k++] = arr[j++];
}
for(k = start, i=0; i < len; i ++, k ++) {
arr[k] = tmp[i];
}
free(tmp);
}
}
void _merge_sort(char * arr, int start, int end) {
if(start < end) {
int mid = start + ((end - start) >> 1);
_merge_sort(arr, start, mid);
_merge_sort(arr, mid + 1, end);
merge(arr, start,mid,end);
}
}
void merge_sort(char * arr, int len) {
if(len < 0) {
len = strlen(arr);
}
_merge_sort(arr, 0 , len - 1);
}
<file_sep>/*
* string.h
*
* Created on: 2012-4-26
* Author: hujin
*/
#ifndef STRING_H_
#define STRING_H_
#include "types.h"
int string_has_chars_of(string str, string substr);
#endif /* STRING_H_ */
<file_sep>#include <stdio.h>
#include <time.h>
int Power_1(int a, int n) {
int p = a;
while(--n){
p = p * a;
}
return p;
}
int Power_2(int a, int n) {
if(n == 1) return a;
int t;
t = Power_2(a, n / 2);
if(n % 2 == 0){
return t * t;
}else{
return t * t * a;
}
}
int Power_3(int a, int n) {
if(n == 1) {
return a;
}else{
return a * Power_3(a, n - 1);
}
}
int main(int arvc, char **argv) {
int b = Power_2(2, 30);
int c = Power_3(2, 30);
clock_t start , finish;
int i = 1000000;
start = clock();
while(i--) {
Power_1(2, 30);
}
finish = clock();
printf("power1: using %ld \n", finish - start);
//--------------------------------
i = 1000000;
start = clock();
while(i--) {
Power_2(2, 30);
}
finish = clock();
printf("power1: using %ld \n", finish - start);
//--------------------------------
i = 1000000;
start = clock();
while(i--) {
Power_3(2, 30);
}
finish = clock();
printf("power1: using %ld \n", finish - start);
return 0;
}
<file_sep>/*
* binary_search_test.c
*
* Created on: 2012-4-26
* Author: hujin
*/
#include "binary_search.h"
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char input[50] = {0};
char e;
printf("Please input a sequence of chars.\n");
scanf("%s\n", input);
printf("Pleace input a char you want to search.\n");
e = getchar();
printf("%s\n%d\n", input, binary_search(input, strlen(input), e));
return 0;
}
<file_sep>/*
* hash_test.c
*
* Created on: 2012-5-8
* Author: hujin
*/
#include <stdio.h>
#include "hash_table.h"
void hash_apply_func(pointer data) {
string tmp = (string) data;
printf("%s\n", tmp);
}
int main(int argc, char **argv) {
hash_table_t * table = hash_table_new(3, NULL);
hash_table_insert(table, "hujin", sizeof("hujin"), "This is the 1nd elem in the HashTable.");
hash_table_insert(table, "bixue", sizeof("bixue"), "This is the 2nd elem in the HashTable.");
hash_table_insert(table, "linux", sizeof("linux"), "This is the 3nd elem in the HashTable.");
hash_table_insert(table, "linux2", sizeof("linux2"), "This is the 4nd elem in the HashTable.");
string str = (string) hash_table_find(table, "hujin", sizeof("hujin"));
if(str) {
printf("%s\n", str);
}else{
printf("find error\n");
}
str = (string)hash_table_find(table ,"linux2", sizeof("linux2"));
if(str) {
printf("%s\n", str);
}else{
printf("find error\n");
}
hash_table_apply(table, (hash_table_apply_func_t) hash_apply_func, true);
return 0;
}
<file_sep>/*
* statics.h
*
* Created on: 2012-5-30
* Author: hujin
*/
#ifndef STATICS_H_
#define STATICS_H_
int quick_select(int input[], int len, int select_index);
#endif /* STATICS_H_ */
<file_sep>/*
* test_bigint.c
*
* Created on: 2012-4-12
* Author: hujin
*/
#include <stdio.h>
#include "bigint2.h"
int main(int argc, char **argv) {
char input1[100] = {0};
char input2[100] = {0};
printf("Please input the first number:\n");
scanf("%s", input1);
printf("Please input the second number:\n");
scanf("%s", input2);
bigint_t * bi = bigint_new_from_string(input1);
bigint_t * bi2 = bigint_new_from_string(input2);
bigint_t * product = bigint_multi(bi, bi2);
char * output = bigint_to_string(product);
bigint_print(product);
printf("The product is of %s and %s is:%s\n",input1, input2, output);
free(output);
bigint_free(bi);
bigint_free(bi2);
bigint_free(product);
return 0;
}
<file_sep>/*
* heap_test.c
*
* Created on: 2012-4-20
* Author: hujin
*/
#include "hsort.h"
int main(int argc, char **argv) {
heap_t * heap = heap_new();
heap_append(heap, '5');
heap_appends(heap, "87202");
heap_print(heap);
heap_sort(heap);
heap_print(heap);
heap_free(heap);
return 0;
}
<file_sep>CC = gcc
BUILD_PATH=build
vpath %.h include
INCLUDE = -I/usr/include -Iinclude
CFLAGS = -Wall -O0 -g -std=c99 $(INCLUDE)
SOURCES = $(wildcard *.c)
OBJS = $(patsubst %.c,%.o,$(SOURCES))
EXES = sort_test test_bigint matrix power power2 heap_test binary_search_test string_test slist_test \
statics_test
$(EXES):$(OBJS)
$(CC) -o sort_test sort_test.o qsort.o merge_sort.o
$(CC) -o test_bigint test_bigint.o bigint2.o
$(CC) -o power power.o
$(CC) -o power2 power2.o
$(CC) -o matrix matrix.o
$(CC) -o heap_test heap_test.o hsort.o
$(CC) -o binary_search_test binary_search.o binary_search_test.o
$(CC) -o string_test string_test.o bitmap.o strings.o
$(CC) -o slist_test slist_test.o slist.o
$(CC) -o list_test list_test.o list.o
$(CC) -o hash_test hash_test.o hash_table.o
$(CC) -o statics_test statics_test.o statics.o
#include $(subst .c,.d,$(SOURCES))
#%.d:%.c
# $(CC) -M $(INCLUDE) $< > $@.$$$$; \
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
rm -f $@.$$$$
all: $(EXES)
%.o:%.c
@echo Compiling $< to $@ ......
$(CC) -c $(CFLAGS) $< -o $@
clean:
rm -f $(EXES)
find . -name '*.[od]' | xargs rm -f
.PHONY: clean
<file_sep>/*
* list.c
*
* Created on: 2012-5-8
* Author: hujin
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
list_t * _list_new(int size, list_dtor_func_t dtor) {
list_t * ret =(list_t *) malloc(sizeof(list_t));
if(!ret) return NULL;
ret->curr = NULL;
ret->dtor = dtor;
ret->size = size;
ret->head = NULL;
ret->tail = NULL;
ret->length = 0;
return ret;
}
bool list_append(list_t * list, pointer data) {
list_node_t * node = (list_node_t *) malloc(list->size + sizeof(list_node_t));
if(!node) return false;
node->next = NULL;
node->prev = list->tail;
memcpy(node->data, data, list->size);
if(!list->head) {
list->head = list->tail = node;
}else{
list->tail->next = node;
}
list->tail = node;
list->length ++;
return true;
}
bool list_prepend(list_t * list, pointer data) {
list_node_t * node = (list_node_t *) malloc(list->size + sizeof(list_node_t));
if(!node) return false;
node->prev = NULL;
node->next = list->head;
memcpy(node->data, data, list->size);
if(!list->head) {
list->head = list->tail = node;
}
list->head = node;
list->length ++;
return true;
}
void list_clear(list_t * list) {
list_node_t *curr = list->head, *next;
while(curr) {
if(list->dtor) {
list->dtor(curr->data);
}
next = curr->next;
free(curr);
curr = next;
}
list->head = list->tail = NULL;
list->length = 0;
}
/**
* insert the a element after the specified element.
* @param list_t * list the linked list you want to insert.
* @param pointer position
* @param pointer data;
* @param list_compare_func_t func
*/
bool list_insert(list_t * list,pointer position, pointer data, list_compare_func_t func) {
list_node_t * curr = list->head;
list_node_t * node = (list_node_t *)malloc(list->size + sizeof(list_node_t));
if(!node) return false;
while(curr) {
if(func && func(position, curr->data) == 0) {
break;
}
curr = curr->next;
}
if(curr) {
memcpy(node->data, data, list->size);
node->next = curr->next;
node->prev = curr;
curr->next = node;
}else{
list_append(list, data);
}
return true;
}
void list_apply(list_t * list, list_apply_func_t func) {
list_node_t * curr = list->head;
while(curr) {
func(curr->data);
curr = curr->next;
}
}
<file_sep>/*
* statics_test.c
*
* Created on: 2012-5-30
* Author: hujin
*/
#include <stdio.h>
#include "statics.h"
int main(int argc, char **argv) {
//0 2 4 5 8 9 10 23
int arr[8] = {9, 2 ,4 ,5, 8, 10, 0, 23};
int select_index = 5;
int index = quick_select(arr, 8, select_index);
printf("the %dth index of array is %d\n", select_index, arr[index]);
return 0;
}
<file_sep>/*
* string_test.c
*
* Created on: 2012-4-26
* Author: hujin
*/
#include "strings.h"
#include <stdio.h>
int main(int argc, char **argv) {
char a[] ="qwerty";
char b[] = "ert";
char c[] = "kijd";
if(string_has_chars_of(a, b)) {
printf("string \"%s\" contains chars of \"%s\".\n", a, b);
}else{
printf("string \"%s\" do not contains chars of \"%s\".\n", a, b);
}
if(string_has_chars_of(a, c)) {
printf("string \"%s\" contains chars of \"%s\".\n", a, c);
}else{
printf("string \"%s\" do not contains chars of \"%s\".\n", a, c);
}
return 0;
}
<file_sep>#include <stdio.h>
#define swap(e1, e2) {\
char tmp;\
tmp = e1;\
e1 = e2;\
e2 = tmp;\
}
/**
* 该版本不好
*/
int partition(char input[], int l, int r){
char p = input[l];
int i = l, j = r + 1;
do{
do{
i++;
}while(input[i] < p);
do{
j--;
}while(input[j] > p);
swap(input[i], input[j]);
}while(j > i);
swap(input[i], input[j]);
swap(input[j], input[l]);
return j;
}
/**
* 双向扫描进行分区
*/
int partition2(char input[], int left, int right) {
int l, r;
l = left, r = right;
char p = input[left];
while(l < r) {
// 条件应该 为 l < r 否则会出现过多的交换
while(l < r && input[r] >= p) {
r --;
}
input[l] = input[r];
while(l < r && input[l] <= p) {
l ++;
}
input[r] = input[l];
}
input[l] = p;
return l;
}
/**
* 算法导论分区实现
*/
int partition3(char input[], int left, int right) {
// j 作为开路先锋,找寻比小于等于 pivot 的元素,然后再与 i 进行交换,却表 i 坐在元素比 pivot 小
int i = left -1, j;
char p = input[right];
for(j = left; j < right; j ++) {
if(input[j] <= p) {
i ++;
swap(input[i], input[j]);
}
}
swap(input[i + 1], input[right]);
return i + 1;
}
void quicksort(char input[], int l, int r){
//partition(input, l, r);
if (l < r){
int p;
p = partition3(input, l, r);
quicksort(input, l, p-1);
quicksort(input, p+1, r);
}
}
<file_sep>/*
* msort.h
*
* Created on: 2012-4-11
* Author: hujin
*/
#ifndef MSORT_H_
#define MSORT_H_
#endif /* MSORT_H_ */
<file_sep>
/**
* 矩阵乘法分治算法实现,仅支持2^n的矩阵乘法。
*/
#include <stdio.h>
#include <stdlib.h>
#define MATRIX_MAX_DIMENSION 32
#define matrix_for_init {{{0},{0}},0}
typedef struct{
int data[MATRIX_MAX_DIMENSION][MATRIX_MAX_DIMENSION];
int dimension;
}matrix_t;
/**
* indicate whether a number is the power of 2.
* @param int n The input number n.
* @return int 1 or 0
*/
int is_power_of_2(int n) {
if(n && !(n & (n - 1))){
return 1;
}else{
return 0;
}
}
void matrix_input(matrix_t *m1){
printf("The dimension(should be the power of 2):");
scanf("%d", &m1->dimension);
if(m1->dimension > MATRIX_MAX_DIMENSION) {
printf("error: the max dimension should be %d.\n", MATRIX_MAX_DIMENSION);
exit(-1);
}
if(!is_power_of_2(m1->dimension)) {
printf("error: the dimension of matrix should the power of 2.\n");
exit(-1);
}
printf("The sequence of %d numbers:", m1->dimension * m1->dimension);
int i, j;
for(i=0;i < m1->dimension ; i ++){
for(j=0; j < m1->dimension; j ++){
scanf("%d", &m1->data[i][j]);
}
}
}
int matrix_add(matrix_t m1, matrix_t m2, matrix_t *ret){
if(m1.dimension != m2.dimension) {
printf("error: the dimension do not match!\n");
return 0;
}
int i,j;
int dim = m1.dimension;
for(i=0; i < dim; i ++) {
for(j=0; j < dim; j++) {
(*ret).data[i][j] = m1.data[i][j] + m2.data[i][j];
}
}
ret->dimension = dim;
return 1;
}
/**
*
* @param matrix_t m1
* @param matrix_t m2
* @param matrix_t *ret
*
*/
int matrix_sub(matrix_t m1, matrix_t m2, matrix_t *ret){
if(m1.dimension != m2.dimension) {
printf("error: the dimension do not match!\n");
return 0;
}
int i,j;
int dim = m1.dimension;
for(i=0; i < dim; i ++) {
for(j=0; j < dim; j++) {
(*ret).data[i][j] = m1.data[i][j] - m2.data[i][j];
}
}
ret->dimension = dim;
return 1;
}
void matrix_split(matrix_t m, matrix_t *m00, matrix_t *m01, matrix_t *m10, matrix_t * m11) {
int dim = m.dimension / 2;
int i,j;
m00->dimension = m01->dimension = m10->dimension = m11->dimension = dim;
for(i=0; i < m.dimension; i ++){
for(j=0; j < m.dimension; j ++){
if(i < dim && j < dim){
m00->data[i][j] = m.data[i][j];
}else if(i < dim && j >= dim) {
m01->data[i][j - dim] = m.data[i][j];
}else if(i >= dim && j< dim) {
m10->data[i - dim][j] = m.data[i][j];
}else{
m11->data[i - dim][j - dim] = m.data[i][j];
}
}
}
}
void matrix_multi(matrix_t mt1, matrix_t mt2, matrix_t *ret){
if(mt1.dimension != mt2.dimension) {
printf("error:the dimension of the two matrix do not match!\n");
exit(-1);
}
if(mt1.dimension < 2) {
ret->data[0][0] = mt1.data[0][0] * mt2.data[0][0];
ret->dimension = 1;
}else{
int dim = mt1.dimension / 2;
matrix_t m1 ,m2, m3, m4, m5, m6, m7;
matrix_t a00, a01, a10, a11, b00, b01, b10, b11;
matrix_t tmp1, tmp2;
matrix_split(mt1, &a00, &a01, &a10, &a11);
matrix_split(mt2, &b00, &b01, &b10, &b11);
matrix_add(a00, a11, &tmp1);
matrix_add(b00, b11, &tmp2);
matrix_multi(tmp1, tmp2 , &m1);
matrix_add(a10, a11, &tmp1);
matrix_multi(tmp1, b00, &m2);
matrix_sub(b01, b11, &tmp1);
matrix_multi(a00, tmp1, &m3);
matrix_sub(b10, b00, &tmp1);
matrix_multi(a11, tmp1, &m4);
matrix_add(a00, a01, &tmp1);
matrix_multi(tmp1, b11, &m5);
matrix_sub(a10, a11, &tmp1);
matrix_add(b00, b01, &tmp2);
matrix_multi(tmp1, tmp2, &m6);
matrix_sub(a01, a11, &tmp1);
matrix_add(b10, b11, &tmp2);
matrix_multi(tmp1, tmp2, &m7);
matrix_t c1, c2, c3, c4;
matrix_add(m1, m4, &c1);
matrix_add(m7, c1, &c1);
matrix_sub(c1, m5, &c1);
matrix_add(m3, m5, &c2);
matrix_add(m2, m4, &c3);
matrix_add(m1, m3, &c4);
matrix_add(m6, c4, &c4);
matrix_sub(c4, m2, &c4);
int i,j;
for(i=0;i < dim; i++) {
for(j=0;j < dim; j++) {
ret->data[i][j] = c1.data[i][j];
ret->data[i][j + dim] = c2.data[i][j];
ret->data[i + dim][j] = c3.data[i][j];
ret->data[i + dim][j + dim] = c4.data[i][j];
}
}
ret->dimension = mt1.dimension;
}
}
/**
* print a matrix .
*/
void matrix_print(matrix_t m){
int dim = m.dimension;
int i, j;
for(i=0; i < dim; i++) {
for(j=0; j < dim; j++) {
printf("%5d", m.data[i][j]);
}
printf("\n");
}
printf("\n");
}
int main(int argc, char **argv) {
matrix_t m1 = matrix_for_init, m2 = matrix_for_init;
printf("Please input the first matrix:\n");
matrix_input(&m1);
matrix_print(m1);
printf("Please input the second matrix:\n");
matrix_input(&m2);
matrix_print(m2);
matrix_t ret = matrix_for_init;
matrix_multi(m1, m2, &ret);
//matrix_add(m1, m2, &m3);
matrix_print(ret);
return 0;
}
<file_sep>/*
* statics.c
* some algorithms resolve order statistics problems.
*
* Created on: 2012-5-30
* Author: hujin
*/
#include <stdio.h>
#define swap(a, b) {\
tmp = a;\
a = b;\
b = tmp;}\
/**
*
*/
int quick_partition(int arr[], int l, int r) {
int i = l - 1, j = l;
int p = arr[r], tmp;
for(; j < r; j ++) {
if(arr[j] < p) {
i ++;
swap(arr[i], arr[j]);
}
}
i ++;
swap(arr[i], arr[r]);
return i;
}
int _quick_select(int input[], int l, int r, int i) {
if(l == r) {
return l;
}
int p = quick_partition(input, l, r);
int k = p - l + 1;
if(i < k) {
return _quick_select(input, l, p - 1, i);
}else if(i == k) {
return p;
}else {
return _quick_select(input, p + 1 , r, i - k);
}
}
/**
* find the kth smallest element in a given array .
* @param int input[] The given array
* @param int l The lenght of given array
* @param int select_index
*/
int quick_select(int input[], int len, int select_index) {
return _quick_select(input, 0, len - 1, select_index);
}
<file_sep>/*
* hsort.c
*
* Created on: 2012-4-20
* Author: hujin
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hsort.h"
#define swap(a, b) \
{\
char tmp;\
tmp = a;\
a = b;\
b = tmp;\
}
heap_t * heap_new() {
heap_t * ret = malloc(sizeof(heap_t));
ret->size = 0;
ret->m_size = HEAP_SIZE_ALLOC;
ret->data = malloc(sizeof(char) * HEAP_SIZE_ALLOC);
memset(ret->data, 0, sizeof(char) * HEAP_SIZE_ALLOC);
return ret;
}
void heap_append(heap_t * heap, char c) {
if(heap->size == heap->m_size) {
heap->data = realloc(heap->data, sizeof(char) * (heap->m_size + HEAP_SIZE_ALLOC));
}
heap->data[heap->size + 1] = c;
heap->size ++ ;
}
void heap_appends(heap_t * heap, char * str) {
int i=0;
while(str[i] != '\0') {
heap->data[heap->size + 1] = str[i];
heap->size ++;
i ++;
}
}
/**
* 《算法分析与设计》调整成大顶堆算法实现
*/
void heap_ajust(heap_t * heap) {
int k;
int is_heap;
char v;
int j;
for(int i = heap->size / 2; i > 0; i --) {
k = i;
v = heap->data[k];
is_heap = 0;
while(!is_heap && 2 * k <= heap->size) {
j = 2 * k;
if(j < heap->size) {
if(heap->data[j] < heap->data[j + 1]) {
j ++;
}
}
if(v >= heap->data[j]) {
is_heap = 1;
}else{
heap->data[k] = heap->data[j];
k = j;
}
}
}
heap->data[k] = v;
}
/**
*/
void heap_max_heapify(heap_t * heap , int i) {
int left,
right,
largest;
left = heap_left(i);
right = heap_right(i);
if(left <= heap->size && heap->data[left] > heap->data[i]) {
largest = left;
}else{
largest = i;
}
if(right <= heap->size && heap->data[right] > heap->data[largest]) {
largest = right;
}
if(largest != i) {
swap(heap->data[i], heap->data[largest]);
heap_max_heapify(heap, largest);
}
}
void heap_build_max_heap(heap_t * heap) {
int i = heap->size >> 1;
for(;i >= 1; i --) {
heap_max_heapify(heap, i);
}
}
void heap_sort(heap_t * heap) {
int i;
heap_build_max_heap(heap);
for(i = heap->size; i >= 2; i --) {
swap(heap->data[i], heap->data[1]);
heap->size -- ;
heap_max_heapify(heap, 1);
}
}
void heap_print(heap_t * heap) {
printf("%s\n", heap->data + 1);
}
void heap_free(heap_t * p_heap) {
free(p_heap->data);
free(p_heap);
}
<file_sep>/*
* binary_search.h
*
* Created on: 2012-4-26
* Author: hujin
*/
#ifndef BINARY_SEARCH_H_
#define BINARY_SEARCH_H_
int binary_search(char * str, int len, char e);
#endif /* BINARY_SEARCH_H_ */
<file_sep>/*
* bigint.c
*
* Created on: 2012-4-12
* Author: hujin
*/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "bigint2.h"
#include <stdlib.h>
bigint_t * bigint_new() {
bigint_t * ret = (bigint_t *) malloc(sizeof(bigint_t));
if(ret == NULL) return NULL;
memset(ret, 0, sizeof(bigint_t));
return ret;
}
bigint_t * bigint_new_from_string(char * str){
bigint_t * ret = (bigint_t *) malloc(sizeof(bigint_t));
if(ret == NULL) return NULL;
memset(ret, 0, sizeof(bigint_t));
int pos = 1, i;
if(str[0] == '-'){
ret->sign = -1;
}else if(str[0] == '+') {
ret->sign = 1;
}else{
ret->sign = 1;
pos = 0;
}
int len = strlen(str);
int j = 0;
for(i = len - 1; i >= pos; i--, j++){
ret->data[j] = str[i] - '0';
}
ret->len = len;
return ret;
}
int bigint_cmp_ob(bigint_t f, bigint_t s) {
int i;
if(f.len > s.len){
return 1;
}else if(f.len < s.len) {
return -1;
}else{
for(i=0; i < f.len; i++) {
if(f.data[i] > s.data[i]) {
return 1;
}else if(f.data[i] < s.data[i]) {
return -1;
}
}
return 0;
}
}
bigint_t * bigint_add(bigint_t * a, bigint_t * b) {
bigint_t * ret = bigint_new();//make an empty bigint.
if(!ret) return NULL;
/*
if(a->sign * b->sign > 0) {
ret->sign = a->sign;
}else{
}
*/
int i;
int max = a->len > b->len ? a->len : b->len;
for(i = 0; i < max; i ++) {
ret->data[i] = a->data[i] + b->data[i];
}
ret->len = i;
return ret;
}
void bigint_print(bigint_t * bi){
if(bi->sign < 0){
putchar('-');
}
int i;
int * data = bi->data;
for(i=0; data[i] != 0 || i < bi->len; i++) {
if(data[i] > 10) {
data[i + 1] += data[i] / 10;
data[i] = data[i] % 10;
}
}
bi->len = i;
for(i = bi->len - 1; i >= 0; i--) {
printf("%d", data[i]);
}
printf("\n");
}
bigint_t * bigint_multi(bigint_t * f, bigint_t * s){
bigint_t * ret = bigint_new();
if(ret == NULL) return NULL;
int i, j;
for(i = 0; i < s->len; i ++) {
for(j = 0; j < f->len; j ++) {
ret->data[i + j] += f->data[j] * s->data[i];
//printf("%d * %d -- %d:%d",f->data[j], s->data[i], i, j);
}
//printf("\n");
}
ret->len = i + j - 1;
return ret;
}
char * bigint_to_string(bigint_t * bi) {
int i, j, is_neg;
int * data = bi->data;
for(i=0; data[i] != 0 || i < bi->len; i++) {
if(data[i] > 10) {
data[i + 1] += data[i] / 10;
data[i] = data[i] % 10;
}
}
bi->len = i;
if(bi->sign < 0) {
is_neg = 1;
}else{
is_neg = 0;
}
char * ret = malloc(sizeof(char) * (bi->len + is_neg));
for(i = bi->len - 1, j = 0; i >= 0; i--, j ++) {
ret[i + is_neg] = data[j] + '0';
}
if(is_neg) {
ret[0] = '-';
}
return ret;
}
void bigint_free(bigint_t * bi) {
free(bi);
}
<file_sep>/*
* list_test.c
*
* Created on: 2012-5-8
* Author: hujin
*/
#include <stdio.h>
#include "list.h"
typedef struct _record{
int id;
char url[200];
}record;
int record_compare_func(pointer r1, pointer r2) {
record * rr1 = (record *)r1;
record * rr2 = (record *)r2;
if(rr1->id > rr2->id) {
return 1;
}else if(rr1->id < rr2->id) {
return -1;
}else{
return 0;
}
}
void record_print(pointer data) {
record * r = (record *)data;
printf("%d: %s\n", r->id, r->url);
}
int main(int argc, char **argv) {
list_t * list = list_new(record, NULL);
record re1 = {1, "www.baidu.com"};
list_append(list, &re1);
record re3 = {3, "www.sohu.com"};
list_append(list, &re3);
record re5 = {5, "www.sina.com"};
list_append(list, &re5);
record re4 = {4, "www.163.com"};
//list_insert(list, &re3, &re4,(list_compare_func_t) record_compare_func);
record ren = {10, "www.163.com"};
list_insert(list, &ren, &re4,(list_compare_func_t) record_compare_func);
list_apply(list, (list_apply_func_t) record_print);
return 0;
}
<file_sep>/*
* hash_table.c
*
* Created on: 2012-5-8
* Author: hujin
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash_table.h"
ulong hash_func(string key, uint key_len) {
ulong hash = 31;
for(int i=0;key[i] != 0; i ++) {
hash = hash + key[i] * 33;
}
return hash;
}
hash_table_t * hash_table_new(int size, hash_table_dtor_func_t dtor) {
hash_table_t * ht = malloc(sizeof(hash_table_t));
if(!ht) return NULL;
ht->dtor = dtor;
ht->size = 0;
ht->bucket_size = size;
ht->curr = NULL;
ht->head = NULL;
ht->tail = NULL;
ht->bucket = malloc(sizeof(hash_bucket_t *) * ht->bucket_size);
memset(ht->bucket, 0, ht->bucket_size);
return ht;
}
bool hash_table_insert(hash_table_t * ht, string key, int key_size, pointer data){
ulong idx = hash_func(key, key_size);
ulong bidx = idx % (ht->bucket_size - 1);
hash_bucket_t * nb = malloc(sizeof(hash_bucket_t) + key_size);
if(!nb) return false;
nb->data = data;
nb->key_size = key_size;
nb->next = NULL;
nb->elem_next = NULL;
nb->elem_prev = ht->tail;
nb->idx = idx;
if(ht->size == 0) {
ht->head = ht->tail = nb;
}else {
ht->tail->elem_next = nb;
ht->tail = nb;
}
memcpy(nb->key, key, key_size);
hash_bucket_t * bucket = ht->bucket[bidx];
if(!bucket) {
ht->bucket[bidx] = nb;
}else{// 冲突解决
while(bucket->next) {
bucket = bucket->next;
}
bucket->next = nb;
}
ht->size ++;
return true;
}
pointer hash_table_find(hash_table_t * ht, string key, uint key_size) {
ulong idx = hash_func(key, key_size);
ulong bidx = idx % (ht->bucket_size - 1);
hash_bucket_t * bucket = ht->bucket[bidx];
if(!bucket) {
return NULL;
}else {
while(bucket) {
if(strcmp(bucket->key, key) == 0) {
break;
}
bucket = bucket->next;
}
return bucket->data;
}
}
void hash_table_apply(hash_table_t * ht, hash_table_apply_func_t func, bool reverse) {
hash_bucket_t * bucket = reverse ? ht->tail : ht->head;
while(bucket) {
if(func) {
func(bucket->data);
}
bucket = reverse ? bucket->elem_prev : bucket->elem_next;
}
}
void hash_table_clear(hash_table_t * ht) {
hash_bucket_t * bucket = ht->head, *tmp;
ulong idx;
while(bucket) {
if(ht->dtor) {
ht->dtor(bucket->data);
}
idx = bucket->idx;
tmp = bucket->elem_next;
free(bucket);
ht->bucket[idx % ht->bucket_size - 1] = NULL;
bucket = tmp;
}
ht->head = ht->tail = NULL;
ht->curr = NULL;
ht->size = 0;
}
<file_sep>/*
* msort.c
*
* Created on: 2012-4-11
* Author: hujin
*/
#include <stdio.h>
<file_sep>/*
* hashtable.h
*
* Created on: 2012-5-8
* Author: hujin
*/
#ifndef HASH_TABLE_H_
#define HASH_TABLE_H_
#include "types.h"
typedef void (*hash_table_dtor_func_t)(pointer data);
typedef void (*hash_table_apply_func_t)(pointer data);
typedef struct _hash_bucket{
ulong idx;
uint key_size;
pointer data;
struct _hash_bucket * next;
struct _hash_bucket * elem_next;
struct _hash_bucket * elem_prev;
char key[0];
}hash_bucket_t;
typedef struct _hash_table{
int size;
int bucket_size;
hash_bucket_t ** bucket;
hash_bucket_t * head;
hash_bucket_t * tail;
hash_bucket_t * curr;
hash_table_dtor_func_t dtor;
}hash_table_t;
hash_table_t * hash_table_new(int size, hash_table_dtor_func_t dtor);
void hash_table_clear(hash_table_t * ht);
void hash_table_destroy(hash_table_t * ht);
void hash_table_rehash(hash_table_t * ht);
bool hash_table_insert(hash_table_t * ht, string key, int key_len, pointer data);
bool hash_table_remove(hash_table_t * ht, string key, int key_len);
pointer hash_table_find(hash_table_t * ht, string key, uint key_size);
void hash_table_apply(hash_table_t * ht, hash_table_apply_func_t func, bool reverse);
#endif /* HASH_TABLE_H_ */
<file_sep>/*
* power.c
* compute the power of a number in different strategy.
* NOTE: this progrom only works fine in Unix like system.
* Created on: 2012-4-12
* Author: hujin
*/
#include <stdio.h>
#include <sys/time.h>
/**
* 常规方法
*/
int power1(int num, int power) {
int ret = num, i;
for(i = 0; i < power - 1; i ++) {
ret *= num;
}
return ret;
}
/**
* 分治法
*/
int power2(int num, int power) {
if(power == 1) {
return num;
}else if(power % 2){
return power2(num, power / 2) * num;
}else{
return power2(num, power / 2);
}
}
/**
* 减治法
*/
int power3(int num, int power) {
if(power == 1){
return num;
}else{
return power3(num, power - 1) * num;
}
}
int calc_time(int num, int power, int(*power_func)(int, int)) {
int i = 10000000;
struct timeval start , end;
gettimeofday(&start, NULL);
while(i--) {
(*power_func)(num, power);
}
gettimeofday(&end, NULL);
return end.tv_usec + 1000000 * end.tv_sec - (start.tv_usec + start.tv_sec * 1000000);
}
int main(int argc, char **argv) {
printf("常规方法使用时间:%d 微秒\n", calc_time(2, 30, power1));
printf("分治方法使用时间:%d 微秒\n", calc_time(2, 30, power2));
printf("减治方法使用时间:%d 微秒\n", calc_time(2, 30, power3));
return 0;
}
<file_sep>/*
* string.c
*
* Created on: 2012-4-26
* Author: hujin
*/
#include "bitmap.h"
#include "strings.h"
/**
* 判断字符串是否包含子串中的所有字符
* @param char * str 待搜索的字符串
* @param char * substr 待搜索的字符列表
* @return 0 or 1
*/
int string_has_chars_of(string str, string substr) {
bitmap_t * bitmap = bitmap_new(256, 0);
int i = 0;
while(str[i] != '\0') {
bitmap_set(bitmap, str[i]);
i ++;
}
i = 0;
while(substr[i] != '\0') {
if(0 == bitmpa_get(bitmap, substr[i])) {
bitmap_free(bitmap);
return 0;
}
i ++;
}
bitmap_free(bitmap);
return 1;
}
<file_sep>/*
* slist.h
*
* Created on: 2012-4-28
* Author: hujin
*/
#ifndef SLIST_H_
#define SLIST_H_
#include <string.h>
#include <malloc.h>
#include "types.h"
typedef struct _slist_node {
struct _slist_node * next;
char data[0];/*Needs to always be the last in the struct.*/
}slist_node_t;
typedef void (*slist_dtor_func_t)(pointer data);
typedef int (*slist_compare_func_t)(slist_node_t * , slist_node_t *);
typedef void (*slist_apply_func_t)(pointer);
typedef struct _slist{
slist_node_t * head;
slist_node_t * tail;
int length;
int size;
slist_dtor_func_t dtor;
slist_node_t * curr;
}slist_t;
#define slist_new(type, dtor) _slist_new(sizeof(type), dtor)
#define slist_destroy(pslist) slist_clear(pslist);\
free(pslist);\
pslist = NULL;
slist_t * _slist_new(int size, slist_dtor_func_t dtor);
void slist_apply(slist_t * list, slist_apply_func_t apply_func);
bool slist_append(slist_t * list, pointer data);
bool slist_prepend(slist_t * list, pointer data);
void slist_clear(slist_t * list);
void slist_reverse(slist_t * list);
void slist_reverse_from_node(slist_node_t ** node);
#define slist_append_ex(list, type ,salar) {\
type tmp = salar;\
slist_append(list, &tmp);\
}
#define slist_appendi(list, integer) slist_append_ex(list, int, integer)
#define slist_appendl(list, longval) slist_append_ex(list, long, longval)
#define slist_appendf(list, floatval) slist_append_ex(list, float, floatval)
#define slist_appendd(list, doubleval) slist_append_ex(list, double, doubleval)
#define slist_appends(list, str) {\
string tmp = (string)strdup(str);\
slist_append(list, &tmp);\
}
void slist_string_dtor_func(pointer data);
#endif /* SLIST_H_ */
<file_sep>/*
* types.h
*
* Created on: 2012-4-28
* Author: hujin
*/
#ifndef TYPES_H_
#define TYPES_H_
typedef void * pointer;
typedef char * string;
typedef enum{
false,
true
}bool;
typedef unsigned int uint;
typedef unsigned long ulong;
typedef unsigned char uint8;
#endif /* TYPES_H_ */
<file_sep>/*
* merge_sort.h
*
* Created on: 2012-4-27
* Author: hujin
*/
#ifndef MERGE_SORT_H_
#define MERGE_SORT_H_
void merge_sort(char * arr, int len);
#endif /* MERGE_SORT_H_ */
<file_sep>/*
* binary_search.c
*
* Created on: 2012-4-26
* Author: hujin
*/
#include <stdio.h>
#include <string.h>
/**
* 折半查找非递归实现,能够找到出现字符的第一个位置。
* @param char * str 待查找的字符串
* @param int len 待查找字符串的长度
* @param char e 要查找的元素
*/
int binary_search(char * str, int len, char e) {
int ret = -1,
left = 0,
right = len - 1,
mid;
while(left < right) {
mid = left + ((right - left) >> 1);
if(str[mid] > e) {
right = mid - 1;
}else if(str[mid] < e){
left = mid + 1;
}else{
while(str[mid-1] == e) {
mid --;
}
ret = mid;
break;
}
}
return ret;
}
| 6c4351f2f1f3abf748435927771e81b7b00445bb | [
"C",
"Makefile"
] | 40 | C | bixuehujin/algorithms | 145bf56ce2625caa7931bb800d52b8f1cea5bb50 | b1f9646ae7c4a3833fbcc8e8db9c2a193344e873 |
refs/heads/main | <file_sep>const { circleCircumference, circleArea } = require("./circle");
circleCircumference();
circleArea();
<file_sep>let posts = [
{ id: "1633171026249", title: "Kodluyoruz", content: "Selamlar Kodluyoruz" },
{ id: "1633171026210", title: "Patika.dev", content: "<NAME>" },
];
let userData = {
title: process.argv[2],
content: process.argv[3],
};
let addPost = () => {
posts.push({ id: new Date().getTime(), ...userData });
};
async function getPosts() {
await addPost();
console.log(posts);
}
getPosts();
<file_sep>let r = 5;
let pi = 3.14;
let circleCircumference = () => {
let result = pi * r * 2;
console.log("result :>> ", result);
};
let circleArea = () => {
let result = pi * Math.pow(r, 2);
console.log("result :>> ", result);
};
module.exports = {
circleCircumference,
circleArea,
};
<file_sep>const fs = require("fs");
// CREATE FILE
fs.writeFile(
"employee.json",
"{'name':'<NAME>','salary':2000}",
(err, data) => {
console.log("olusturuldu");
}
);
// READ FILE
fs.readFile("./employee.json", "utf8", function callback(err, data) {
console.log("data :>> ", data);
});
// UPDATE FILE
fs.appendFile(
"employee.json",
"\n,{'name':'enes','salary':4000}",
(err, data) => console.log(data)
);
// DELETE FILE
// fs.unlink("employee.json", (err, data) => {
// if (err) {
// console.error(err);
// } else {
// console.log("silindi");
// }
// });
<file_sep># patika-node
Patika.dev node.js kursu ödevler ve diğer çalışmalar
| 41248678f26df9ccdfe349fbf39e8fde66e6669a | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | Enes-ets34/patika-node | 3a4c106309a64812678f675c74a8f0d68da301a6 | 50a04c5cd3bb85e4c981d473a4541a160796b738 |
refs/heads/master | <repo_name>Tukamotosan/KuramotoModel<file_sep>/src/KuramotoModel/main.cpp
#include <stdio.h>
#include <omp.h>
#include "Simulator.h"
int main()
{
#pragma omp parallel for
for (int i = 0; i < 10; i++) {
printf("fuckin!! world!!!(%d)\n", i);
}
Simulator simulator;
for (int i = 0; i < 100; i++) {
simulator.exec2();
}
return 0;
}<file_sep>/src/KuramotoModel/Simulator.h
#pragma once
#include <opencv2/opencv.hpp>
#include <omp.h>
#define _USE_MATH_DEFINES
#include <math.h>
using namespace cv;
class Simulator
{
public:
// 2D Matrix that contains all oscilator's frequency
Mat Thetas;
// Difference of Thetas
Mat ThetasDash;
// divergence (12)
// Filter of fourth derivative of the Laplacian of the Gaussian
Mat LapLapGaussFilter;
// size of oscilators(n=w*h)
int w, h;
// size of oscilators and K
int N, K;
// paramters of filter
float sigmaFilter, mueFilter, maxFilter, rFilter;
int cnt;
// generator of norm
RNG rng;
// mue and sigma of rng
float sigmaOmega, mueOmega;
// parameters of gamma(13)
float beta, R;
// delta time
float dt;
Simulator();
~Simulator();
/*!
*/
void exec();
// Using eq.13 as PIF
void exec2();
/*!
* \brief make_filter. Make filter of fourth derivative of a Gaussian function.
* \param lmin
* \param lmax
* \param sigma
* \param r
* \return
*/
Mat make_filter(const int lmin, const float lmax, const float sigma, const float r);
/*!
* \brief laplap_gaussian. fourth derivative of a Gaussian function
* \param x
* \param y
* \param sigma
* \param r
* \return
*/
float laplap_gaussian(const float x, const float y, const float sigma, const float r);
/*!
* \brief get_r
* \param sigma
* \param R
* \return
*/
float get_r(const float sigma, const float R);
private:
float map(const float x, const float xMin, const float xMax, const float yMin, const float yMax);
};
<file_sep>/README.md
# KuramotoModel
[Generative models of cortical oscillations: neurobiological implications of the Kuramoto model](http://journal.frontiersin.org/article/10.3389/fnhum.2010.00190/full)
の3章あたりの実装.行列計算をOpenMPのMatを使い,OpenMPで並列計算を行う.
128×128の以下のような画像を出力する



<file_sep>/src/KuramotoModel/Simulator.cpp
#include "Simulator.h"
Simulator::Simulator()
{
w = 128; h = 128;
N = w * h;
K = 6 * N;
rng(getTickCount());
mueOmega = 0.0;
sigmaOmega = 0.5;
Thetas = Mat::zeros(w, h, CV_32F);
ThetasDash = Mat::zeros(w, h, CV_32F);
maxFilter = 2.0;
sigmaFilter = 4.0;
rFilter = get_r(sigmaFilter, maxFilter);
beta = 1.2;
R = 0.25;
dt = 0.001;
LapLapGaussFilter = make_filter(-20, 20, sigmaFilter, rFilter);
cnt = 0;
}
Simulator::~Simulator()
{
}
/*!
*/
void Simulator::exec() {
#pragma omp parallel for
for (int x1 = 0; x1 < w; x1++) {
#pragma omp parallel for
for (int y1 = 0; y1 < h; y1++) {
Mat m = Mat::zeros(w, h, CV_32F);
#pragma omp parallel for
for (int x2 = -20; x2 <= 20; x2++) {
float x3 = x1 + x2;
if (x3 < 0 || x3 >= w) { continue; }
#pragma omp parallel for
for (int y2 = -20; y2 <= 20; y2++) {
float y3 = y1 + y2;
if (y3 < 0 || y3 >= h) { continue; }
float v = sin(Thetas.at<float>(x3, y3) - Thetas.at<float>(x1, y1));
m.at<float>(x3, y3) = v;
}
}
Mat m2;
filter2D(m, m2, -1, LapLapGaussFilter);
ThetasDash.at<float>(x1, y1) = (float)rng.gaussian(sigmaOmega) + K*m2.at<float>(x1, y1) / N;
}
}
// compute Thetas
Thetas += dt * ThetasDash;
cnt++;
double minVal, maxVal;
Point minLoc, maxLoc;
minMaxLoc(Thetas, &minVal, &maxVal, &minLoc, &maxLoc);
printf("cnt = %d\t(min,max)=(%.8f,%.8f)\n", cnt, minVal, maxVal);
if ((cnt % 10) != 0) { return; }
Mat gray_image(w, h, CV_8UC1);
float max = 3.2;
float v;
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
v = map(Thetas.at<float>(x, y), minVal, maxVal, 0, 255);
gray_image.at<unsigned char>(y, x) = (unsigned char)v;
}
}
imwrite("data\\chap3_2\\gray" + std::to_string(cnt) + ".jpg", gray_image);
}
/*!
*/
void Simulator::exec2() {
/*Mat m0 = Mat::zeros(4, 4, CV_32F);
m0.forEach<float>([](float &p, const int *position) -> void {
p = position[0];
});*/
#pragma omp parallel for
for (int x1 = 0; x1 < w; x1++) {
#pragma omp parallel for
for (int y1 = 0; y1 < h; y1++) {
Mat m = Mat::zeros(w, h, CV_32F);
float v = 0.0;
#pragma omp parallel for
for (int x2 = -20; x2 <= 20; x2++) {
float x3 = x1 + x2;
if (x3 < 0 || x3 >= w) { continue; }
#pragma omp parallel for
for (int y2 = -20; y2 <= 20; y2++) {
float y3 = y1 + y2;
if (y3 < 0 || y3 >= h) { continue; }
//float v = sin(Thetas.at<float>(x3, y3) - Thetas.at<float>(x1, y1));
//m.at<float>(x3, y3) = v;
float theta = Thetas.at<float>(x3, y3) - Thetas.at<float>(x1, y1);
float v = -sin(theta + beta) + R*sin(2.0*theta);
m.at<float>(x3,y3) = v;
}
}
Mat m2;
filter2D(m, m2, -1, LapLapGaussFilter);
ThetasDash.at<float>(x1, y1) = (float)rng.gaussian(sigmaOmega) + K*m2.at<float>(x1, y1) / N;
}
}
// compute Thetas
Thetas += dt * ThetasDash;
cnt++;
double minVal, maxVal;
Point minLoc, maxLoc;
minMaxLoc(Thetas, &minVal, &maxVal, &minLoc, &maxLoc);
printf("cnt = %d\t(min,max)=(%.8f,%.8f)\n", cnt, minVal, maxVal);
if ((cnt % 10) != 0) { return; }
Mat gray_image(w, h, CV_8UC1);
float max = 3.2;
float v;
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
v = map(Thetas.at<float>(x, y), minVal, maxVal, 0, 255);
gray_image.at<unsigned char>(y, x) = (unsigned char)v;
}
}
imwrite("data\\gray" + std::to_string(cnt) + ".jpg", gray_image);
}
/*!
* \brief make_filter. Make filter of fourth derivative of a Gaussian function.
* \param lmin
* \param lmax
* \param sigma
* \param r
* \return
*/
Mat Simulator::make_filter(const int lmin, const float lmax, const float sigma, const float r) {
Mat filter = Mat::zeros(lmax - lmin + 1, lmax - lmin + 1, CV_32F);
for (int x = lmin; x <= lmax; x++) {
for (int y = lmin; y <= lmax; y++) {
float v = laplap_gaussian((float)x, (float)y, sigma, r);
filter.at<float>(x - lmin, y - lmin) = v;
}
}
return filter;
}
/*!
* \brief laplap_gaussian. fourth derivative of a Gaussian function
* \param x
* \param y
* \param sigma
* \param r
* \return
*/
float Simulator::laplap_gaussian(const float x, const float y, const float sigma, const float r) {
float sigma2 = sigma*sigma;
float sigma4 = sigma2*sigma2;
float sigma10 = sigma4*sigma4*sigma2;
float a = 1.0 / (2.0*M_PI*sigma10);
float b = x*x - 4.0*sigma2; b = b*b;
float c = y*y - 4.0*sigma2; c = c*c;
float d = 2.0*x*x*y*y;
float e = -24.0*sigma4;
float f = -(x*x + y*y) / (2.0*sigma2);
return r*a*(b + c + d + e)*exp(f);
}
/*!
* \brief get_r
* \param sigma
* \param R
* \return
*/
float Simulator::get_r(const float sigma, const float R) {
return R*M_PI*pow(sigma, 6.0f) / 4.0;
}
float Simulator::map(const float x, const float xMin, const float xMax, const float yMin, const float yMax) {
return (x - xMin)*(yMax - yMin) / (xMax - xMin) + yMin;
} | 3b405ceb7ee95cd28908bd2a157bc32f59004eaf | [
"Markdown",
"C++"
] | 4 | C++ | Tukamotosan/KuramotoModel | a6d66a5147bb176e17ad064ab9656f96c6d705cd | 4c784c3a45a955c6779758f31b3a87441fa767af |
refs/heads/master | <file_sep><!DOCTYPE <html>
<html>
<head>
<meta charset="utf-8" />
<title>Ejercicio Notas</title>
</head>
<body>
<form method="post">
<div>
<label for="nota">Nota:</label>
<input type="int" name="nota">
</div>
<button type="submit">Enviar</button>
</form>
<?php
if(!empty($_POST["nota"])) {
if($_POST["nota"]>=0 && $_POST["nota"]<5) {
echo "Suspenso :(";
}
elseif($_POST["nota"]>=5 && $_POST["nota"]<6){
echo "Bien, debes de hacerlo mejor :S";
}
elseif($_POST["nota"]>=6 && $_POST["nota"]<8) {
echo "Notable, no esta mal :D";
}
elseif($_POST["nota"]>=8 && $_POST["nota"]<10){
echo "Notable, esta muy bien ! :)";
}
elseif($_POST["nota"]==10){
echo "Sobresaliente <3";
}
echo "</br>";
echo "</br>";
echo "Nota: ".$_POST["nota"];
}
?>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>MONEDAS RANDOM</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<body>
<form method="post">
<br>
<div>
<label for="numero"><b>Número de vueltas:</b></label>
<select name="flip">
<option value="1" selected >1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
</select>
</div>
<br>
<div>
<label for="tipo"><b>Tipo de moneda:</b></label>
<select name="type">
<option value="euro" selected >Euro</option>
<option value="dolar">Dólar</option>
<option value="yen">Yen</option>
<option value="libra">Libra</option>
<option value="franco">Franco Suizo</option>
</select>
</div>
<br>
<input type="submit" value="Lanzar">
<br>
</form>
<?php
$numero = $_POST["flip"];
$tipo = $_POST["type"];
$monedas = array();
for ($i=0; $i<$numero; $i++){
//Debemos de indicar la posicion del array en la que queremos que empiece.
$monedas[$i] = rand (0, 1);
}
for ($x=0; $x<$numero; $x++){
if($monedas[$x] == 0) {
print "<img src=\"other/cara_moneda.jpg\">";
}else{
print "<img src=\"other/cruz_moneda.jpg\">";
}
}
?>
</body>
</html><file_sep><?php
include("function.php");
$listA = inicializar_array(10, 1, 20);
echo "<pre>";
print_r($listA);
echo "</pre>";
?><file_sep><?php
//Create random variable
$aleatorio = rand (0, 1);
//Create if
if ($aleatorio == 0){
echo "<img src=\"other/cara_moneda.jpg\">";
}else{
echo "<img src=\"other/cruz_moneda.jpg\">";
}
?><file_sep># php-learn
*** LEARNING PHP ***
<file_sep><?php
//Declare server array
//Show server IP
echo "IP: ".$_SERVER['SERVER_ADDR']. "</br>";
//Show server name
echo "SEVER NAME: ". $_SERVER['SERVER_NAME']. "</br>";
//Show server software
echo "SERVER SOFTWARE: ". $_SERVER['SERVER_SOFTWARE']. "</br>";
//Show user agent
echo "USER AGENT: ". $_SERVER['SERVER_USER_AGENT']. "</br>";
//Show user ip
echo "USER IP: ". $_SERVER['REMOTE_ADDR']. "</br>";
?><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Formulario con PHP</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<body>
<form method="post">
<div>
<label for="name">Nombre:</label>
<input type="text" name="nombre">
</div>
<div>
<label for="msg">Mensaje:</label>
<textarea name="mensaje"></textarea>
</div>
<div class="button">
<button type="submit">Enviar el mensaje</button>
</div>
</form>
<?php
if (!empty($_POST["nombre"]) && !empty($_POST["mensaje"])){
echo "<br>";
echo "Nombre: ".$_POST["nombre"];
echo "<br>";
echo "Mensaje: ".$_POST["mensaje"];
}
?>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TABLA MULTIPLICAR ALEATORIA</title>
</head>
<body>
<form method="post">
<div>
<label for="numero">Introduce un número:</label>
<input type="text" name="numero">
</div>
<?php
echo "<table border=\"1\">";
//Create random variable
$aleatorio = rand(1, 10);
//Create for
for ($i = 1; $i<=10; $i++){
//Multiply random variable with for
$resultado = $aleatorio * $i;
echo "<tr>";
echo "<td>$aleatorio</td>";
echo "<td> x </td>";
echo "<td>$i</td>";
echo "<td> = </td>";
echo "<td>$resultado</td>";
echo "</tr>";
}
echo "</table>";
?>
</body>
</html><file_sep><?php
$title = "Tabla de multiplicar";
$numero = 8;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title><?php echo $title; ?></title>
</head>
<body>
<?php
//Comentario de una sola línea
/*
Esto es un comentario
de varias líneas
*/
//TABLA DEL 8
echo "<table border=\"1\">";
$num = 8;
for ($i = 1; $i<=10; $i++){
$resultado = $num * $i;
echo "<tr>";
echo "<td>$num</td>";
echo "<td> x </td>";
echo "<td>$i</td>";
echo "<td> = </td>";
echo "<td>$resultado</td>";
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
<file_sep><?php
include('functions.php');
$temperaturas = inicializar_array(10, -10, 40);
$media = calcular_media($temperaturas);
eho "<h2>Media: $media</h2>"
?><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TABLA MULTIPLICAR ALEATORIA</title>
</head>
<body>
<form method="post">
<div>
<label for="numero">Introduce un número:</label>
<input type="text" name="numero">
</div>
<div class="button">
<button type="submit">Calcular</button>
</div>
</form>
<?php
$numero = (int) $_POST["numero" ];
if (!empty($numero) && is_int($numero)){
echo "<table border=\"1\">";
for ($i = 1; $i<=10; $i++){
$numero = (int) $_POST["numero"];
$resultado = $numero * $i;
echo "<tr>";
echo "<td>$numero</td>";
echo "<td> x </td>";
echo "<td>$i</td>";
echo "<td> = </td>";
echo "<td>$resultado</td>";
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html> | b084a4327baef531dd4472b69fb1d5569725da8d | [
"Markdown",
"PHP"
] | 11 | PHP | adrianlopezib/php-learn | 91053f88b09679acac4e4fd82cc1a01ae8b98f8f | bc7b2770f1d9c84f47b9418fd0f91eeb58a34937 |
refs/heads/master | <repo_name>shang97/myrepo<file_sep>/README.md
# myrepo
Line added from Github
<file_sep>/吴恩达老师课程/Course1/L_layers_Logistic.py
import numpy as np
import matplotlib.pyplot as plt
#import h5py
import warnings
warnings.filterwarnings('ignore')
# 多层神经网络的参数初始化
def initialize_parameters(layers_dims):
"""
初始化所有层的参数,包括输入层和隐藏层之间,隐藏层和输出层之间。
参数:
layers_dims - 每层神经元数量的列表,分别为 输入层、隐藏层、输出层
"""
np.random.seed(3)
parameters = {}
# 第一个是输入层的神经元数量,所以计算神经网络的层数时要减一
n_layers = len(layers_dims) - 1
for l in range(1, n_layers+1):
# l 对应 layer_dims 的第 l+1 个元素
parameters["W" + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1]) / np.sqrt(layers_dims[l - 1])
parameters["b" + str(l)] = np.zeros((layers_dims[l], 1))
# 确保数据的格式是正确的
assert(parameters["W" + str(l)].shape == (layers_dims[l], layers_dims[l-1]))
assert(parameters["b" + str(l)].shape == (layers_dims[l], 1))
return parameters
# 不同的激活函数
def sigmoid(Z):
return 1 / (1 + np.exp(-Z))
def relu(Z):
return np.maximum(0, Z)
def tanh():
pass
# 单层网络的前向传播,区分不同层
def forward(A_last, W, b, activation):
"""
根据上一层(l-1)的线性输出A_last 和本层的参数 W,b,计算出本层(l)的线性输出 Z 和激活 A
返回:
cache - 元组,包含 元组linear_cache:(上一层的线性输出 A_last,以及本层的参数 W(不需要保存b),
和 元素 activation_cache(本层的线性输出 Z), 用于反向传播
"""
if activation == "sigmoid":
Z = np.dot(W, A_last) + b
A = sigmoid(Z)
elif activation == "relu":
Z = np.dot(W, A_last) + b
A = relu(Z)
assert(A.shape == (W.shape[0], A_last.shape[1]))
linear_cache = (A_last, W, b)
activation_cache = Z
cache = (linear_cache, activation_cache)
return A, cache
# 多层网络的前向传播
def L_layers_forward(X, parameters):
"""
总共 L(n_layers)层,实现输入层(X)到输出层AL(Yhat)的计算
参数:
parameters - 从W1 到 WL,b1 到 bL(无W0、b0)
返回:
AL - 最后的激活值
caches - 缓存列表,共 L 个cache元组:隐藏层的 L-1 个 cache:(linear_cache, activation_cache),索引从 0 到 L-2
和输出层的一个cache:(linear_cache, activation_cache),索引为 L-1
"""
# 参数包括 W和b对,所以要除以2,如果不整除而采用除法的话,结果是float,而range函数要求的输入必须是int
n_layers = len(parameters) // 2
# 所有隐藏层(1 到 L-1层)的线性输出和 relu激活
A_last = A0 = X
caches = []
for l in range(1, n_layers):
# 根据上一层的激活 A_last 和本层的参数 Wl 和 bl 来计算本层(l)的激活值 A
A, cache = forward(A_last, parameters['W' + str(l)], parameters['b' + str(l)], "relu")
caches.append(cache)
# 本层 A 是计算下一层 A 的 A_last
A_last = A
# 输出层(第L层)的线性输出和 sigmoid激活
AL, cache = forward(A_last, parameters['W' + str(n_layers)], parameters['b' + str(n_layers)], "sigmoid")
caches.append(cache)
assert(AL.shape == (1, X.shape[1]))
return AL, caches
# 计算成本
def compute_cost_2class(AL, Y):
"""
二分类的交叉熵成本函数。
参数:
AL - 与标签预测相对应的概率向量,维度为(1,示例数量)
Y - 标签向量(例如:如果不是猫,则为0,如果是猫则为1),维度为(1,数量)
返回:
cost - 交叉熵成本
"""
m = Y.shape[1]
# 哈达玛积的矩阵顺序不重要(element-wise product); axis默认是None,即对所有的元素进行求和
# print(Y.shape)
cost = - 1/ m * np.sum(np.multiply(np.log(AL), Y) + np.multiply(np.log(1 - AL), 1 - Y) )
# print(cost)
# axis默认对所有元素求和,所以当Y是向量时,可以看作矩阵乘法,但是当Y是矩阵(对应多分类)呢???
# I = np.ones((m, 1))
# cost1 = -1/m * np.dot( (np.log(AL) * Y + np.log(1 - AL) * (1 - Y)), I )
# print(np.squeeze(cost1))
# 确保成本是标量
cost = np.squeeze(cost)
assert(cost.shape == ())
return cost
# 反向传播--线性部分
def linear_backward(dZ, linear_cache):
"""为单层实现反向传播的线性部分(第L层)。基于 dZl 计算和输出 dWl、dbl"""
A_last, W, b = linear_cache
# 批数据量
m = A_last.shape[1]
# 值(向量)都是一样的, 但是互为转置
dW = np.dot(dZ, A_last.T) / m
# dW1 = np.dot(A_prev, dZ.T) / m
# db的结果是一致的,注意要keepdims,不要squeeze
db = np.sum(dZ, axis=1, keepdims=True) / m
# I = np.ones((m, 1))
# db1 = np.dot(dZ, I) / m
# 根据Wl计算dAl-1
dA_last = np.dot(W.T, dZ)
assert (dA_last.shape == A_last.shape)
assert (dW.shape == W.shape)
# 保存b的目的,就是在这里对照一下shape,其他地方完全用不到,但是也是有必要的!!!
assert (db.shape == b.shape)
return dA_last, dW, db
# 激活函数的求导
def relu_backward(dA, activation_cache):
"""dZ 的计算也可以写成 Z和激活函数的导数值(Z中的元素如果大于0,导数值为1,其他为0) 的逐元素运算,"""
Z = activation_cache
dZ = np.array(dA, copy=True)
dZ[Z <= 0] = 0
assert (dZ.shape == Z.shape)
return dZ
def sigmoid_backward(dA, activation_cache):
Z = activation_cache
# 这个除法是逐元素除法
S = 1 / (1 + np.exp(-Z))
dZ = dA * S * (1- S)
assert (dZ.shape == Z.shape)
return dZ
def tanh_backward():
pass
# 单层网络的反向传播,区分不同层
def linear_activation_backward(dA, cache, activation="relu"):
# (A_last,W), Z
linear_cache, activation_cache = cache
# 反向传播到第 l 层神经网络(隐藏层)
if activation == "relu":
# 输入dAl,计算dZl
dZ = relu_backward(dA, activation_cache)
# 计算 𝑑𝐴_𝑙𝑎𝑠𝑡 和 𝑑𝑊𝑙、𝑑𝑏𝑙
dA_last, dW, db = linear_backward(dZ, linear_cache)
# 反向传播到第 L 层神经网络(输出层)
elif activation == "sigmoid":
dZ = sigmoid_backward(dA, activation_cache)
dA_last, dW, db = linear_backward(dZ, linear_cache)
return dA_last, dW, db
# 多层网络的反向传播
def L_layers_backward(AL, Y, caches):
""" 从最后一层(第L层)开始,向前反向传播"""
# 列表caches的每个元素是每层的cache元组
n_layers = L = len(caches)
m = AL.shape[1]
# 逐元素除法,和 / 的结果一致
dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
# dAL1 = - ( Y / AL - (1 - Y) / (1 - AL) )
# 对输出层的反向传播单独计算,传入dAL,计算 dAL-1 和 dWL、dbL
grads = {}
# 列表的 index 需要减 1
current_cache = caches[n_layers - 1]
grads["dA" + str(n_layers - 1)], grads["dW" + str(n_layers)], grads["db" + str(n_layers)] = linear_activation_backward(dAL,
current_cache, "sigmoid")
# 再传播到隐藏层(1 到 L-1层)
for l in reversed(range(1, n_layers)):
# 列表的 index 需要减 1
current_cache = caches[l - 1]
# 反向传播到第 l 层,传入 dAl 和 Wl bl Al-1,计算 dZl dWl dbl 和 dAl-1
dA_last, dW, db = linear_activation_backward(grads["dA" + str(l)], current_cache, "relu")
grads["dA" + str(l - 1)] = dA_last
grads["dW" + str(l)] = dW
grads["db" + str(l)] = db
return grads
# 多层网络的参数更新
def update_parameters(parameters, grads, learning_rate):
"""梯度下降法更新参数"""
n_layers = L = len(parameters) // 2 # 整除,结果是int而非float
# 参数更新:从 1 层 到 L 层(包含隐藏层和输出层)
for l in range(1, n_layers + 1):
parameters["W" + str(l)] = parameters["W" + str(l)] - learning_rate * grads["dW" + str(l)]
parameters["b" + str(l)] = parameters["b" + str(l)] - learning_rate * grads["db" + str(l)]
return parameters
# 多层网络的模型预测
def predict(X, y, parameters):
"""用于预测L层神经网络的结果,当然也包含两层 """
# 批数据量
m = X.shape[1]
p = np.zeros((1, m))
#根据参数前向传播,AL是个向量,每个元素对应某个样本的预测概率
AL, caches = L_layers_forward(X, parameters)
for i in range(0, m):
if AL[0, i] > 0.5:
p[0, i] = 1
else:
p[0, i] = 0
print("准确度为: " + str(float(np.sum((p == y))/m)))
return p
# 多层网络的综合构建
def L_layers_model(X, Y, layers_dims, learning_rate=0.01, num_iterations=3000, print_cost=True, isPlot=True):
"""实现一个L层神经网络"""
np.random.seed(1)
parameters = initialize_parameters(layers_dims)
costs = []
# 多层网络的批量训练
for i in range(num_iterations + 1):
AL, caches = L_layers_forward(X, parameters)
cost = compute_cost_2class(AL, Y)
grads = L_layers_backward(AL, Y, caches)
parameters = update_parameters(parameters, grads, learning_rate)
costs.append(cost)
if i % 500 == 0 and print_cost:
print("第", i ,"次迭代,成本值为:", cost)
# 迭代完成,绘制cost变化图
if isPlot:
plt.figure(figsize=(6,6))
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters<file_sep>/吴恩达老师课程/Course1/dnn_utils.py
import numpy as np
def sigmoid(Z):
"""
Implements the sigmoid activation in numpy
Arguments:
Z -- numpy array of any shape
Returns:
A -- output of sigmoid(z), same shape as Z
cache -- returns Z as well, useful during backpropagation
"""
A = 1 / (1 + np.exp(-Z))
activation_cache = Z
return A, activation_cache
def sigmoid_backward(dA, cache):
"""
Implement the backward propagation for a single SIGMOID unit.
Arguments:
dA -- post-activation gradient, of any shape
cache -- 'Z' where we store for computing backward propagation efficiently
Returns:
dZ -- Gradient of the cost with respect to Z
"""
Z = cache
A = 1 / (1 + np.exp(-Z))
# sigmoid 函数的导数
dA_dZ = A * (1 - A)
# dZ = dJ_dZ = dJ_dA * dA_dZ = dA * dA_dZ
dZ = dA * dA_dZ
assert (dZ.shape == Z.shape)
return dZ
def relu(Z):
"""
Implement the RELU function.
Arguments:
Z -- Output of the linear layer, of any shape
Returns:
A -- Post-activation parameter, of the same shape as Z
cache -- a python dictionary containing "A" ; stored for computing the backward pass efficiently
"""
A = np.maximum(0, Z)
# 方法二(np.where 映射 if 判断,函数作用于每个元素上,而不是整个数组)
#A = np.where(Z>0, Z, 0)
#A = np.where(Z<=0, 0, Z)
# 方法三(np.vectorize 映射 if 判断,函数作用于每个元素上,而不是整个数组)
#func = lambda x: x if x>0 else 0
#func = lambda x: 0 if x<= 0 else x
#func_vector = np.vectorize(func)
#A = func_vector(Z)
# 方法四(逐元素的for 循环中进行判断)
#A = np.array(Z, copy=True)
#for i in range(Z.shape[0]):
#for j in range(Z.shape[1]):
# 大于 0 就保留原来的值,也可以判断 A[i, j],因为取值等于 Z[i, j]
#if Z[i, j] <= 0:
#A[i, j] = 0
assert(A.shape == Z.shape)
activation_cache = Z
return A, activation_cache
def relu_backward(dA, cache):
"""
Implement the backward propagation for a single RELU unit.
Arguments:
dA -- post-activation gradient, of any shape
cache -- 'Z' where we store for computing backward propagation efficiently
Returns:
dZ -- Gradient of the cost with respect to Z
"""
# Z^l A^l=f(Z^l) dZ^l dA^l 的shape都是一样的
Z = cache
# 计算dZ,方法一(相当于把 dA * dA_dZ 融合在一起了)
# 如果直接对 A 操作,而不是复制个 dZ 出来,那么函数运行结束后,dA 会被改变!!!! 但是后面也用不到 dA 了啊????
dZ = np.array(dA, copy=True) # just converting dz to a correct object.
# When z <= 0, you should set dz to 0 as well.
dZ[Z <= 0] = 0
# 计算dZ,方法二(相当于把 if 判断加在数组上,函数作用于每个元素上,而不是整个数组)
# relu 函数的导数
#dA_dZ = np.where(Z<=0, 0, 1)
#dZ = dA * dA_dZ
# 计算dZ,方法三(也相当于把 if 判断加在数组上,函数作用于每个元素上,而不是整个数组)
#func = lambda x: 0 if x<= 0 else 1
#func_vector = np.vectorize(func)
#dA_dZ = func_vector(Z)
#dZ = dA * dA_dZ
# 计算dZ,方法四(逐元素的for 循环中进行判断)
#dZ = np.array(dA, copy=True)
#for i in range(dZ.shape[0]):
#for j in range(dZ.shape[1]):
# Z 中取值大于 0 的话,dZ 中相应位置保留原值
#if Z[i, j] <= 0:
#dZ[i, j] = 0
assert (dZ.shape == Z.shape)
return dZ
def tanh(Z):
"""
Implements the tanh activation in numpy
Arguments:
Z -- numpy array of any shape
Returns:
A -- output of tanh(z), same shape as Z
cache -- returns Z as well, useful during backpropagation
"""
A = (np.exp(Z) - np.exp(-Z)) / (np.exp(Z) + np.exp(-Z))
activation_cache = Z
return A, activation_cache
def tanh_backward(dA, cache):
"""
Implement the backward propagation for a single TANH unit.
Arguments:
dA -- post-activation gradient, of any shape
cache -- 'Z' where we store for computing backward propagation efficiently
Returns:
dZ -- Gradient of the cost with respect to Z
"""
Z = cache
A = 1 / (1 + np.exp(-Z))
# tanh 函数的导数
#dA_dZ = 1 - np.power(A, 2)
dA_dZ = 1 - A**2
dZ = dA * dA_dZ
assert (dZ.shape == Z.shape)
return dZ
def leaky_relu(Z):
"""
Implement the leaky relu function.
Arguments:
Z -- Output of the linear layer, of any shape
Returns:
A -- Post-activation parameter, of the same shape as Z
cache -- a python dictionary containing "A" ; stored for computing the backward pass efficiently
"""
# 方法一
np.maximum(0.01*Z, Z)
# 方法二(np.where 映射 if 判断,函数作用于每个元素上,而不是整个数组)
A = np.where(Z<=0, 0.01*Z, Z)
#A = np.where(Z>0, Z, 0.01*Z)
# 方法三(np.vectorize 映射 if 判断,函数作用于每个元素上,而不是整个数组)
#func = lambda x: 0.01*x if x <= 0 else x
#func_vector = np.vectorize(func)
#A = func_vector(Z)
assert(A.shape == Z.shape)
activation_cache = Z
return A, activation_cache
def leaky_relu_backward(dA, cache):
"""
Implement the backward propagation for a single Leaky ReLU unit.
Arguments:
dA -- post-activation gradient, of any shape
cache -- 'Z' where we store for computing backward propagation efficiently
Returns:
dZ -- Gradient of the cost with respect to Z
"""
# Z^l A^l=f(Z^l) dZ^l dA^l 的shape都是一样的
Z = cache
# 会报错的方法,赋的值是二维的
#dZ = np.array(dA, copy=True)
#dZ[Z <= 0] = 0.01 * dZ
# 计算dZ,方法一(相当于把 if 判断加在数组上)
# relu 函数的导数
dA_dZ = np.where(Z<=0, 0.01, 1)
dA_dZ = np.where(Z>0, 1, 0.01)
dZ = dA * dA_dZ
# 计算dZ,方法二(也相当于把 if 判断加在数组上)
#func = lambda x: 0.01 if x<=0 else 1
#func = lambda x: 1 if x>0 else 0.01
#func_vector = np.vectorize(func)
#dA_dZ = function_vector(Z)
#dZ = dA * dA_dZ
assert (dZ.shape == Z.shape)
return dZ | 8954b7b205d758d4c66d18688baea8bc18b88e68 | [
"Markdown",
"Python"
] | 3 | Markdown | shang97/myrepo | a04c5123f312070ccb2c2d3f1eb297fd2309b4d4 | 5cd4d156d258aea439d017f1413a1eff970d78cc |
refs/heads/master | <repo_name>fennovj/cad-doge<file_sep>/preprocessing/opticDiscVesselDetection.py
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 15:14:26 2015
@author: Bram
"""
import math
import skimage.io as skio
import cv2
from skimage.morphology import erosion, dilation, opening, closing, white_tophat
from skimage.morphology import black_tophat, skeletonize, convex_hull_image
from skimage.morphology import disk, octagon, reconstruction, watershed, square
from skimage.filters import rank, threshold_otsu
from skimage import exposure, segmentation, color
from matplotlib import pyplot as plt
from scipy import ndimage
import numpy as np
import colorsys as color
def threshold(image, threshold = 0.5):
image[image < threshold] = 0
return image
def convertToHLS(image):
rows, cols, channel = image.shape
hlsimage = np.zeros((rows, cols, channel), dtype = float)
image = image.astype(np.float)
image = image/255.0
for i in range(rows):
for j in range(cols):
hlsimage[i,j,:] = np.array(color.rgb_to_hls(*image[i,j,:]), dtype=float)
return hlsimage
def convertToRGB(image):
rows, cols, channel = image.shape
rgbimage = np.zeros((rows, cols, channel), dtype = float)
for i in range(rows):
for j in range(cols):
rgbimage[i,j,:] = np.array(color.hls_to_rgb(*image[i,j,:]), dtype=float)
rgbimage = rgbimage*255.0
return rgbimage.astype(np.uint8)
def drawCircle(rows, cols, x, y, radius):
im = np.zeros((rows, cols), dtype = np.int32)
c = 4
R = radius**2
xp = 0
yp = radius
while (xp<yp):
x1 = x+xp
x2 = x-xp
x3 = y+xp
x4 = y-xp
y1 = y+yp
y2 = y-yp
y3 = x+yp
y4 = x-yp
im[x1-c:x1+c, y2-c:y2+c] = 1
im[x1-c:x1+c, y1-c:y1+c] = 1
im[x2-c:x2+c, y2-c:y2+c] = 1
im[x2-c:x2+c, y1-c:y1+c] = 1
im[y3-c:y3+c, x4-c:x4+c] = 1
im[y3-c:y3+c, x3-c:x3+c] = 1
im[y4-c:y4+c, x4-c:x4+c] = 1
im[y4-c:y4+c, x3-c:x3+c] = 1
xp = xp + 1
yp = math.sqrt(R-xp**2)
im[x,y]=1
return im
def computeCentroid(image):
rows, cols = image.shape
nrow = 0
ncol = 0
counter = 0
for i in range(rows):
for j in range(cols):
if(image[i,j]>0):
nrow = nrow + i
ncol = ncol + j
counter = counter + 1
return nrow/counter, ncol/counter
def detectOpticDisc(image):
kernel = octagon(10, 10)
thresh = threshold_otsu(image[:,:,1])
binary = image > thresh
print binary.dtype
luminance = convertToHLS(image)[:,:,2]
t = threshold_otsu(luminance)
t = erosion(luminance, kernel)
labels = segmentation.slic(image[:,:,1], n_segments = 3)
out = color.label2rgb(labels, image[:,:,1], kind='avg')
skio.imshow(out)
x, y = computeCentroid(t)
print x, y
rows, cols, _ = image.shape
p1 = closing(image[:,:,1],kernel)
p2 = opening(p1, kernel)
p3 = reconstruction(p2, p1, 'dilation')
p3 = p3.astype(np.uint8)
#g = dilation(p3, kernel)-erosion(p3, kernel)
#g = rank.gradient(p3, disk(5))
g = cv2.morphologyEx(p3, cv2.MORPH_GRADIENT, kernel)
#markers = rank.gradient(p3, disk(5)) < 10
markers = drawCircle(rows, cols, x, y, 85)
#markers = ndimage.label(markers)[0]
#skio.imshow(markers)
g = g.astype(np.uint8)
#g = cv2.cvtColor(g, cv2.COLOR_GRAY2RGB)
w = watershed(g, markers)
print np.max(w), np.min(w)
w = w.astype(np.uint8)
#skio.imshow(w)
return w
def detectVessels(image):
kernel = square(2)
image = ndimage.gaussian_filter(image[:,:,2], 2)
image = opening(image, kernel)
return image
if __name__ == "__main__":
imagepath = "C:\\Users\\<NAME>\\Documents\\reduced"
#samplepath = "D:\\Documents\\Dropbox\\CAD\\sample\\"
#imagepath = "D:\\Downloads\\trainingdata\\train"
#outfolder = "D:\\Downloads\\trainingdata\\reduced"
testpic = "C:\\Users\\<NAME>\\Documents\\reduced\\16_left.jpeg"
testoutput = "C:\\Users\\<NAME>\\Dropbox\\CAD\\Project\\Detectionexamples"
image = skio.imread(testpic, False)
#t = threshold(luminance, 0.75)
op = detectOpticDisc(image)
print np.max(op), np.min(op)
#skio.imshow(op)
#skio.imshow(drawCircle(512, 512, 250, 150, 30))
#skio.imshow(t)<file_sep>/utils/score.py
"""
Functions for assessing the performance of different classifiers.
"""
import numpy as np
def pad_to_length(array, length, value = 0):
addedzeros = length - np.size(array)
return np.pad(array,(0,addedzeros), 'constant', constant_values = value)
def calc_weighted_kappa(predictions, true_classes):
"""
The accuracy of the predictions (how many of the predictions were correct).
inputs must be arrays/lists, consisting of integers (either signed or unsigned)
inputs must be one-dimensional arrays, with the same length
predictions must be integers.
:return: The quadratic weighted kappa score
"""
if not isinstance(predictions, np.ndarray):
predictions = np.array(predictions)
if not isinstance(true_classes, np.ndarray):
true_classes = np.array(true_classes)
assert np.size(np.shape(predictions)) == 1 and np.size(np.shape(true_classes)) == 1
assert np.size(predictions) == np.size(true_classes)
assert predictions.dtype.kind in 'ui' and true_classes.dtype.kind in 'ui'
N = np.amax(np.concatenate((predictions, true_classes))) + 1 #number of classes, starting from 0
O = np.zeros((N,N),dtype='float')
for i in range(np.size(predictions)):
O[predictions[i], true_classes[i]] += 1.0
W = np.array([[((i - j)**2.0)/((N - 1)**2.0) for j in range(0, N)]for i in range(0, N)])
predbin = pad_to_length(np.bincount(predictions), N)
truebin = pad_to_length(np.bincount(true_classes), N)
E = np.outer(predbin, truebin)
E = E * (np.sum(O) / np.sum(E))
return 1.0 - (np.sum(W * O) / np.sum(W * E))
def calc_accuracy(predictions, true_classes):
"""
The accuracy of the predictions (how many of the predictions were correct).
Predictions: the predicted classes
true_classes: the true classes
:return: The accuracy as a fraction [0-1].
"""
assert np.size(np.shape(predictions)) == 1 and np.size(np.shape(true_classes)) == 1
assert np.size(predictions) == np.size(true_classes)
N = float(np.size(predictions))
return 1.0 - (np.count_nonzero(predictions-true_classes) / N)
if __name__ == '__main__':
x = np.array([1,2,3,0])
y = np.array([1,2,3,4])
N = np.amax(np.concatenate((x,y))) + 1
print "N = " + str(N)
print calc_weighted_kappa( [1,1,2,3,2,1,0,0,1,2,3,4,4,3,2,1,0],[1,4,4,2,1,2,3,4,1,0,0,2,0,1,2,3,0])<file_sep>/learning/componentfeatures.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 25 14:46:22 2015
@author: Fenno
"""
import numpy as np
from skimage.measure import perimeter as perim
from math import pi
area = lambda picture, label: np.sum(picture == label)
perimeter = lambda picture, label: perim(picture == label, 8)
def aspectratio(picture, label):
widtho = np.max(picture == label, 0)
heighto = np.max(picture == label, 1)
minw = np.argmax(widtho)
minh = np.argmax(heighto)
maxw = len(widtho) - np.argmax(widtho[::-1]) - 1
maxh = len(heighto) - np.argmax(heighto[::-1]) - 1
return (maxh - minh) / (1.0 * (maxw - minw))
circularity = lambda picture, label: perimeter(picture, label) / (4.0 * pi * area(picture, label))
totalgreen = lambda picture, label, green: np.sum(green[picture==label])
#can also be used for shadecorrected
meangreen = lambda picture, label, green: np.mean(green[picture==label])
#can also be used for shadecorrected image
normalizedintensity = lambda picture, label, green, bg : np.mean(green - np.mean(bg)) / np.std(bg)
#can also be used for shadecorrected
normmeanintensity = lambda picture, label, green, bg : (np.mean(green) - np.mean(bg)) / np.std(bg)
#can also be used for shadecorrected
#centroid and edgedist are not actual features
centroid = lambda picture, label : np.mean(np.where(picture==label),axis=1)
def edgedist(pixel, shape=(512,512)):
x = pixel[0]
y= pixel[1]
circumference = 2.0*shape[0] + 2.0*shape[1]
totaldist = np.sum([np.hypot(x-a, y-b) for a in range(shape[0]) for b in [0,shape[1]]])
totaldist2 = np.sum([np.hypot(x-a, y-b) for a in [0,shape[0]] for b in range(shape[1])])
return (totaldist + totaldist2) / circumference, circumference
def compactness(picture, label):
c = centroid(picture, label)
db, circum = edgedist(c, np.shape(picture))
pixels = np.array(np.where(picture==label)).T
area = np.shape(pixels)[0]
totaldist = np.sum([np.hypot(*(pixels[i,:]-c)) for i in range(area)])
return np.sqrt((totaldist - db) / float(circum))
def getDiameter(pixel, shape=(512,512)):
return np.min([pixel[0], pixel[1], shape[0] - pixel[0], shape[1]-pixel[1]])
<file_sep>/README.md
# cad-doge
The repository of Team Doge for the Computer Aided Diagnosis course
Added initial files<file_sep>/preprocessing/preprocessingForFeatures.py
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 15:14:26 2015
@author: Bram
"""
import skimage.io as skio
import numpy as np
import cv2
from opticdiscdetection import detectOpticDisc
from scipy.ndimage.filters import median_filter
"""
This class preprocesses the original image for feature extraction
"""
class Images(object):
def __init__(self, image):
self.image = detectOpticDisc(image)
self.green_plane = image[:,:,1]
self.background_image = median_filter(self.green_plane, size=17)
self.shade_corrected_image = self.green_plane.astype(np.int) - self.background_image.astype(np.int)
self.pp = np.copy(self.shade_corrected_image)
self.pp[self.pp > 0] = 0
image_hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
intensity = np.mean(image, axis=2)
intensity = median_filter(intensity, size=5)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
intensity = intensity.astype(np.uint16)
intensity = clahe.apply(intensity)
intensity = intensity.astype(np.float)/float(255)
r,c = intensity.shape
self.hsi_image = np.concatenate((image_hsv[:,:,0:2], intensity.reshape(r,c,1)), axis=2)
if __name__ == "__main__":
imagepath = "C:\\Users\\<NAME>\\Documents\\reduced"
testpic = "C:\\Users\\<NAME>\\Documents\\reduced\\16_left.jpeg"
testoutput = "C:\\Users\\<NAME>\\Dropbox\\CAD\\Project\\Detectionexamples"
image = skio.imread(testpic, False)
x = Images(image)
skio.imshow(x.hsi_image[:,:,2])<file_sep>/learning/readTraining.py
__author__ = 'Fenno'
import os
import skimage.io as skio
from sklearn.ensemble import RandomForestClassifier
import numpy as np
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
BASEFOLDER = 'D:\\Documents\\Data\\DMED'
IMGFOLDER = 'DMED-P'
LABELFOLDER = 'DMED-P'
NAMEFOLDER = 'DMED-GT'
TESTFOLDER = 'Reduced'
#assumes preprocessed images are in DMED-P
def getTrainingImage(name, words = ['Exudate'], basefolder = BASEFOLDER, imgfolder = IMGFOLDER, labelfolder = LABELFOLDER, namefolder = NAMEFOLDER):
imagepath = os.path.join(basefolder, imgfolder, name + '.jpg')
labelspath = os.path.join(basefolder, labelfolder, name+ '.tif')
namespath = os.path.join(basefolder, namefolder, name + '.txt')
image = skio.imread(imagepath)
labels = skio.imread(labelspath)
with open(namespath) as f:
for line in f:
num = int(line.split(':')[0])
if not any(x in line for x in words):
labels[labels == num] = 0
return image, labels
def randomForest(train,
labels,
test,
sample_weight=None,
n_estimators=100,
n_jobs=1,
verbose=0):
"""
Trains a model by giving it a feature matrix, as well as the labels (the ground truth)
then using that model, predicts the given test samples
output is 9 probabilities, one for each class
:param train: The training data, to train the model
:param labels: The labels of the training data, an array
"""
n,f = np.shape(test)
assert n % (512*512) == 0
numimg = int(n / (512*512))
print "Now defining model... ", numimg, n, f
model = RandomForestClassifier(n_estimators=n_estimators,
n_jobs=n_jobs,
verbose=verbose)
print "Now training model..."
model.fit(train, labels)
import pickle
pickle.dump(model, open("model.m", 'wb'))
print "Now predicting samples..."
predictions = model.predict_proba(test)[:,1]
return predictions.reshape((512,512,numimg))
def readSingleTraining(name, path = os.path.join(BASEFOLDER, IMGFOLDER)):
picture = skio.imread(os.path.join(path, name) + '.jpg')
labels = skio.imread(os.path.join(path, name) + '.tif')
return picture, labels
#Assumed pre-processed images are in DMED-P
#Assumes there are only .jpg and .tif files in that directory, and no other files
def readAllTraining(path = os.path.join(BASEFOLDER, IMGFOLDER)):
numimage = len(os.listdir(path)) / 2
result = np.zeros((512, 512, 3, numimage))
resultlabels = np.zeros((512, 512, numimage))
for i, filename in enumerate(os.listdir(path)):
if filename.split('.')[-1] == 'tif':
continue
f = os.path.basename(filename).split('.')[0]
result[:,:,:,i/2], resultlabels[:,:,i/2] = readSingleTraining(f, path)
return result, resultlabels
def readSingleTesting(name, path):
picture = skio.imread(os.path.join(path, name) + '.jpeg')
return picture
def readAllTesting(path= os.path.join(BASEFOLDER, TESTFOLDER), num=100):
numimage = len(os.listdir(path))
result = np.zeros((512, 512, 3, num))
for i, filename in enumerate(os.listdir(path)):
if i == num:
break
f = os.path.basename(filename).split('.')[0]
result[:,:,:,i] = readSingleTesting(f, path)
return result
from whitelesionfeatures import getWhiteLesionFeatures as FEATUREEXTRACTOR
def getFeatureMatrix(imagematrix, labelmatrix = None, featureExtractor = FEATUREEXTRACTOR ):
x,y,d,n = np.shape(imagematrix)
assert x == 512 and y == 512 and d == 3
print "n = ", n
if labelmatrix is not None:
x2, y2, n2 = np.shape(labelmatrix)
assert x2 == 512 and y2 == 512 and n == n2
labelmatrix = np.copy(labelmatrix)
labelmatrix[labelmatrix > 0] = 1
for i in range(n):
print "Now at image " + str(i)
features = featureExtractor(imagematrix[:,:,:,i])
_, f = np.shape(features)
if i == 0:
resultfeatures = np.empty((0,f))
resultfeatures = np.vstack((resultfeatures, features))
if labelmatrix is not None:
if i == 0:
resultlabels = np.empty(0)
resultlabels = np.concatenate((resultlabels, np.ravel(labelmatrix[:,:,i])))
if labelmatrix is not None:
return resultfeatures, resultlabels
return resultfeatures
def filterData():
train = np.load('train.npy')
labels = np.load('labels.npy')
#test = np.load('test.npy')
n, f = np.shape(train)
result = np.ones((n), dtype=bool)
print np.sum(result)
for i in range(n):
#print train[i,:]
if max(train[i,:]) < 0.05 and min(train[i,:]) > -0.05:
result[i] = False
print np.sum(result)
print np.shape(train[result,:])
np.save('trainfilter.npy', train[result,:])
np.save('labelfilter.npy', labels[result])
if __name__ == '__main__':
import sys
imagematrix, labelmatrix = readAllTraining()
imagematrix = readAllTesting()
imagematrix = imagematrix.astype('uint8')
resultfeatures = getFeatureMatrix(imagematrix)
np.save("resultfeaturestest", resultfeatures)
train = np.load('trainfilter.npy')
labels = np.load('labelfilter.npy')
test = np.load('test.npy')
test = np.nan_to_num(test)
test = np.zeros((512*512, 1))
np.save('resultlabels2.npy', labels.astype('float32'))
np.save('resultfeaturestest2.npy', test.astype('float32'))
predictions = randomForest(train, labels, test, n_estimators=100, n_jobs=2, verbose=100)
import pickle
model = pickle.load(open('model.m', 'rb'))
n,f = np.shape(test)
assert n % (512*512) == 0
numimg = int(n / (512*512))
predictions = model.predict_proba(test)[:,1]
x = predictions.reshape((512,512,numimg))
np.save("predictions", predictions)
x = np.load('predictions.npy')
x = x.reshape(512,512,100)
print np.shape(x)
i = 68
print i
skio.imshow(x[:,:,i])<file_sep>/preprocessing/opticdiscdetection.py
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 15:14:26 2015
@author: Bram
"""
import skimage.io as skio
import cv2
from skimage import segmentation, color
import numpy as np
"""
Detect optic disc and makes it white, so you don't get confused with the
black background, needs the original rgb image
"""
def detectOpticDisc(image):
labels = segmentation.slic(image, n_segments = 70)
out = color.label2rgb(labels, image, kind='avg')
gray = cv2.cvtColor(out, cv2.COLOR_RGB2GRAY)
minimum = np.max(gray)
image[gray==minimum] = 255
return image
if __name__ == "__main__":
imagepath = "C:\\Users\\<NAME>\\Documents\\reduced"
#samplepath = "D:\\Documents\\Dropbox\\CAD\\sample\\"
#imagepath = "D:\\Downloads\\trainingdata\\train"
#outfolder = "D:\\Downloads\\trainingdata\\reduced"
testpic = "C:\\Users\\<NAME>\\Documents\\reduced\\13_left.jpeg"
testoutput = "C:\\Users\\<NAME>\\Dropbox\\CAD\\Project\\Detectionexamples"
image = skio.imread(testpic, False)
op = detectOpticDisc(image)
skio.imshow(op)<file_sep>/learning/secondLevel.py
__author__ = 'Fenno'
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
import numpy as np
#basic features: sum, mean, min, max, std
#connected components: max, biggest one
def bins(image):
return np.bincount(image.flatten())[1:]
features = [np.max, np.mean, np.min, np.std, np.median ]
#connected components: ammount, biggest one, average size, average for substantial (> 10 pixels) components
componentfeatures = [np.max,
lambda x : np.max(bins(x)),
lambda x: np.mean(bins(x)),
lambda x: np.mean(bins(x)[bins(x) > 10])]
#Input: a 512x512xn matrix of predictions for either red or white lesion
#output: an nxf matrix of features
def getFeatures(imagematrix):
_,_, n = np.shape(imagematrix)
f = np.shape(features)
result = np.zeros((n,f))
for i in range(n):
result[n,:] = [feature(imagematrix[:,:,n]) for feature in features]
return result
def randomForestSecond(train,
labels,
test,
prior_weight = None,
n_estimators=100,
n_jobs=1,
verbose=0):
"""
:param train: The features of training data, obtained with getFeatures
:param labels: The kaggle labels of the training data
:param test: The faetures of testing data
:param prior_weight: the normalized weights to which output will be rescaled
by default: no rescaling. If 'auto', use ratio from kaggle training data
:param n_estimators:
:param n_jobs:
:param verbose:
:return:
"""
if prior_weight == 'auto':
prior_weight = [25810/35126.0, 2443/35126.0, 5292/35126.0, 873/35126.0, 708/35126.0]
assert np.sum(prior_weight) < (1.0 + 1e-4) and np.sum(prior_weight) > (1.0 - 1e-4)
model = RandomForestRegressor(n_estimators=n_estimators,
n_jobs=n_jobs,
verbose=verbose)
print "Now training model..."
model.fit(train, labels)
print "Now predicting samples..."
predictions = model.predict_proba(test)
if prior_weight is not None:
sortedpred = np.sort(predictions)
indexratio = np.cumsum(prior_weight)
n = len(sortedpred)
indexes = [int(i * n) for i in indexratio[:-1]]
thresholds = [sortedpred[i] for i in indexes] + [sortedpred[-1]]
predictions = np.digitize(predictions, thresholds, right=True)
return predictions<file_sep>/utils/regiongrow.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 25 13:14:14 2015
@author: Fenno
"""
import numpy as np
class Queue:
def __init__(self):
self.items = []
self.all = []
def isEmpty(self):
return self.items==[]
def enque(self,item):
self.items.insert(0,item)
self.all.insert(0,item)
def deque(self):
return self.items.pop()
def qsize(self):
return len(self.items)
def isInside(self, item):
return (item in self.all)
fourneighbors = [lambda (x,y): (x+1, y),
lambda (x,y): (x-1, y),
lambda (x,y): (x, y+1),
lambda (x,y): (x, y-1)]
def regionGrowing(pic, seed, threshold, compare_original = True, neighbors = 4):
"""Given IxJ image and list of seed coordinates and list of thresholds,
region grows all of them
returns an image that is 1 at the grown regions, and 0 everywhere else
"""
assert neighbors == 4, "Only 4 neighbors implemented right now"
neighbors = fourneighbors #note: can add 8 neighbors later
I, J = np.shape(pic)
sx = seed[0]
sy = seed[1]
Q = Queue()
Q.enque((sx,sy))
while not Q.isEmpty():
t = Q.deque()
x = t[0]
y = t[1]
for neigh in neighbors:
nx, ny = neigh((x,y))
if not compare_original: sx, sy = x, y #compare to current pixel or original pixel
if (0 <= nx < I) and (0 <= ny < J) and \
abs(pic[nx, ny] - pic[sx, sy]) <= threshold and \
not Q.isInside((nx, ny)):
Q.enque((nx, ny))
result = np.zeros((I,J))
for (i, j) in Q.all:
result[i,j] = 1
return result
if __name__ == "__main__":
fname = "D:\\Documents\\Data\\Cad Project\\reduced\\100_left.jpeg"
import time
import skimage.io as skio
from skimage.viewer import ImageViewer
#path = "D:\\Documents\\Data\\Cad Project\\reduced\\10003_left.jpeg"
path = "C:\\Users\\<NAME>\\Documents\\reduced\\16_left.jpeg"
#path = "D:\\Documents\\Data\\Cad Project\\reduced\\rgb.bmp"
image = skio.imread(path)
result1 = regionGrowing(image[:,:,1], (0,0), 10, False)
result2 = regionGrowing(image[:,:,1], (0,511), 10, False)
result3 = regionGrowing(image[:,:,1], (511,0), 10, False)
result4 = regionGrowing(image[:,:,1], (511,511), 10, False)
result5 = np.logical_or(np.logical_or(result1, result2), np.logical_or(result3, result4))
ImageViewer(result5).show()
<file_sep>/learning/whitelesionfeatures.py
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 27 15:14:26 2015
@author: Bram
"""
import sys
import numpy as np
from skimage import io as skio, color
from scipy.signal import convolve2d
from scipy.ndimage.filters import gaussian_filter
from scipy.stats.mstats import zscore
from skimage.filters import sobel
from sklearn.feature_extraction.image import grid_to_graph
from sklearn.cluster import AgglomerativeClustering
import cv2
sys.path.append("C:\Users\<NAME>\Dropbox\CAD\Project\cad-doge\preprocessing")
from preprocessing.preprocessingForFeatures import Images
#from opticdiscdetection import detectOpticDisc
"""
Areas of clusters (number of pixels)
"""
def getAreas(labels):
labeling = np.unique(labels)
for label in labeling:
labels[labels==label*np.ones(labels.shape)] = np.sum(labels==label*np.ones(labels.shape))
return labels
"""
Get features corresponding to agglomerative clustering
"""
def agglomerativeClusteringFeatures(image):
connectivity = grid_to_graph(*image[:,:,2].shape)
X = np.reshape(image[:,:,2], (-1,1))
ward = AgglomerativeClustering(n_clusters=150,
linkage = 'ward', connectivity = connectivity).fit(X)
labels = np.reshape(ward.labels_, image[:,:,2].shape)
averageIntensity = color.label2rgb(labels, image[:,:,2], kind = 'avg')
#areas = getAreas(labels)
return averageIntensity
"""
Compute ratio between optic disc and area of clusters
"""
def computeRatio(op, areas):
r = op[:,:,0]==255*np.ones(op[:,:,0].shape)
g = op[:,:,1]==255*np.ones(op[:,:,1].shape)
b = op[:,:,2]==255*np.ones(op[:,:,2].shape)
boolean = np.logical_and(np.logical_and(r, g), b)
sizeOp = np.sum(boolean)
return areas/sizeOp
"""
Get features corresponding to the optic disc, needs the size of the
clusters as well
"""
def opticDiscFeatures(rgbimage, areas):
ratios = computeRatio(rgbimage, areas)
return ratios
"""
Count the number of edge pixels in a 17 by 17 window
"""
def nrOfEdgePixels(rgbimage, intensityImage):
redEdges = sobel(rgbimage[:,:,0])
grayEdges = sobel(intensityImage)
t = redEdges - grayEdges
t[t < 0.05] = 0
t[t >= 0.05] = 1
return convolve2d(t, np.ones((17,17)), mode="same")
"""
The standard deviation of the preprocessed intensity
values in a window around the pixel
"""
def stdConvoluted(image, N):
im = np.array(image, dtype=float)
im2 = im**2
ones = np.ones(im.shape)
kernel = np.ones((2*N+1, 2*N+1))
s = convolve2d(im, kernel, mode="same")
s2 = convolve2d(im2, kernel, mode="same")
ns = convolve2d(ones, kernel, mode="same")
return np.sqrt((s2 - s**2 / ns) / ns)
def getDoG(image, sigma1, sigma2):
f1 = gaussian_filter(image, sigma1)
f2 = gaussian_filter(image, sigma2)
return f2-f1
"""
Get all the features for white lesion detection
"""
def getWhiteLesionFeatures(image):
s = 512
r = image[:,:,0]==np.zeros(image[:,:,0].shape)
g = image[:,:,1]==np.zeros(image[:,:,1].shape)
b = image[:,:,2]==np.zeros(image[:,:,2].shape)
mask = np.logical_and(np.logical_and(r, g), b)
mask = mask.reshape((s*s, 1))
ppimages = Images(image)
areas = agglomerativeClusteringFeatures(ppimages.hsi_image)
intensity = ppimages.hsi_image[:, :, 2].reshape((s*s, 1))
intensity[intensity==mask] = 0
std = stdConvoluted(ppimages.hsi_image[:,:,2], 7).reshape((s*s, 1))
std[std==mask] = 0
hue = ppimages.hsi_image[:, :, 0].reshape((s*s, 1))
hue[hue==mask] = 0
ratio = opticDiscFeatures(ppimages.image, areas).reshape((s*s, 1))
ratio[ratio==mask] = 0
edges = nrOfEdgePixels(ppimages.image, ppimages.hsi_image[:, :, 2]).reshape((s*s, 1))
edges[edges==mask] = 0
DoG4 = getDoG(ppimages.hsi_image[:,:,2], 4, 8).reshape((s*s, 1))
DoG4[DoG4==mask] = 0
features = np.concatenate((intensity,
std,
hue,
ratio,
edges,
DoG4), axis=1)
return features
if __name__ == "__main__":
testpic = "C:\\Users\\<NAME>\\Documents\\reduced\\16_left.jpeg"
image = skio.imread(testpic, False)
features = getWhiteLesionFeatures(image)
print np.min(features), np.max(features)
print features.shape
#skio.imshow(test.astype(np.uint8))
#out = getWhiteLesionFeatures(image)
<file_sep>/utils/crossvalidate.py
"""
This class lets you do cross validation as simply as possible (or as simple as I could come up with).
See discussion on issue https://gitlab.science.ru.nl/maverickZ/kaggle-otto/issues/6
"""
from random import Random
from sys import stdout
from time import time
from numpy import array, setdiff1d
from subprocess import check_output
from score import calc_weighted_kappa, calc_accuracy
class SampleCrossValidator():
"""
Facilitates cross validation by providing series of train and test data on which to run your own code. The results can be returned to this class to get performance metrics. Brief example in demo/test_crossvalidate.py .
"""
def __init__(self, data, true_classes, test_frac = 0.3, use_data_frac = None, show = True, seed = 4242):
"""
Construct a validator instance, binding data and parameters.
:param data: Array with all the training data (no need to shuffle) with sample rows and feature columns.
:param true_classes: Array with the true class label integers.
:param test_frac: Optionally, the fraction of the used data to assign for testing (the rest being training).
:param use_data_frac: Optionally, the fraction of the total data to include in test and training.
:param show: Whether to print output each time a probability is added; defaults to True.
:param seed: A fixed seed for sampling, so that the same data yields the same results consistently. Should probably not be changed.
"""
assert data.shape[0] == true_classes.shape[0], 'There should be a true class for each sample ({0:d} vs {1:d}).'.format(data.shape[1], true_classes.shape[0])
assert 0 < test_frac < 1
assert 0 < use_data_frac < 1 + 1e-6
self.data = data
self.true_classes = true_classes
self.test_frac = test_frac
self.use_data_frac = use_data_frac
self.show = bool(show)
self.random = Random(seed)
self.samples = []
self.results = []
self.yield_time = None
self.total_data_count = self.data.shape[0]
self.use_data_count = int(self.total_data_count * use_data_frac) if use_data_frac else self.total_data_count
self.test_count = int(test_frac * self.use_data_count)
def get_cross_validation_set(self):
"""
Get one pair of shuffled train and test data. Intended for internal use.
:return: train_data, train_classes, test_data, test_classes
"""
""" Get the indices of the data being used (sampled randomly). """
if self.use_data_frac:
use_indices = array(self.random.sample(range(self.total_data_count), self.use_data_count))
else:
use_indices = array(range(self.total_data_count))
""" Get the indices of the testing data randomly (subset of the data being used). """
test_indices = array(self.random.sample(use_indices, self.test_count))
""" The set difference is a series of n 'in' operations, which are O(1) hashmap lookups. So it scales well. """
train_indices = setdiff1d(use_indices, test_indices)
self.random.shuffle(train_indices)
""" Return the information for predicting the test data. """
return self.data[train_indices, :], self.true_classes[train_indices], self.data[test_indices, :], self.true_classes[test_indices]
def yield_cross_validation_sets(self, rounds = 3):
"""
Yields each of the sets of cross validation data.
:param rounds: How many rounds of cross validation to perform.
:return: An iterator with (train_data, train_classes, test_data) tuple on each iteration.
"""
assert len(self.samples) == 0, 'This {0:s} already has samples; create a new one if you want to cross-validate again.'.format(self.__class__.__name__)
for round in range(rounds):
""" Store the test indices for validation later (I hope train won't be needed). """
train_data, train_classes, test_data, test_classes = self.get_cross_validation_set()
self.samples.append(test_classes)
self.yield_time = time()
yield train_data, train_classes, test_data
def add_prediction(self, prediction):
"""
Register a classification result for scoring.
:param prediction: SxC array with predicted probabilities, with each row corresponding to a test data sample and each column corresponding to a class.
:return: (logloss, accuracy) tuple of floats
"""
duration = time() - self.yield_time
#assert prediction.shape[1] == NCLASSES, 'There should be a probability for each class.'
assert len(self.results) < len(self.samples), 'There is already a prediction for each sample generated.'
test_classes = self.samples[len(self.results)]
kappa = calc_weighted_kappa(prediction, test_classes)
accuracy = calc_accuracy(prediction, test_classes)
if self.show and not len(self.results):
stdout.write(' # kappa accuracy time\n')
self.results.append((kappa, accuracy, duration,))
if self.show:
stdout.write('{0:-3d} {1:6.3f} {2:5.2f}% {3:6.3f}s\n'.format(len(self.results), kappa, 100 * accuracy, duration))
return kappa, accuracy
def get_results(self):
"""
:return: List of arrays [logloss, accuracy, duration] with a value for each iteration.
"""
return [array(li) for li in zip(*self.results)]
def print_results(self, output_handle = stdout):
"""
Print some results to output_handle (console by default).
The current git hash is included so that the result can hopefully be reproduced by going back to that commit.
"""
kappa, accuracy, duration = self.get_results()
output_handle.write('*cross validation results*\n')
#output_handle.write('code version {0:s}\n'.format(check_output(['git', 'rev-parse','HEAD']).rstrip()))
output_handle.write('repetitions {0:d}\n'.format(len(self.results)))
output_handle.write('training # {0:d}\n'.format(self.use_data_count - self.test_count))
output_handle.write('testing # {0:d}\n'.format(self.test_count))
output_handle.write(' mean min max\n'.format(self.test_count))
output_handle.write('kappa {0:8.4f} {1:8.4f} {2:8.4f}\n'.format(kappa.mean(), kappa.min(), kappa.max()))
output_handle.write('accuracy {0:7.3f}% {1:7.3f}% {2:7.3f}%\n'.format(100 * accuracy.mean(), 100 * accuracy.min(), 100 * accuracy.max()))
output_handle.write('duration {0:7.4f}s {1:7.4f}s {2:7.4f}s\n'.format(duration.mean(), duration.min(), duration.max()))
if kappa.mean() > 0.6:
output_handle.write('amazing results!!\n')
elif kappa.mean() > 0.5:
output_handle.write('good results!\n')
elif kappa.mean() > 0.4:
output_handle.write('pretty good\n')
elif kappa.mean() > 0.3:
output_handle.write('okay results\n')
elif kappa.mean() > 0.2:
output_handle.write('not that bad\n')
elif kappa.mean() >0.1:
output_handle.write('room for improvement\n')
elif kappa.mean() > 0:
output_handle.write('meh...\n')
else:
output_handle.write('not good, sorry\n')
if __name__ == '__main__':
import numpy as np
data = np.random.rand(100,50)
true_classes = np.random.randint(0,5,100)
validator = SampleCrossValidator(data, true_classes, test_frac = 0.2, use_data_frac = 1)
for train, classes, test in validator.yield_cross_validation_sets(rounds = 1):
N = test.shape[0]
validator.add_prediction(np.random.randint(0,5,N))
validator.print_results()
<file_sep>/preprocessing/preprocess.py
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 15:14:26 2015
@author: Fenno
"""
import skimage.io as skio
from skimage.transform import resize
from scipy.ndimage.interpolation import zoom
import numpy as np
import os
from skimage import segmentation, color
"""
Thresholds an image given a threshold, by setting all pixels below the threshold to 0
you are below the threshold if the mean of the RGP values < threshold
warning: depending on the threshold, will zero out pixels inside the eye as well
TODO: fix this
"""
def threshold(image, threshold = 20.0):
intensity = np.mean(image, axis=2)
image[intensity < threshold] = 0
return image
"""
Better alternative to thresholding
"""
def segmentBackground(image):
labels = segmentation.slic(image, n_segments = 3)
out = color.label2rgb(labels, image, kind='avg')
intensity = np.mean(out, axis=2)
minimum_intensity = np.min(intensity)
image[intensity==minimum_intensity] = 0
return image
"""
Makes an image square by adding empty rows to the top, bottom, left, right where needed,
then resizes the image to the desired size (by default, 256x256)
"""
def makeSquare(image, size=512, labels=None):
rows, cols, _ = image.shape
size = (size, size, 3)
dtype = image.dtype
if labels is not None:
labeldtype = labels.dtype
if rows < cols:
newrows = (cols-rows) / 2
addstuff = np.zeros((newrows, cols, 3),dtype=dtype)
image = np.concatenate((addstuff, image, addstuff), axis= 0)
if cols - rows % 2:
image = np.concatenate((image, np.zeros((1,cols,3),dtype=dtype)), axis=0)
if labels is not None:
#print np.shape(labels), np.shape(addstuff), np.shape(addstuff[:,:,0])
labels = np.concatenate((addstuff[:,:,0], labels, addstuff[:,:,0]), axis = 0)
if cols - rows % 2:
labels = np.concatenate((labels, np.zeros((1,cols), dtype=labeldtype)),axis=0)
if cols < rows:
newcols = (rows-cols) / 2
addstuff = np.zeros((rows, newcols, 3),dtype=dtype)
image = np.concatenate((addstuff, image, addstuff), axis=1)
if rows - cols % 2:
image = np.concatenate((image, np.zeros((rows,1,3),dtype=dtype)), axis=1)
if labels is not None:
#print np.shape(labels), np.shape(addstuff), np.shape(addstuff[:,:,0])
labels = np.concatenate((addstuff[:,:,0], labels, addstuff[:,:,0]), axis = 1)
if cols - rows % 2:
labels = np.concatenate((labels, np.zeros((rows,1), dtype=labeldtype)),axis=1)
#skio.imsave(os.path.join("D:\\Documents\\Data\\DMED", "DMED-P", "test5.tif"), labels)
if labels is not None:
return resize(image, size), zoom(labels, 512.0 / max(rows, cols))
return resize(image, size)
"""
Crops an image by cutting off the rows and columns to the left, right, top, bottom
that are all zero. Therefore, it is smart to do this after thresholding
"""
def crop(image, labels = None):
nonzeros = np.nonzero(image)
if np.size(nonzeros[0]) == 0 or np.size(nonzeros[0]) == 0:
return np.zeros((1,1,3),dtype=image.dtype)
minrow = np.min(nonzeros[0])
maxrow = np.max(nonzeros[0])
mincol = np.min(nonzeros[1])
maxcol = np.max(nonzeros[1])
if (maxrow - minrow) == 0 or (maxcol - mincol) == 0:
return np.zeros((1,1,3),dtype=image.dtype)
if labels is not None:
return image[minrow:maxrow,mincol:maxcol,:], labels[minrow:maxrow,mincol:maxcol]
return image[minrow:maxrow,mincol:maxcol,:]
def process(imagepath, outpath, size=512):
print "Now processing " + os.path.basename(imagepath)
image = skio.imread(imagepath)
image = segmentBackground(image)
image = crop(image)
image = makeSquare(image, size)
skio.imsave(outpath, image)
del image
from learning.readTraining import getTrainingImage
def processLabels(name, outpath, labelout, size=512):
#image = skio.imread(imagepath)
#labels = skio.imread(labelpath)
image, labels = getTrainingImage(name)
labels[labels > 0] = -1
image = segmentBackground(image)
image, labels = crop(image, labels)
image, labels = makeSquare(image, size, labels)
#skio.imsave(os.path.join("D:\\Documents\\Data\\DMED", "DMED-P", "test6.tif"), labels)
skio.imsave(outpath, image)
skio.imsave(labelout, labels)
if __name__ == "__main__":
"""
BASEFOLDER = "D:\Documents\Data\CAD Project\\trainingdata"
imagepath = os.path.join(BASEFOLDER, "train")
outfolder = os.path.join(BASEFOLDER, "reducednew")
images = os.listdir(imagepath)
done = os.listdir(outfolder)
for picture in images:
if picture not in done and os.path.splitext(picture)[-1] in ['.jpg', '.jpeg']:
process(os.path.join(imagepath, picture), os.path.join(outfolder, picture))
"""
BASEFOLDER = "D:\\Documents\\Data\\DMED"
imagepath = os.path.join(BASEFOLDER, "DMED")
outfolder = os.path.join(BASEFOLDER, "DMED-P")
labelpath = os.path.join(BASEFOLDER, "DMED-GT")
images = os.listdir(imagepath)
done = os.listdir(outfolder)
for picture in images:
if picture not in done and os.path.splitext(picture)[-1] in ['.jpg', '.jpeg']:
label = ''.join(os.path.splitext(picture)[:-1]) + '.tif'
processLabels(os.path.basename(picture).split('.')[0], os.path.join(outfolder, picture), os.path.join(outfolder, label))
#processLabels(os.path.join(imagepath, picture), os.path.join(labelpath, label) , os.path.join(outfolder, picture), os.path.join(outfolder, label))<file_sep>/demo/simpleLearning.py
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 22:09:32 2015
@author: Fenno
"""
#The input for these features is typically a 512x512x3 matrix
import numpy as np
import sklearn.ensemble as ske
import skimage.io as skio
from os.path import join
def mask(picture, operation):
mask = np.repeat(np.sum(picture, 2) == 0, 3, 2)
return np.ma.masked_where(mask, picture)
def maskedIntensity(picture):
intensity = np.mean(picture, 2)
return np.ma.masked_where(intensity == 0, intensity)
mean_intensity = lambda intensity: np.ma.mean(intensity)
median_intensity = lambda intensity: np.ma.median(intensity)
std_intensity = lambda intensity: np.ma.std(intensity)
maskIntenFeatures = [mean_intensity, median_intensity, std_intensity]
def getFeatures(imagepath):
image = skio.imread(imagepath)
inten = maskedIntensity(image)
return np.array([f(inten) for f in maskIntenFeatures])
def createFeatureMatrix(trainLabelsPath, imagespath, number = 10000, suffix = '.jpeg'):
labels = np.genfromtxt(trainLabelsPath, dtype=None, delimiter = ',', skip_header = 1)
assert 0 < number <= np.size(labels)
labels = labels[:number]
feats = getFeatures(join(imagespath, labels[0][0] + suffix))
numfeats = np.size(feats)
featMatrix = np.empty((number, numfeats))
labs = np.empty(number)
for i, (fname, label) in enumerate(labels):
featMatrix[i,:] = getFeatures(join(imagespath, fname + suffix))
labs[i] = label
return featMatrix, labs.astype('int32')
def randomForest(traindata, trainlabels, testdata, n_estimators = 50):
model = ske.RandomForestClassifier(n_estimators = n_estimators).fit(traindata, trainlabels)
return model.predict(testdata).astype('int32')
if __name__ == '__main__':
#trainlabelpath = "D:\\Documents\\Dropbox\\CAD\\sampledata\\trainLabels.csv"
trainlabelpath = "C:\\Users\\fenno_000\\Dropbox\CAD\\sampledata\\trainLabels.csv"
imagepath = "C:\\Users\\fenno_000\\Documents\CAD Project\\reduced"
feats, labels = createFeatureMatrix(trainlabelpath, imagepath, 100)
print "done reading matrix"
from crossvalidate import SampleCrossValidator
validator = SampleCrossValidator(feats, labels, 0.1, 1.0)
for train, classes, test in validator.yield_cross_validation_sets(rounds = 1):
prediction = randomForest(train, classes, test, 50)
validator.add_prediction(prediction)
validator.print_results()
| 9a19e0294a68f3a1743e8d78244e7b86ad66bf96 | [
"Markdown",
"Python"
] | 13 | Python | fennovj/cad-doge | 78fe64d5a20c399c4dff096c01a50f6f8b8c881c | 6d8b708754a08256b75cadf91250a34b41e43c6e |
refs/heads/master | <file_sep>import sys
from datetime import datetime
import hashlib
import rsa
class User:
def __init__(self, name, balance=None):
self.name = name
self.balance = balance if balance is not None else 100
self.pubkey, self.__privkey = rsa.newkeys(512)
def send(self, receiver, amount):
if self.balance >= amount:
tr = Transaction(self, receiver, amount)
sign = rsa.sign(str(tr).encode(), self.__privkey, "SHA-256")
return {"transaction": tr, "sign": sign}
else:
sys.exit(f"{self.name} has not enough money.")
class Transaction:
def __init__(self, sender, receiver, amount):
self.timestamp = datetime.now()
self.sender = sender
self.receiver = receiver
self.amount = amount
def __str__(self):
return f"{self.timestamp}\n{self.sender.name} send {self.amount} coin to {self.receiver.name}\nSender's public key:\n{self.sender.pubkey.save_pkcs1().decode('UTF-8')}"
def executing(self):
self.sender.balance -= self.amount
self.receiver.balance += self.amount
def verification(self, signature):
if rsa.verify(str(self).encode(), signature, self.sender.pubkey):
return True
return False
def get_hash(self):
hash_ = hashlib.sha256(str(self).encode())
return hash_.digest()
class Block:
def __init__(self, block_number, prev_hash, hash_of_transactions):
self.block_number = block_number
self.prev_hash = prev_hash
self.hash_of_transactions = hash_of_transactions
self.nonce = 0
def __str__(self):
return f"Block number: {self.block_number}\nNonce: {self.nonce}\nHash of transactions: {self.hash_of_transactions}\nHash of previous block: {self.prev_hash}"
def mining(self, difficulty):
while self.get_hash()[0:difficulty] != '0' * difficulty:
self.nonce += 1
return self.get_hash()
def get_hash(self):
hash_ = hashlib.sha256(str(self).encode())
return hash_.hexdigest()
class Blockchain:
def __init__(self, difficulty):
self.blocks = []
self.difficulty = difficulty
self.current_block_number = 0
genesis = Block(self.current_block_number + 1, '0' * 64, '0' * 64)
genesis.mining(self.difficulty)
self.append_block(genesis)
def show_chain(self):
for block in self.blocks:
print(block, "\nHash of current block: ", block.get_hash(), end="\n---------\n")
def get_last_block(self):
return self.blocks[self.current_block_number - 1]
def append_block(self, block):
self.blocks.append(block)
self.current_block_number += 1
class ValidTransactions:
def __init__(self, hashes):
self.hashes = hashes
self.valid_transactions = []
def validator(self):
for transaction in self.hashes:
if transaction["transaction"].verification(transaction["sign"]):
self.valid_transactions.append(transaction["transaction"].get_hash())
transaction["transaction"].executing()
else:
return "This is an invalid transaction: ", transaction["transaction"]
return self.valid_transactions
class MerkleTree:
def __init__(self):
pass
def get_root(self, hashes):
while len(hashes) != 1:
if len(hashes) % 2 != 0:
hashes.append(hashes[-1])
merkle_hashes = []
for index in range(0, len(hashes) - 1, 2):
hash_ = hashlib.sha256(hashes[index] + hashes[index + 1])
merkle_hashes.append(hash_.digest())
hashes = merkle_hashes
return hashes[0].hex()
feri = User("Feri")
peti = User("Peti", 150)
miklos = User("Miklós")
eniko = User("Eniko", 10)
users = [feri, peti, miklos, eniko]
print("Users balance before send coin\n------------------------------------------------------")
for user in users:
print(f"Username: {user.name}, balance: {user.balance}")
print("------------------------------------------------------")
tr1 = feri.send(peti, 10)
tr2 = feri.send(miklos, 30)
tr3 = miklos.send(eniko, 30)
tr4 = eniko.send(peti, 5)
transactions = [tr1, tr2, tr3, tr4]
print(transactions[0]["transaction"], "\n------------------------------------------------------")
merkle_tree = MerkleTree()
hashes = ValidTransactions(transactions).validator()
hash_of_transactions = merkle_tree.get_root(hashes)
block_chain = Blockchain(4)
# number 2
block1 = Block(block_chain.current_block_number + 1, block_chain.get_last_block().get_hash(), hash_of_transactions)
block1.mining(block_chain.difficulty)
block_chain.append_block(block1)
# number 3
block2 = Block(block_chain.current_block_number + 1, block_chain.get_last_block().get_hash(), hash_of_transactions)
block2.mining(block_chain.difficulty)
block_chain.append_block(block2)
# number 4
block3 = Block(block_chain.current_block_number + 1, block_chain.get_last_block().get_hash(), hash_of_transactions)
block3.mining(block_chain.difficulty)
block_chain.append_block(block3)
# blockchain
block_chain.show_chain()
print("Users balance after sent coin\n------------------------------------------------------")
for user in users:
print(f"Username: {user.name}, balance: {user.balance}")
| bdabefc8355f241f92060be364218060a752adb6 | [
"Python"
] | 1 | Python | komlo654/blockchain | dd5d27b9d73af6d3594ade0712ee92b1be1a9de3 | 49ee827c9e94705b3b38bd5b8e8fc43e47aff311 |
refs/heads/master | <repo_name>laksgreen/spinnaker<file_sep>/scripts/2-InstallHalyard.sh
#!/bin/bash
## Install JDK
sudo apt update
sudo apt install openjdk-8-jdk openjdk-8-jre -y
java -version
sudo apt-get -y install jq apt-transport-https
## Install Halyard
curl -O https://raw.githubusercontent.com/spinnaker/halyard/master/install/debian/InstallHalyard.sh
sudo bash InstallHalyard.sh --user ubuntu
hal -v
hal -h
sleep 5s
# Install Docker
PRIVATE_IP=`curl -X GET "http://169.254.169.254/latest/meta-data/local-ipv4"`
curl -fsSL get.docker.com -o get-docker.sh
sh get-docker.sh
sudo usermod -aG docker ubuntu
sudo docker run -p $PRIVATE_IP:9090:9000 -d --name minio1 -v /mnt/data:/data -v /mnt/config:/root/.minio minio/minio server /data
MINIO_SECRET_KEY="minioadmin"
MINIO_ACCESS_KEY="minioadmin"
echo $MINIO_SECRET_KEY | hal config storage s3 edit --endpoint http://$PRIVATE_IP:9090 \
--access-key-id $MINIO_ACCESS_KEY \
--secret-access-key
hal config storage edit --type s3
echo -e "NOTE: If the 'docker container ls' command is not working instantly, logout from current session and login again. It will be working fine"
<file_sep>/scripts/3-configure-oauth.sh
#!/bin/bash
# Pass the variable that need to be set:
INSTANCE_IP=`curl -s ifconfig.co`
read -p "Enter Client Id: " CLIENT_ID
read -p "Enter Client Secret: " CLIENT_SECRET
read -p "Provider {gitlab|google|github|azure}: " PROVIDER
REDIRECT_URI=http://$INSTANCE_IP:8084/login
set -e
if [ -z "${CLIENT_ID}" ] ; then
echo "CLIENT_ID not set"
exit
fi
if [ -z "${CLIENT_SECRET}" ] ; then
echo "CLIENT_SECRET not set"
exit
fi
if [ -z "${PROVIDER}" ] ; then
echo "PROVIDER not set"
exit
fi
if [ -z "${REDIRECT_URI}" ] ; then
echo "REDIRECT_URI not set"
exit
fi
hal config security authn oauth2 edit \
--client-id $CLIENT_ID \
--client-secret $CLIENT_SECRET \
--provider $PROVIDER
hal config security authn oauth2 enable
hal config security authn oauth2 edit --pre-established-redirect-uri $REDIRECT_URI
hal config security ui edit \
--override-base-url http://${INSTANCE_IP}:9000
hal config security api edit \
--override-base-url http://${INSTANCE_IP}:8084
<file_sep>/scripts/1-swapspace.sh
#!/bin/bash
## Create a Swap Space
sudo fallocate -l 8G /swapspace
sudo chmod 600 /swapspace
sudo mkswap /swapspace
echo '/swapspace none swap sw 0 0' | sudo tee -a /etc/fstab
sudo swapon /swapspace
| cb55b8a2c8d4473541fe54f97189120bcc88b08f | [
"Shell"
] | 3 | Shell | laksgreen/spinnaker | bf052848f4c5f03cf4357544979067385f935087 | 524d9978675d9a77af6bb9ea15fa1587eef1acec |
refs/heads/master | <repo_name>sciencemanx/jlpt-flashcards<file_sep>/README.md
# jlpt-flashcards
Automatically create flashcards for different JLPT levels
<file_sep>/src/flashcards.py
#! /usr/bin/env python3
import os
import shutil
import genanki
import requests
from vocab import get_vocab, JLPT_LEVELS
MODEL_ID = 654321
DECK_BASE_ID = 563412
VOCAB_FIELDS = [
{'name': 'id'},
{'name': 'kana'},
{'name': 'kanji'},
{'name': 'partofspeech'},
{'name': 'meaning'},
{'name': 'audio'},
]
JA_EN_TEMPLATE = {
'name': 'kana->kanji/meaning',
'qfmt': '{{audio}}</br><strong><span style="font-family: Meiryo; font-size: 60px; ">{{kana}}</span></strong><br/>(<i>{{partofspeech}}</i>)',
'afmt': '{{FrontSide}}<hr><span style="font-family: Meiryo; font-size: 30px; ">{{kanji}}</span><br><strong><span style="font-size: 40px; ">{{meaning}}</span></strong></br>',
}
EN_JA_TEMPLATE = {
'name': 'meaning->kana/kanji',
'qfmt': '<strong><span style="font-size: 40px; ">{{meaning}}</span></strong> (<i>{{partofspeech}}</i>)</br>',
'afmt': '{{FrontSide}}<hr><strong><span style="font-family: Meiryo; font-size: 60px; ">{{kanji}}</span></strong></br><span style="font-family: Meiryo; font-size: 30px; ">{{kana}}</span></br>{{audio}}',
}
MODEL_CSS = '''
.card {
font-family: arial;
font-size: 20px;
text-align: center;
color: black;
background-color: white;
}
.card1 { background-color: #969696; }
.card2 { background-color: #FFFFFF; }'
)
'''
VOCAB_MODEL = genanki.Model(
MODEL_ID,
'JLPT Vocab Model',
fields=VOCAB_FIELDS,
templates=[
JA_EN_TEMPLATE,
EN_JA_TEMPLATE,
],
css=MODEL_CSS,
)
class KanjiNote(genanki.Note):
@property
def guid(self):
return genanki.guid_for(self.fields[0], self.fields[1])
def get_deck(jlpt_level):
vocab = get_vocab(jlpt_level)
deck = genanki.Deck(DECK_BASE_ID + jlpt_level, 'JLPT Vocab::N{}'.format(jlpt_level))
media = []
for v in vocab:
if v.path is not None:
media.append(v.path)
audio = '[sound:{}]'.format(v.path)
else:
audio = ''
note = KanjiNote(
model=VOCAB_MODEL,
fields=[str(v.id), v.kana, v.kanji, ', '.join(v.pos), v.defn, audio]
)
deck.add_note(note)
return deck, media
def get_package(jlpt_levels=None):
if jlpt_levels is None:
jlpt_levels = list(JLPT_LEVELS)
assert all(jlpt_level in JLPT_LEVELS for jlpt_level in jlpt_levels)
all_media = []
decks = []
for jlpt_level in jlpt_levels:
deck, media = get_deck(jlpt_level)
decks.append(deck)
all_media.extend(media)
return genanki.Package(decks, media_files=all_media)
if __name__ == '__main__':
levels = [2]
package = get_package(levels)
package.write_to_file('jlpt_{}.apkg'.format('-'.join('n{}'.format(n) for n in levels)))
<file_sep>/src/pronounce.py
import json
import os
import requests
FORVO_KEY = ''
FORVO_URL = 'https://apifree.forvo.com/{}'
PARAM_DEFAULTS = {
'format': 'json',
'key': FORVO_KEY,
'action': 'pronounced-words-search',
'language': 'ja',
}
dot = '・'
tilde = '~'
slash = '/'
FORVO_FAILING = False
def forvo(**kwargs):
global FORVO_FAILING
if FORVO_FAILING:
raise AssertionError
for k, v in PARAM_DEFAULTS.items():
kwargs[k] = kwargs.get(k, v)
params = ['{}/{}'.format(k, v) for k, v in kwargs.items()]
url = FORVO_URL.format('/'.join(params))
res = requests.get(url)
if res.status_code == 400:
print(url)
print(res)
print(res.text)
print('forvo failing')
FORVO_FAILING = True
assert res.status_code == 200
d = json.loads(res.text)
return d['items']
def get_pronunciation_url(word, ext='mp3', **kwargs):
assert ext in ['ogg', 'mp3']
word = word.replace(tilde, '')
word = word.replace('(', '')
word = word.replace(')', '')
if dot in word:
word = word.split(dot)[0]
if slash in word:
word = word.split(slash)[0]
items = forvo(search=word, **kwargs)
if len(items) == 0:
print(word)
raise AssertionError()
best = items[0]['standard_pronunciation']
if ext == 'ogg':
return best['pathogg']
if ext == 'mp3':
return best['pathmp3']
def download_pronunciation(word, ext='ogg', **kwargs):
assert ext in ['ogg', 'mp3']
url = get_pronunciation_url(word, ext=ext, **kwargs)
res = requests.get(url)
assert res.status_code == 200
filename = '{}.{}'.format(word.replace('/', '-'), ext)
with open(filename, 'wb') as f:
f.write(res.content)
return filename
<file_sep>/src/vocab.py
import os
from typing import List, NamedTuple
from bs4 import BeautifulSoup
from progressbar import progressbar
import requests
from pronounce import download_pronunciation
class Vocab(NamedTuple):
id: int
kana: str
kanji: str
pos: List[str]
defn: str
path: str
URL_FMT = 'https://jlptstudy.net/N{0}/lists/n{0}_vocab-list.html'
JLPT_LEVELS = [2, 4, 5]
def get_vocab_html(level):
assert level in JLPT_LEVELS
url = URL_FMT.format(level)
res = requests.get(url)
assert res.status_code == 200
return str(res.content, encoding='utf8')
def get_vocab(level):
assert level in JLPT_LEVELS
html = get_vocab_html(level)
soup = BeautifulSoup(html, 'html.parser')
vocab_table = soup.find('table', {'class':'vocab-list'})
def process_row(vocab):
fields = vocab.find_all('td')
idx, kana, kanji, pos, defn = [tag.text.strip() for tag in fields]
if kanji == '':
kanji = kana
path = '{}.mp3'.format(kanji.replace('/', '-'))
if not os.path.isfile(path):
try:
path = download_pronunciation(kanji)
except AssertionError:
path = None
return Vocab(int(idx), kana, kanji, pos.split(','), defn, path)
vocab_rows = [r for r in vocab_table.find_all('tr') if len(r.find_all('td')) == 5]
return [process_row(r) for r in progressbar(vocab_rows)]
| 498bbaf0bbf3ab6a05dcb2211fcce5b3ebff459c | [
"Markdown",
"Python"
] | 4 | Markdown | sciencemanx/jlpt-flashcards | b0f7b7f8e4a7efe3959b64897a5a598e1abc83b2 | ce66bdc6bca040b64461020ee7193cd5f06c9d79 |
refs/heads/master | <repo_name>wlcumt/cattlewl<file_sep>/code/iaas/api-logic/src/main/java/io/cattle/platform/iaas/api/filter/instance/InstanceOutputFilter.java
package io.cattle.platform.iaas.api.filter.instance;
import io.cattle.platform.core.addon.HealthcheckState;
import io.cattle.platform.core.addon.MountEntry;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.constants.NetworkConstants;
import io.cattle.platform.core.dao.ServiceDao;
import io.cattle.platform.core.dao.VolumeDao;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.docker.transform.DockerTransformer;
import io.cattle.platform.iaas.api.filter.common.CachedOutputFilter;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.meta.ObjectMetaDataManager;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.util.type.CollectionUtils;
import io.github.ibuildthecloud.gdapi.context.ApiContext;
import io.github.ibuildthecloud.gdapi.id.IdFormatter;
import io.github.ibuildthecloud.gdapi.model.Resource;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
public class InstanceOutputFilter extends CachedOutputFilter<Map<Long, Map<String, Object>>> {
@Inject
ServiceDao serviceDao;
@Inject
ObjectManager objectManager;
@Inject
VolumeDao volumeDao;
@Inject
DockerTransformer transformer;
@Override
public Class<?>[] getTypeClasses() {
return new Class<?>[] {};
}
@Override
public String[] getTypes() {
return new String[]{InstanceConstants.TYPE_CONTAINER};
}
@Override
public Resource filter(ApiRequest request, Object original, Resource converted) {
if (request == null || !"v1".equals(request.getVersion())) {
if (original instanceof Instance) {
Map<Long, Map<String, Object>> data = getCached(request);
if (data != null) {
Map<String, Object> fields = data.get(((Instance) original).getId());
if (fields != null) {
converted.getFields().putAll(fields);
}
}
converted.getFields().put(InstanceConstants.FIELD_EXIT_CODE,
transformer.getExitCode((Instance) original));
}
}
if (((Instance) original).getServiceId() != null) {
Map<String, URL> actions = converted.getActions();
if (actions != null) {
actions.remove("converttoservice");
}
}
List<Long> networkIds = DataAccessor.fieldLongList(original, InstanceConstants.FIELD_NETWORK_IDS);
if (networkIds.size() > 0) {
IdFormatter idF = ApiContext.getContext().getIdFormatter();
converted.getFields().put(InstanceConstants.FIELD_PRIMARY_NETWORK_ID, idF.formatId(NetworkConstants.KIND_NETWORK, networkIds.get(0)));
}
Map<String, Object> labels = CollectionUtils.toMap(converted.getFields().get(InstanceConstants.FIELD_LABELS));
if ("rancher-agent".equals(labels.get("io.rancher.container.system")) &&
"rancher-agent".equals(converted.getFields().get(ObjectMetaDataManager.NAME_FIELD))) {
Map<String, URL> actions = converted.getActions();
if (actions != null) {
actions.remove("remove");
actions.remove("stop");
actions.remove("start");
actions.remove("restart");
}
}
return converted;
}
@Override
protected Map<Long, Map<String, Object>> newObject(ApiRequest apiRequest) {
Map<Long, Map<String, Object>> result = new HashMap<>();
List<Long> ids = getIds(apiRequest);
IdFormatter idF = ApiContext.getContext().getIdFormatter();
for (Map.Entry<Long, List<Object>> entry : serviceDao.getServicesForInstances(ids, idF).entrySet()) {
Map<String, Object> fields = new HashMap<>();
fields.put(InstanceConstants.FIELD_SERVICE_IDS, entry.getValue());
result.put(entry.getKey(), fields);
}
for (Map.Entry<Long, List<MountEntry>> entry : volumeDao.getMountsForInstances(ids, idF).entrySet()) {
Map<String, Object> fields = result.get(entry.getKey());
if (fields == null) {
fields = new HashMap<>();
result.put(entry.getKey(), fields);
}
fields.put(InstanceConstants.FIELD_MOUNTS, entry.getValue());
}
for (Map.Entry<Long, List<HealthcheckState>> entry : serviceDao.getHealthcheckStatesForInstances(ids, idF)
.entrySet()) {
Map<String, Object> fields = result.get(entry.getKey());
if (fields == null) {
fields = new HashMap<>();
result.put(entry.getKey(), fields);
}
fields.put(InstanceConstants.FIELD_HEALTHCHECK_STATES, entry.getValue());
}
return result;
}
@Override
protected Long getId(Object obj) {
if (obj instanceof Instance) {
return ((Instance) obj).getId();
}
return null;
}
}
<file_sep>/code/iaas/api-logic/src/main/java/io/cattle/platform/iaas/api/filter/instance/InstanceAgentValidationFilter.java
package io.cattle.platform.iaas.api.filter.instance;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.iaas.api.filter.common.AbstractDefaultResourceManagerFilter;
import io.cattle.platform.object.ObjectManager;
import io.github.ibuildthecloud.gdapi.exception.ClientVisibleException;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;
import io.github.ibuildthecloud.gdapi.request.resource.ResourceManager;
import io.github.ibuildthecloud.gdapi.util.ResponseCodes;
import io.github.ibuildthecloud.gdapi.validation.ValidationErrorCodes;
import javax.inject.Inject;
public class InstanceAgentValidationFilter extends AbstractDefaultResourceManagerFilter {
@Inject
ObjectManager objectManager;
@Override
public String[] getTypes() {
return new String[] {InstanceConstants.TYPE_CONTAINER};
}
@Override
public Class<?>[] getTypeClasses() {
return new Class<?>[] { Instance.class };
}
@Override
public Object delete(String type, String id, ApiRequest request, ResourceManager next) {
Object instance = objectManager.loadResource(type, id);
if (instance == null || !(instance instanceof Instance)) {
return super.delete(type, id, request, next);
}
if (InstanceConstants.isRancherAgent((Instance)instance)) {
throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, ValidationErrorCodes.ACTION_NOT_AVAILABLE,
"Can not delete rancher-agent", null);
}
return super.delete(type, id, request, next);
}
} | 246b34f2ffa533af7dd82641dab72ccb4112edde | [
"Java"
] | 2 | Java | wlcumt/cattlewl | d709bde3a0d7cb17b6a8a1bb4685681330bc625a | 38962c34b22c6d27579e74da123655c621ae4928 |
refs/heads/master | <file_sep>
<div class="pix_section pix-padding-v-85 gray-bg" id="section_call_to_action_1" style="display: block; margin-top: 60px">
<div class="container">
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12 column ui-droppable">
<div class="pix-content text-center">
<div class="pix-margin-bottom-30">
<img class="img-size" src="<?php echo base_url()?>assets/imgs/platinum.jpg">
</div>
<h5 class="text-center pix-purple"><span class="pix_edit_text"><strong>Obtenez votre pack platinum</strong></span></h5>
<h2 class="pix-black-gray-dark text-center pix-no-margin-top secondary-font">
<span class="pix_edit_text"><strong>Augmentez vos possibilités !</strong></span>
</h2>
<h5 class="pix-black-gray-light text-center pix-margin-bottom-30">
<span class="pix_edit_text">Mettez-vous à jour grâce au pack Platinum et bénéficiez de toute notre gamme de produits dés au aujourd'hui</span>
</h5>
<a href="#" class="btn purple-bg btn-lg pix-white btn-round-lg">
<span class="pix_edit_text">
<button type="button" class="btn btn-lg btn-primary">Contactez nous</button>
</span>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="pix_section pix-padding-v-50" id="section_accordions_1" style="display: block; margin-top: 50px">
<div class="container">
<div class="row">
<div class="col-md-6 col-xs-12 col-sm-6 column ui-droppable">
<div class="pix-content">
<div class="pix-margin-bottom-20">
<i class="pixicon-chat2 big-icon-65 pix-orange"></i>
</div>
<img style="margin-left: 35%" class="img-size text-center" src="<?php echo base_url()?>assets/imgs/premium.png">
<p class="pix-black-gray-light big-text pix-margin-bottom-30">
<span class="pix_edit_text">
<h3 class="text-center">Vous disposez actuellement du pack premium</h3>
</span>
</p>
<div class="pix-margin-bottom-30">
<a href="#" class="btn orange-bg btn-lg btn-round-lg small-text pix-white secondary-font">
<span class="pix_edit_text">
</span>
</a>
</div>
</div>
</div>
<div class="col-md-6 col-xs-12 col-sm-6 column ui-droppable">
<h2 class="text-center">Voici les options que vous avez souscrites</h2>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Nom de l'option</th>
<th scope="col">Produit</th>
<th scope="col">date</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Facturation PDF</td>
<td>Eseason</td>
<td>10/02/2019</td>
</tr>
<tr>
<th scope="row">2</th>
<td>E signature</td>
<td>Eseason</td>
<td>28/01/2019</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Assistance support premium</td>
<td>ALL</td>
<td>02/01/2019</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<file_sep>app.controller('LoginCtrl', ['$scope', '$location','LoginFactory',
function ($scope, $location, LoginFactory)
{
$scope.base_url = $location.protocol() + "://" + $location.host()+'/index.php/';
$scope.login = function () {
$scope.error = 0;
LoginFactory.checkLogin($scope.user, $scope.password).then(function (data) {
console.log(data);
if (data === 'true') {
location.href = $scope.base_url + 'home';
} else {
$scope.error = 1;
}
});
if ($scope.password === "<PASSWORD>" && $scope.user === "clement") {
location.href = $scope.base_url + 'home';
}
};
}
]);
<file_sep><?php
/**
* Created by PhpStorm.
* User: Clement
* Date: 02/05/2019
* Time: 09:24
*/
class ActusController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->model('ActusModel');
}
public function index()
{
$this->load->view('partial/header');
$this->load->view('actus');
}
public function readArticle($id)
{
$this->load->view('partial/header');
$this->load->view('article');
}
public function getArticle()
{
$result = $this->ActusModel->getArticle($_REQUEST['id']);
$this->jsonEncode($result);
}
public function getArticles()
{
if(isset($_REQUEST['limit']))
{
$limit = 2;
}
else {
$limit = null;
}
$result = $this->ActusModel->getArticles($limit);
$this->jsonEncode($result);
}
public final function jsonEncode ($data)
{
echo json_encode($data);
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Clement
* Date: 03/05/2019
* Time: 11:12
*/
class LoginController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('ClientModel');
}
public function index()
{
$idClient = $_REQUEST['idclient'];
$name = $_REQUEST['name'];
$check = $this->ClientModel->login($idClient, $name);
echo json_encode($check);
}
public function getInfos()
{
echo json_encode($_SESSION);
}
}
<file_sep>app.factory('ChangelogFactory', ['$http', '$location', function ($http, $location) {
return {
getProducts: function (slug) {
return $http({
method: 'GET',
url: 'http://changelog.local/api/products/' + slug
}).then(function (x) {
return x.data;
});
},
}
}]);
<file_sep>app.factory('LoginFactory', ['$http', '$location', function ($http, $location) {
return {
checkLogin: function (idclient, name) {
return $http({
method: 'GET',
params: {
'idclient': idclient,
'name': name
},
url: $location.protocol() + "://" + $location.host() + '/index.php/login'
}).then(function (x) {
return x.data;
});
},
getInfos: function () {
return $http({
method: 'GET',
url: $location.protocol() + "://" + $location.host() + '/index.php/getInfos'
}).then(function (x) {
return x.data;
});
},
getResponsableClient: function () {
return $http({
method: 'GET',
url: $location.protocol() + "://" + $location.host() + '/index.php/getResponsableClient'
}).then(function (x) {
return x.data;
});
},
}
}]);
<file_sep><?php
/**
* Created by PhpStorm.
* User: Clement
* Date: 20/05/2019
* Time: 12:21
*/
class ActusModel extends CI_Model
{
public function getArticles($limit)
{
$this->db->select('*');
$this->db->from('actus pro');
if($limit == 2)
{
$this->db->limit(2);
}
$query = $this->db->get();
return $query->result_array($query);
}
public function getArticle($id)
{
$this->db->select('*');
$this->db->from('actus act');
$this->db->where('act.id', $id);
$query = $this->db->get();
return $query->result_array($query);
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Clement
* Date: 06/05/2019
* Time: 11:07
*/
class EnterpriseController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('ClientModel');
}
public function index()
{
$this->load->view('partial/header');
$this->load->view('entreprise');
}
public function getResponsable()
{
$check = $this->ClientModel->getResponsableClient($_SESSION['id']);
echo json_encode($check);
}
}
<file_sep>app.controller('maps', ['$scope', '$location','LoginFactory',
function ($scope, $location, LoginFactory)
{
$scope.src='https://maps.google.com/maps?q=';
$scope.city='béziers'+'%20';
$scope.country='franc%20';
$scope.postcode='34500';
$scope.lastSrc= '&t=&z=13&ie=UTF8&iwloc=&output=embed';
$scope.url = $scope.src + $scope.city + $scope.country + $scope.postcode + $scope.lastSrc;
}
]);
<file_sep><?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Created by PhpStorm.
* User: Clement
* Date: 10/05/2019
* Time: 14:30
*/
class ProductsController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
}
public function index()
{
$this->load->view('products');
}
}
<file_sep><html lang="en">
<script id="tinyhippos-injected">if (window.top.ripple) {
window.top.ripple("bootstrap").inject(window, document);
}</script>
<head>
<meta charset="utf-8">
<title>CustomerPortal</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/hammerjs/2.0.8/hammer.min.js"></script>
<link id="theme-style" rel="stylesheet" href="<?php echo base_url() ?>assets/css/home.css">
<link id="theme-style" rel="stylesheet" href="<?php echo base_url() ?>assets/css/contrats.css">
<script src="<?php echo base_url() ?>node_modules/angular/angular.js"></script>
<script src="<?php echo base_url() ?>node_modules/angular-sanitize/angular-sanitize.js"></script>
<script src="<?php echo base_url() ?>assets/js/app.js"></script>
<script src="<?php echo base_url() ?>assets/js/NavCtrl.js"></script>
<script src="<?php echo base_url() ?>assets/js/SupportCtrl.js"></script>
<script src="<?php echo base_url() ?>assets/js/HomeCtrl.js"></script>
<script src="<?php echo base_url() ?>assets/js/LoginFactory.js"></script>
<script src="<?php echo base_url() ?>assets/js/LoginCtrl.js"></script>
<script src="<?php echo base_url() ?>assets/js/ChangelogFactory.js"></script>
<script src="<?php echo base_url() ?>assets/js/ActusCtrl.js"></script>
<script src="<?php echo base_url() ?>assets/js/ActusFactory.js"></script>
<script src="<?php echo base_url() ?>assets/js/ArticleCtrl.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
integrity="<KEY>" crossorigin="anonymous">
<!------ Include the above in your HEAD tag ---------->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<body ng-app="portailClient">
<div ng-controller="HomeCtrl">
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-3 color">
<div class="container" ng-controller="NavCtrl">
<button class="navbar-toggler navbar-toggler-right mx-auto" type="button" data-toggle="collapse"
data-target="#navbar2SupportedContent" aria-controls="navbar2SupportedContent" aria-expanded="false"
aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
<div class="collapse navbar-collapse text-center justify-content-between" id="navbar2SupportedContent">
<a class="p-2 text-secondary" href="#"><i class="fas fa-headset fa-1x"></i></a>
<a class="p-2 text-secondary" ng-click="nav('home')">Accueil</a>
<a class="p-2 text-secondary" ng-click="nav('actus')">Actualités</a>
<a class="p-2 text-secondary" ng-click="nav('contrats')">Mes contrats</a>
<a class="p-2 text-secondary" ng-click="nav('entreprise')">Enterprise</a>
<a class="p-2 text-secondary" href="#">Support</a>
<a class="p-2 text-secondary" ng-click="logout()">
<button ng-click="logout()" type="button" class="btn btn-warning">Deconnexion</button>
</a>
</div>
<div ng-controller="SupportCtrl">
<button data-toggle="modal" data-target="#exampleModal" type="button" class="btn btn-info">Ouvrir un
incident
</button>
</div>
</div>
</nav>
<file_sep><html lang="en">
<script id="tinyhippos-injected">if (window.top.ripple) {
window.top.ripple("bootstrap").inject(window, document);
}</script>
<head>
<meta charset="utf-8">
<title>CustomerPortal</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/hammerjs/2.0.8/hammer.min.js"></script>
<link id="theme-style" rel="stylesheet" href="<?php echo base_url() ?>assets/css/home.css">
<script src="<?php echo base_url() ?>node_modules/angular/angular.js"></script>
<script src="<?php echo base_url() ?>node_modules/angular-sanitize/angular-sanitize.js"></script>
<script src="<?php echo base_url() ?>assets/js/app.js"></script>
<script src="<?php echo base_url() ?>assets/js/NavCtrl.js"></script>
<script src="<?php echo base_url() ?>assets/js/SupportCtrl.js"></script>
<script src="<?php echo base_url() ?>assets/js/HomeCtrl.js"></script>
<script src="<?php echo base_url() ?>assets/js/LoginFactory.js"></script>
<script src="<?php echo base_url() ?>assets/js/ChangelogFactory.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
integrity="<KEY>" crossorigin="anonymous">
<!------ Include the above in your HEAD tag ---------->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<body ng-app="portailClient">
<div ng-controller="HomeCtrl">
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-3 color">
<div class="container" ng-controller="NavCtrl">
<button class="navbar-toggler navbar-toggler-right mx-auto" type="button" data-toggle="collapse"
data-target="#navbar2SupportedContent" aria-controls="navbar2SupportedContent" aria-expanded="false"
aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
<div class="collapse navbar-collapse text-center justify-content-between" id="navbar2SupportedContent">
<a class="p-2 text-secondary" href="#"><i class="fas fa-headset fa-1x"></i></a>
<a class="p-2 text-secondary" ng-click="nav('home')">Accueil</a>
<a class="p-2 text-secondary" ng-click="nav('products')">Mes produits</a>
<a class="p-2 text-secondary" ng-click="nav('contrats')">Mes contrats</a>
<a class="p-2 text-secondary" ng-click="nav('entreprise')">Enterprise</a>
<a class="p-2 text-secondary" href="#">Support</a>
<a class="p-2 text-secondary" ng-click="logout()">
<button ng-click="logout()" type="button" class="btn btn-warning">Deconnexion</button>
</a>
</div>
<div ng-controller="SupportCtrl">
<button data-toggle="modal" data-target="#exampleModal" type="button" class="btn btn-info">Ouvrir un
incident
</button>
</div>
</div>
</nav>
<div class="container">
<div class="row match-height">
<div class="card" ">
<div class="card-header">
<h4 class="card-title">Basic Card</h4>
</div>
<div class="card-content">
<div class="card-body">
<h5>Basic Card With Header & Footer</h5>
</div>
<img class="img-fluid" src="<?php echo base_url()?>assets/imgs/login-background.jpg" alt="Card image cap">
<div class="card-body">
<p class="card-text">Some quick example text to build on the card title and make up the bulk of
the card's content.</p>
<a href="#" class="card-link">Card link</a>
<a href="#" class="card-link">Another link</a>
</div>
</div>
<div class="card-footer border-top-blue-grey border-top-lighten-5 text-muted">
<span class="float-left">3 hours ago</span>
<span class="float-right">
<a href="#" class="card-link">Read More <i class="fa fa-angle-right"></i></a>
</span>
</div>
</div>
</div>
</div>
<file_sep>app.controller('ArticleCtrl', ['$scope', '$location','ActusFactory',
function ($scope, $location, ActusFactory)
{
$scope.goBack = function () {
location.href = $scope.base_url + 'actus';
};
$scope.base_url = $location.protocol() + "://" + $location.host()+'/index.php/';
var id = $location.path().split('/')[3];
ActusFactory.getArticle(id).then(function (data) {
console.log(data);
$scope.actus = data[0];
});
$scope.readMore = function (id) {
location.href = $location.protocol() + "://" + $location.host() + '/index.php/actus/'+id
};
}
]);
<file_sep><div class="wrapper" ng-controller="LoginCtrl">
<form class="form-signin">
<h2 class="form-signin-heading">Bienvenue</h2>
<h4 class="form-signin-heading">Veuillez vous authentifiez</h4>
<input type="text" class="form-control" ng-model="user" name="username" placeholder="<NAME>" required="required" autofocus="" />
<br>
<input type="text" class="form-control" ng-model="password" placeholder="Nom du site complet" required="required"/>
<br>
<button class="btn btn-lg btn-primary btn-block" ng-click="login()">Login</button>
<div class="container-fluid">
<img class="center-block img-size" src="<?php echo base_url()?>assets/imgs/logo.png">
</div>
<br>
<div class="alert alert-danger" role="alert" ng-if="error == 1">
Erreur ne ne sommes pas parvenus a vous connecter
</div>
</form>
<div class="img">
<img src="<?php echo site_url()?>assets/imgs/login-background.jpg">
</div>
</div>
<style>
.img {
z-index: -9999;
position: fixed;
top: 0;
}
.img-size {
margin: 0 auto;
width: 80%;
margin-top: 15px;
padding-bottom: -8px;
}
body {
background: #eee !important;
}
.wrapper {
margin-top: 80px;
margin-bottom: 80px;
}
.form-signin {
max-width: 380px;
padding: 15px 35px 45px;
margin: 0 auto;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.1);
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 30px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
font-size: 16px;
height: auto;
padding: 10px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="text"] {
margin-bottom: -1px;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.form-signin input[type="password"] {
margin-bottom: 20px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
</style>
<file_sep> <div class="py-5 text-center mx-3 mb-3">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h1 class="display-4"><img class="align-content-center position-logo"
src="<?php echo base_url() ?>assets/imgs/Sequoiasoft_Direct_logo.png">
</h1>
<h4>Bienvenue {{camping.name_full}}</h4>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<h5>
<strong><i class="fas fa-exclamation-triangle"></i></strong> Attention vous arrivez en fin de contrat
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</h5>
</div>
</div>
</div>
</div>
<div class="row">
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<div class="row border">
<div class="col-md-6 background-tips">
<div class="about_box background-tips">
<br>
<div class="about_box_1">
<div class="about_img_box text-center">
<i class="fas fa-lightbulb fa-3x text-center"></i>
</div>
<div class="container">
<div class="about_con_box">
<h3 class="text-center">Le saviez vous</h3>
<p>Vous pouvez exporter vos statistiques depuis le back-office WEBCAMP de vos
dernières réservations pour en savoir plus cliquer ici</p>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="col-md-12">
<h3 class="service-title main-title">Documentation sur vos produits</h3>
<div class="row">
<div class="col-6 center-element">
<a href="http://helpdesk.thelis.fr/article-categories/eseasonresa/" class="thumbnail">
<img class="size-logo"
src="<?php echo base_url() ?>assets/imgs/esaeson_resa.png"/>
</a>
</div>
<div class="col-6 center-element">
<a href="http://helpdesk.thelis.fr/article-categories/webcamp/" class="thumbnail">
<img class="size-logo"
src="<?php echo base_url() ?>assets/imgs/logo_webcamp.gif"/>
</a>
</div>
<div class="col-6 center-element">
<a href="http://helpdesk.thelis.fr/article-categories/eseason/" class="thumbnail">
<img class="size-logo" src="<?php echo base_url() ?>assets/imgs/eseason.png"/>
</a>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12 border">
<div class="col-12">
<div class="row">
<div class="col-6">
<div class="container">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Demande</th>
<th scope="col">date</th>
<th scope="col">status</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Tracking</td>
<td>10/04/2019</td>
<td><i class="far fa-hourglass"></i> en cour</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Intégration bancaire</td>
<td>05/03/2019</td>
<td><i class="fas fa-check"></i> Valider</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Ajout de css custom</td>
<td>03/01/2019</td>
<td><i class="fas fa-times-circle"></i> Annuler</td>
</tr>
</tbody>
</table>
<a href="akuiteo://client=500020754">Akuiteo</a>
<a href="akuiteo://client=105443">TEest</a>
<a class="btn btn-primary" href="https://my.sequoiasoft.com" role="button">Accèder
a akuiteo</a>
<br>
<br>
</div>
</div>
<div class="col-6">
<h4 class="text-center">Demander une formation</h4>
<form>
<div class="form-group">
<div class="form-group">
<label class="text-center" for="exampleFormControlSelect1">Selectionner
votre produit</label>
<select class="form-control" id="exampleFormControlSelect1">
<option>ESeason Resa</option>
<option>Webcamp</option>
<option>Eseason</option>
</select>
</div>
</div>
<div class="text-center">
<button type="button" class="btn btn-primary">Contacter mon commercial
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<br>
<h4>Les dernières mise a jour de nos produits :</h4>
<div class="row">
<div class="col-md-12 border" style="height: 450px; overflow: auto;">
<div class="col-12">
<select class="form-control lead"
data-step="2" data-intro="Vous pouvez choisir diférente version ici"
ng-model="filter.version"
ng-options="v.number as v.number for v in product.versions track by v.number">
<option value="">Toutes les versions</option>
</select>
<label class="checkbox-inline amelioration lead"
data-step="3"
data-intro="Vous pouvez choisir de filtrer par Type d'amélioration">
<input type="checkbox" id="inlineCheckbox1"
ng-init="filter.types.amelioration = true"
ng-model="filter.types.amelioration">
Améliorations
</label>
<label class="checkbox-inline evolution lead"
data-step="4"
data-intro="Vous pouvez choisir de filtrer par Type d'évolution">
<input type="checkbox" id="inlineCheckbox2"
ng-init="filter.types.evolution = true"
ng-model="filter.types.evolution">
Evolutions
</label>
<label class="checkbox-inline bugs lead"
data-step="5"
data-intro="Et par Type de Bug">
<input type="checkbox" id="inlineCheckbox3"
ng-init="filter.types.bug = true"
ng-model="filter.types.bug">
Bugs
</label>
<div class="doc-body" style="font-family: Helvetica Neue, Helvetica, Arial, sans-serif">
<div class="content-inner">
<div class="alert alert-info text-center"
ng-if="0 === filteredVersions.length">
Aucun résultat ne correspond à vos filtres de recherche
</div>
<div
ng-repeat="version in filteredVersions = (product.versions | filter: filterVersions)">
<section class="doc-section">
<div class="section-title panel panel-default">
<span id="{{version.number}}" class="release-version"
data-step="7" data-intro="Vous trouverez le numéro de version ici">
v {{version.number}}</span><span
class="release-date"> - <em>{{version.date | date:"dd/MM/yyyy"}}</em></span>
</div>
<div class="section-block"
ng-if="changelog.enabled"
ng-repeat="changelog in version.changelogs">
<div class="task-block">
<div class="task-title">
<i class="icon fa fa-ban"
ng-if="logIsPrivate(changelog)"></i>
<span data-step="8"
data-intro="Le titre du changelog"
ng-bind="getLog(changelog).title"></span>
</div>
<div data-step="9" data-intro="ici le type du changelog">
<span class="badge badge-amelioration"
ng-if="getChangelogType(changelog) == 1">Amélioration</span>
<span class="badge badge-evol"
ng-if="getChangelogType(changelog) == 2">Evolution</span>
<span class="badge badge-bug"
ng-if="getChangelogType(changelog) == 3">Bug</span>
<div class="clear"></div>
</div>
<p class="task-description"
data-step="10"
data-intro="Et pour finir la desciption du log"
ng-bind-html="getLog(changelog).description"></p>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4" style="" >
<div class="col mx-2 pt-5 px-5 mb-3 border">
<h4>Actualités</h4>
<div class="card">
<img class="card-img-top"
src="<?php echo base_url() ?>assets/uploads/files/{{actusHome[0].img}}"
alt="Card image cap">
<div class="card-body">
<p class="card-text">{{actusHome[0].extrait | limitTo: 100 }}{{actusHome[0].extrait.length > 100 ? '...' : ''}}
<a class="cursor" ng-click="readMore(actusHome[0].id)">Voir plus</a></p>
</div>
</div>
<div class="card">
<img class="card-img-top"
src="<?php echo base_url() ?>assets/uploads/files/{{actusHome[1].img}}"
alt="Card image cap">
<div class="card-body">
<p class="card-text">{{actusHome[1].extrait | limitTo: 100 }}{{actusHome[1].extrait.length > 100 ? '...' : ''}}
<a class="cursor" ng-click="readMore(actusHome[1].id)">Voir plus</a></p>
</div>
</div>
<a ng-controller="NavCtrl" ng-click="nav('actus')" class="btn btn-info text-center" role="button">Voir plus d'actus</a>
<br>
</div>
</div>
</div>
</div>
<div class="text-center">
<div class="container-fluid">
<div class="row px-2"></div>
<div class="row px-2">
</div>
<div class="row px-2"></div>
</div>
</div>
</div>
<footer>
<div class="container py-5">
<div class="row">
<div class="col-12 col-md"><i class="fa fa-dot-circle-o fa-lg d-block pt-1"></i>
<small class="d-block my-3 text-muted">© 2017-2018</small>
</div>
<div class="col-6 col-md">
<h5><b>Features</b></h5>
<ul class="list-unstyled text-small">
<li>
<a class="text-muted" href="#">Cool stuff</a>
</li>
<li>
<a class="text-muted" href="#">Random feature</a>
</li>
<li>
<a class="text-muted" href="#">Team feature</a>
</li>
<li>
<a class="text-muted" href="#">Stuff for developers</a>
</li>
<li>
<a class="text-muted" href="#">Another one</a>
</li>
<li>
<a class="text-muted" href="#">Last time</a>
</li>
</ul>
</div>
<div class="col-6 col-md">
<h5><b>Resources</b></h5>
<ul class="list-unstyled text-small">
<li>
<a class="text-muted" href="#">Resource</a>
</li>
<li>
<a class="text-muted" href="#">Resource name</a>
</li>
<li>
<a class="text-muted" href="#">Another resource</a>
</li>
<li>
<a class="text-muted" href="#">Final resource</a>
</li>
</ul>
</div>
<div class="col-6 col-md">
<h5><b>Resources</b></h5>
<ul class="list-unstyled text-small">
<li>
<a class="text-muted" href="#">Business</a>
</li>
<li>
<a class="text-muted" href="#">Education</a>
</li>
<li>
<a class="text-muted" href="#">Government</a>
</li>
<li>
<a class="text-muted" href="#">Gaming</a>
</li>
</ul>
</div>
<div class="col-6 col-md">
<h5><b>About</b></h5>
<ul class="list-unstyled text-small">
<li>
<a class="text-muted" href="#">Team</a>
</li>
<li>
<a class="text-muted" href="#">Locations</a>
</li>
<li>
<a class="text-muted" href="#">Privacy</a>
</li>
<li>
<a class="text-muted" href="#">Terms</a>
</li>
</ul>
</div>
</div>
</div>
<div ng-app="portailClient" ng-controller="SupportCtrl" class="modal fade" id="exampleModal" tabindex="-1"
role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Crée une nouvelle DMS</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="exampleFormControlSelect1">Produit</label>
<select class="form-control" id="exampleFormControlSelect1">
<option ng-repeat="soft in listproduct">{{soft}}</option>
</select>
<label for="exampleInputsujet">Sujet</label>
<small id="tittle" class="form-text text-muted">Titre de votre incident</small>
<input type="text" class="form-control" id="exampleInputsujet" aria-describedby="emailHelp"
placeholder="Titre" ng-model="camping.mail">
<small id="textAera" class="form-text text-muted">Décrivez votre incident</small>
<textarea class="form-control" aria-label="With textarea"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Annuler</button>
<button type="button" ng-click="validate()" class="btn btn-primary" data-dismiss="modal">Valider ma
DMS
</button>
</div>
</div>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="<KEY>"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="<KEY>"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity="<KEY>"
crossorigin="anonymous"></script>
<file_sep>app.controller('NavCtrl', ['$scope', '$location',
function ($scope, $location)
{
$scope.test = 'test du controller';
console.log('test');
$scope.base_url = $location.protocol() + "://" + $location.host()+'/index.php/';
$scope.logout = function () {
location.href = $scope.base_url;
};
$scope.nav = function (slug) {
location.href = $scope.base_url+slug;
};
$scope.openModal = function() {
console.log('test');
var modalInstance = $uibModal.open({
templateUrl: "modalContent.html",
controller: "ModalContentCtrl",
size: '',
});
modalInstance.result.then(function(response){
$scope.result = `${response} button hitted`;
});
};
}
]);
<file_sep><?php
/**
* Created by PhpStorm.
* User: Clement
* Date: 03/05/2019
* Time: 11:07
*/
require_once 'WSSoapClient.php';
class ClientModel extends CI_Model
{
public function login($id, $name)
{
$result = $this->callUser($id);
if ($result->userDetail->nomSiteClient == $name) {
$_SESSION['id'] = $id;
if (isset($result->userDetail->listeProduit)) {
$_SESSION['product'] = $result->userDetail->listeProduit;
} else {
$_SESSION['product'] = null;
}
$_SESSION['name_full'] = $result->userDetail->nomSiteClient;
$_SESSION['name'] = $result->userDetail->nom;
$_SESSION['address1'] = $result->userDetail->adresse1;
$_SESSION['address2'] = $result->userDetail->adresse2;
$_SESSION['postCode'] = $result->userDetail->codePostal;
$_SESSION['family'] = $result->userDetail->famille;
$_SESSION['ville'] = $result->userDetail->ville_1;
if(isset($result->userDetail->telContact))
{
$_SESSION['phone'] = $result->userDetail->telContact;
} else {
$_SESSION['phone'] = null;
}
return true;
} else {
return false;
}
}
public function getResponsableClient()
{
$result = $this->callResponsable();
$result = trim($result, '"');
$getInfo =$this->callUser($result);
$_SESSION['responsable']['nom'] = $getInfo->userDetail->nom;
$_SESSION['responsable']['prenom'] = $getInfo->userDetail->prenom;
$_SESSION['responsable']['mail'] = $getInfo->userDetail->mailContact;
$_SESSION['responsable']['civilite'] = $getInfo->userDetail->civilite;
return $_SESSION['responsable'];
}
private function callUser($id)
{
$options = array(
'userName' => $id
);
$client = new SoapClient("https://my.sequoiasoft.com/akuiteo/WS/UtilisateurWS?wsdl", array('cache_wsdl' => WSDL_CACHE_NONE, 'trace'=> 1 ));
$client->__setSoapHeaders(Array(new WsseAuthHeader("portailSQS", "Clément2019")));
return $result = $client->loadUserDetail($options);
}
private function callResponsable()
{
$options = array(
'arg0' => $_SESSION['id']
);
$client = new SoapClient("https://my.sequoiasoft.com/akuiteo/WS/ClientWS?wsdl", array('cache_wsdl' => WSDL_CACHE_NONE, 'trace'=> 1 ));
$client->__setSoapHeaders(Array(new WsseAuthHeader("portailSQS", "Clément2019")));
$result = $client->getResponsableClient($options);
return $result->return;
}
}
<file_sep>app.controller('ActusCtrl', ['$scope', '$location','ActusFactory',
function ($scope, $location, ActusFactory)
{
$scope.base_url = $location.protocol() + "://" + $location.host()+'/index.php/';
ActusFactory.getActus(null).then(function (data) {
$scope.actus = data;
});
$scope.readMore = function (id) {
location.href = $location.protocol() + "://" + $location.host() + '/index.php/actus/'+id
};
}
]);
<file_sep><div class="container-fluid" ng-controller="ActusCtrl">
<div class="row flex-xl-nowrap">
<div class="col-12 col-md-3 col-xl-2 bd-sidebar">
<h3>Filter les articles</h3>
<div class="md-form active-pink active-pink-2 mb-3 mt-0">
<input class="form-control" type="text" placeholder="Rechercher des articles" aria-label="Search" ng-model='actus.title'>
</div>
</div>
<main class="col-12 col-md-9 col-xl-8 py-md-3 pl-md-5 bd-content">
<div class="row">
<div class="col-md-4" ng-repeat="news in actus">
<div class="card mb-4 border-dark card-height">
<img class="card-img-top" src="<?php echo base_url() ?>assets/uploads/files/{{news.img}}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{news.title}}</h5>
<p class="card-text">{{news.extrait | limitTo: 100 }}{{news.extrait.length > 100 ? '...' : ''}}</p>
<a class="btn btn-dark btn-sm" ng-click="readMore(news.id)">Voir l'article</a>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
| efe2a0ac7a91ae657d7dd82e5be1c91c61b278d0 | [
"JavaScript",
"PHP"
] | 19 | PHP | clementcros/portail-client | 8a374e9d6e635226b690092efc53d5d935354ec1 | c6ca5c6894e2d7aa239b37ccecf0df32277d4aac |
refs/heads/master | <file_sep>package entra21.java.coneccao;
import java.sql.Connection;
import java.sql.DriverManager;
public class Banco {
private static Connection coneccao;
public static Connection conectar() {
try {
Class.forName("com.mysql.jdbc.Driver");
coneccao = DriverManager.getConnection("jdbc.mysql://localhost/filme", "root", "");
return coneccao;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void desconectar() {
if (coneccao != null) {
try {
coneccao.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
<file_sep>package dao;
import entra21.java.bean.FilmeBean;
public class FilmeJUnitTest {
public void testeInserir() {
FilmeBean filme = new FilmeBean();
filme.setNome("O Programador de Programa");
filme.setDiretor("<NAME>");
filme.setCategoria("Ação, Suspense");
filme.setAno((short)1992);
filme.setAtorPrincipal("<NAME>");
filme.setTempoFilme((short)96);
filme.setOrcamento(15000);
filme.setFaturamento(5000);
filme.setFaixaEtaria((short)18);
filme.setLegenda(true);
filme.setDublado(true);
filme.setIdiomaOriginal("Inglês");
}
}
<file_sep>DROP DATABASE IF EXISTS filme;
CREATE DATABASE filme;
USE filme;
CREATE TABLE filmes (
id INT PRIMARY KEY AUTO_INCREMENT,
nome VARCHAR(255) NOT NULL,
diretor VARCHAR(100) NOT NULL,
categoria VARCHAR(255) NOT NULL,
ano SMALLINT NOT NULL,
ator_principal VARCHAR(100) NOT NULL,
tempo_filme SMALLINT NOT NULL,
orcamento DOUBLE NOT NULL,
faturamento DOUBLE NOT NULL,
faixa_etaria SMALLINT NOT NULL,
legenda BOOLEAN NOT NULL,
dublado BOOLEAN NOT NULL,
idioma_original VARCHAR(50) NOT NULL
);
| 4713f180a3a93a06455f24bf21d3f36b2390e241 | [
"Java",
"SQL"
] | 3 | Java | MarcioAugustoInkster/Macarrao | 3e87c86ece8f59799cacd5447003039d53b37956 | f743296e6a9e67f024f2c27826ee4e713699a571 |
refs/heads/main | <repo_name>ashishbehera/ReactJS-Basics<file_sep>/src/AppComponent.js
//import logo from './logo.svg';
import './App.css';
import { ClassComp, ClassComp1 } from './components/ClassComp';
import FunctionalComp from './components/FunctionalComp';
import Click from './components/Click';
import Counter from './components/Counter';
import ParentComp from './components/ParentComp';
function App() {
return (
<div>
<h1>Welcome to the World of React JS!!!</h1>
<h1>This Tutorial is about components</h1>
<FunctionalComp />
<ClassComp />
<ClassComp1 />
<Click />
<Counter />
<ParentComp/>
</div>
);
}
export default App;
| 7b8ee38d6a48777890d5d28572000ad4423d1c90 | [
"JavaScript"
] | 1 | JavaScript | ashishbehera/ReactJS-Basics | 8b5f271d12c27f6ff21189a234d1ace32054fe83 | 182b4e7aec6a27f2bdd8098f723ab3fc79180dcf |
refs/heads/main | <file_sep>DROP TABLE IF EXISTS players;
CREATE TABLE players (
id text,
name text
);
INSERT INTO players (id, name) VALUES
('bilbo', '<NAME>'),
('gandalf', 'Gandalf, il mago bianco'),
('aragorn', 'Aragorn, figlio di Arathorn'),
('sauron', 'Sauron, il signore di Mordor');
DROP TABLE IF EXISTS games;
CREATE TABLE games (
room text ,
player1 text,
player2 text,
session_number int,
show_picture int,
results DEFAULT ''
);
INSERT INTO games
(room, player1, player2, session_number, show_picture) VALUES
('1', 'bilbo', 'gandalf', 10, 20),
('2', 'bilbo', 'aragorn', 10, 0),
('3', 'bilbo', 'sauron', 10, 0),
('4', 'gandalf', 'aragorn', 10, 0),
('5', 'gandalf', 'sauron', 10, 0),
('6', 'aragorn', 'sauron', 10, 0);
<file_sep><!doctype html>
<html lang="en">
<head>
<meta author="<NAME>">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="60">
{% include 'bootstrap_css.html' %}
<title>Admin - Prisoner's Dilemma</title>
</head>
<body>
<div class="container">
<h1>Prisoner's Dilemma</h1>
<h2>Administration</h2>
<p>
<a class="btn btn-primary" href="{{ suffix }}/monitor">Monitor</a>
</p>
<h3>List of URLs</h3>
{{ content }}
</div>
{% include 'bootstrap_js.html' %}
</body>
</html>
<file_sep>
function hide_image(id, laps){
window.timerID = setInterval(function() {
var aOpaque = document.getElementById('imageID').style.opacity;
aOpaque = aOpaque-.1;
aOpaque = aOpaque.toFixed(1);
document.getElementById(id).style.opacity = aOpaque;
if(document.getElementById(id).style.opacity<=0) clearInterval(window.timerID);
}, laps);
}
<file_sep>"""
Prisoner's dilemma web service
proof-of-concept for a Flask web service allowing playing to the prisoner's dilemma
Copyright 2021 <NAME>
"Prisoner's dilemma web service" is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.
"Prisoner's dilemma web service" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not see <http://www.gnu.org/licenses/>.
"""
suffix="/prisoner"
from flask import Flask, render_template, Markup, redirect, request
app = Flask(__name__, static_folder='static', static_url_path=f'{suffix}/static')
app.debug = True
import sqlite3
actions_list = {"C": "cooperate", "D": "defect"}
def payoff(current_player, other_player):
if current_player == "C" and other_player == "C":
return 3
if current_player == "C" and other_player == "D":
return 1
if current_player == "D" and other_player == "C":
return 4
if current_player == "D" and other_player == "D":
return 2
return 0
def results_dict(s):
if s == "":
return {}
else:
return eval(s)
@app.route(f'{suffix}/action/<player_action>/<player_id>/<room_id>/<session_idx>')
def action(player_action, player_id, room_id, session_idx):
if player_action not in actions_list:
return f"action {player_action} not found"
connection = sqlite3.connect("prisoner_dilemma.db")
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute(("SELECT room, player1, player2, session_number, results "
"FROM games WHERE room = ?"),
(room_id, ))
row = cursor.fetchone()
results = results_dict(row["results"])
if session_idx not in results:
results[session_idx] = {}
results[session_idx][player_id] = player_action
cursor.execute("UPDATE games SET results = ? WHERE room = ?",
(str(results), room_id))
connection.commit()
if len(results[session_idx]) < 2:
wait = True
content = ""
else:
wait = False
opponent = row["player1"] if row["player1"] != player_id else row["player2"]
opponent_action = results[session_idx][opponent]
gain = payoff(player_action, opponent_action)
content = (f'You chose to {actions_list[player_action]} and the other partecipant chose to {actions_list[opponent_action]}.<br>'
f"As a result, you earned {gain} points. "
)
return render_template("results.html",
wait=wait,
player_id=player_id,
room_id=room_id,
content=Markup(content),
suffix=suffix
)
@app.route(f'{suffix}/room/<player_id>/<room_id>')
def room(player_id, room_id):
"""
let play a session of room room_id
"""
connection = sqlite3.connect("prisoner_dilemma.db")
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute(("SELECT room, player1, player2, session_number, show_picture, results "
"FROM games WHERE room = ?"),
(room_id, ))
row = cursor.fetchone()
results = results_dict(row["results"])
# find 1st playable session
for session_idx in [str(x) for x in range(1, row["session_number"] + 1)]:
if (session_idx not in results) or (len(results.get(session_idx, {})) < 2):
break
else:
return f'all {row["session_number"]} played'
if session_idx not in results:
results[session_idx] = {}
if player_id in results[session_idx]:
return redirect(f"{suffix}/action/{results[session_idx][player_id]}/{player_id}/{room_id}/{session_idx}")
else:
opponent = row["player1"] if row["player1"] != player_id else row["player2"]
if row["show_picture"]:
picture = (f'<img id="imageID" src="{app.static_url_path}/pictures/{opponent}.jpg">\n'
f'<script src="{app.static_url_path}/hide_image.js"></script>')
# picture = f'<img id="imageID" src="{app.static_url_path}/pictures/{opponent}.jpg">\n'
hide_image = f'<script>window.onload = function() {{ hide_image("imageID", {row["show_picture"] * 1000}); }}</script>'
# hide_image = ""
else:
picture = ""
hide_image = ""
return render_template("room.html",
room_id=room_id,
session_idx=session_idx,
player_id=player_id,
opponent=opponent,
hide_image=Markup(hide_image),
picture=Markup(picture),
suffix=suffix
)
@app.route(f'{suffix}/rooms/<player_id>')
def rooms(player_id):
"""
list all the rooms for the player player_id
"""
connection = sqlite3.connect("prisoner_dilemma.db")
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute(("SELECT room, player1, player2, session_number, results "
"FROM games WHERE player1 = ? OR player2 = ?"),
(player_id, player_id,))
rows = cursor.fetchall()
content = ""
for row in rows:
results = results_dict(row["results"])
# check number of played sessions
played = len([x for x in results if len(results[x]) == 2])
# check if opponent is waiting
opponent_is_waiting = "Yes" if len([x for x in results if len(results[x]) == 1 and player_id not in results[x]]) else "No"
to_be_played = row["session_number"] - played
content += (f'<tr><td><a href="{suffix}/room/{player_id}/{row["room"]}">room #{row["room"]}</a></td>'
f'<td>{row["session_number"]}</td><td>{played}</td><td>{to_be_played}</td>'
f'<td>{opponent_is_waiting}</td>'
'</tr>'
)
if rows:
return render_template("rooms.html",
player_id=player_id,
content=Markup(content),
suffix=suffix)
else:
content += "No more games to play"
return render_template("rooms.html",
player_id=player_id,
content=Markup(content),
suffix=suffix)
@app.route(f'{suffix}/player_id', methods=("POST", "GET"))
def func_player_id():
if request.method == "POST":
player_id = request.form["player_id"]
connection = sqlite3.connect("prisoner_dilemma.db")
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute("SELECT id, name FROM players WHERE id = ?",
(player_id, ))
row = cursor.fetchone()
if not row:
return f"Player {player_id} not found"
return redirect(f"{suffix}/rooms/{player_id}")
'''
return render_template("player.html",
player_id=player_id
)
'''
@app.route(f'{suffix}/admin')
def admin():
"""
administration page
"""
connection = sqlite3.connect("prisoner_dilemma.db")
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
rows = cursor.execute("SELECT id, name FROM players").fetchall()
content = '<table class="table"><thead><tr><th>Players</th><th>Pictures</th><th>URL FOR rooms list</th></tr><thead>'
for row in rows:
content += f'<tr><td>{row["name"]}</td><td><img width="120px" src="{app.static_url_path}/pictures/{row["id"]}.jpg"></td><td>{row["id"]}</td></tr>'
return render_template("admin.html",
content = Markup(content),
suffix=suffix)
@app.route(f'{suffix}/monitor')
def monitor():
"""
monitor all games/sessions
"""
connection = sqlite3.connect("prisoner_dilemma.db")
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
rows = cursor.execute("SELECT room, player1, player2, session_number, show_picture, results FROM games").fetchall()
content = f""
for row in rows:
results = results_dict(row['results'])
n_played = sum([1 for x in results if len(results[x]) == 2])
# pay off
payoff_p1 = 0
payoff_p2 = 0
for x in results:
if len(results[x]) == 2:
payoff_p1 += payoff(results[x][row["player1"]], results[x][row["player2"]])
payoff_p2 += payoff(results[x][row["player2"]], results[x][row["player1"]])
content += (f"Room #{row['room']} "
f"Number of sessions: {row['session_number']} (played: {n_played}) "
f"Show picture of player: {row['show_picture']} s"
)
content += '<table class="table">'
content += '<thead><tr><th>Players</th><th>Points</th><th colspan="25">Sessions</th></tr></thead>'
content += f'<tr><td>{row["player1"]}</td><td>{payoff_p1}</td><td>' + ("</td><td>".join([results[x][row['player1']] for x in results if row['player1'] in results[x]])) + "</td></tr>"
content += f'<tr><td>{row["player2"]}</td><td>{payoff_p2}</td><td>' + ("</td><td>".join([results[x][row['player2']] for x in results if row['player2'] in results[x]])) + "</td></tr>"
content += '</table>'
return render_template("monitor.html",
content = Markup(content),
suffix=suffix)
@app.route(suffix + '/')
@app.route(suffix)
def home():
return render_template("home.html")
if __name__ == "__main__":
app.run(host='0.0.0.0',port=5000) | c5f4f0af48b1565ed55c4895482bb86519d5ff7a | [
"JavaScript",
"SQL",
"Python",
"HTML"
] | 4 | SQL | MartinaBrescini/prisoners_dilemma | 61478c00083a73fefa31cf5920bd26bb98240d21 | 3831eae8504dc44b26e35cd3f86faf683a7ef403 |
refs/heads/master | <repo_name>yinkeet/kubesh<file_sep>/library/aks.py
from subprocess import PIPE, call, check_output
from typing import List
from library.common import WrapPrint, load_environment_variables
from library.kubernetes import Kubernetes
from library.environment import NameFactory
class AKS(Kubernetes):
def __init__(self, info: dict, templates: dict):
super().__init__(info, templates)
self.image_name_factory = NameFactory(
self.templates.get('aks_image_name', 'localhost:5000/$NAMESPACE/$APP/__CONTAINER__') + ':latest'
)
self.short_image_name_factory = NameFactory(
self.templates.get('aks_short_image_name', '$NAMESPACE/$APP/__CONTAINER__') + ':latest'
)
def get_build_image_name(self, container: str) -> str:
image_name = self.image_name_factory.make({'__CONTAINER__': container})
if not self.production:
image_name += ':latest'
else:
with open(container + '/tag') as tag:
image_name += ':' + tag.read()
return image_name
def get_deployment_image_name(self, container: str) -> str:
variables = load_environment_variables(['AZURE_CONTAINER_REGISTRY_NAME'])
image_name = self.short_image_name_factory.make({'__CONTAINER__': container})
if not self.production:
image_name += ':latest'
else:
with open(container + '/tag') as tag:
image_name += ':' + tag.read()
digest = check_output(['az', 'acr', 'repository', 'show', '--name', variables['AZURE_CONTAINER_REGISTRY_NAME'], '--image', image_name, '--query', 'digest', '--output', 'tsv']).decode('UTF-8').replace('\n', '')
return self.get_build_image_name(container) + '@' + digest
def container_built_and_pushed(self, container: str) -> bool:
variables = load_environment_variables(['AZURE_CONTAINER_REGISTRY_NAME'])
image_name = self.short_image_name_factory.make({'__CONTAINER__': container})
with open(container + '/tag') as tag:
image_name += ':' + tag.read()
return call(['az', 'acr', 'repository', 'show', '--name', variables['AZURE_CONTAINER_REGISTRY_NAME'], '--image', image_name], stdout=PIPE, stderr=PIPE) == 0
@WrapPrint('Azure doesn\'t support clean ups... ', 'sorry')
def clean_up(self, containers: List[str]):
pass
def auth(self):
variables = load_environment_variables(['AZURE_APP_ID', 'AZURE_PASSWORD', 'AZURE_TENANT', 'AZURE_CONTAINER_REGISTRY_NAME'])
self._azure_login(variables['AZURE_APP_ID'], variables['AZURE_PASSWORD'], variables['AZURE_TENANT'])
self._azure_acr_login(variables['AZURE_CONTAINER_REGISTRY_NAME'])
@WrapPrint('Logging into azure... ', 'done')
def _azure_login(self, app_id: str, password: str, tenant: str):
call(['az', 'login', '--service-principal', '-u', app_id, '-p', password, '--tenant', tenant], stdout=PIPE)
@WrapPrint('Logging into azure container registry... ', 'done')
def _azure_acr_login(self, name: str):
call(['az', 'acr', 'login', '--name', name], stdout=PIPE)
def cluster(self):
variables = load_environment_variables(['AZURE_RESOURCE_GROUP', 'CLUSTER'])
print('Pointing to azure \'' + variables['CLUSTER'] + '\' cluster... ', end='', flush=True)
call(['az', 'aks', 'get-credentials', '--resource-group', variables['AZURE_RESOURCE_GROUP'], '--name', variables['CLUSTER'], '--overwrite-existing'], stdout=PIPE)
print('done')
<file_sep>/library/docker.py
import os
import sys
from subprocess import PIPE, call, check_output
from typing import List
from library.environment import Environment, NameFactory
class Docker(Environment):
def __init__(self, info: dict, templates: dict):
super().__init__(info, templates)
self.image_name_factory = NameFactory(
self.templates.get('docker_image_name', '__DIRECTORY_NAME_____CONTAINER__')
)
def _build_command(self, command) -> List[str]:
if isinstance(self.deployment_filename, str):
base = ['docker-compose', '-f', self.deployment_filename]
elif isinstance(self.deployment_filename, list) and list:
base = ['docker-compose']
for deployment_filename in self.deployment_filename:
base.extend(['-f', deployment_filename])
else:
raise ValueError('deployment_filename should be str or list')
if isinstance(command, str):
base.append(command)
elif isinstance(command, list) and list:
base.extend(command)
else:
raise ValueError('command should be str or list')
return base
def build(self, containers: List[str]=[]):
command = self._build_command('build')
if containers:
command.extend(containers)
call(command)
def config(self):
print('')
call(self._build_command('config'))
def run(self, containers: List[str]=[]):
command = self._build_command(['up', '-d'])
if containers:
command.extend(containers)
call(command)
def clean_up(self, containers: List[str]=[]):
untagged_images = []
for container in containers:
image_name = self.image_name_factory.make({'__DIRECTORY_NAME__': os.getcwd().split(os.sep)[-1], '__CONTAINER__': container})
untagged_images.extend (
check_output(
['docker', 'images', image_name, '-f', 'dangling=true', '-q']
).decode('UTF-8').splitlines()
)
if untagged_images:
command = ['docker', 'rmi']
command.extend(untagged_images)
call(command, stdout=PIPE)
else:
print('Nothing to clean')
def stop(self, containers: List[str]=[]):
command = self._build_command('stop')
if containers:
command.extend(containers)
call(command)
def logs(self, containers: List[str]=[], pod: str=None, container: str=None, follow: bool=False):
command = self._build_command('logs')
if follow:
command.append('-f')
if containers:
command.extend(containers)
try:
call(command, stderr=PIPE)
except KeyboardInterrupt:
sys.exit(0)
def ssh(self, pod: str=None, container: str=None, command: str=None, args: List[str]=[]):
command = self._build_command(['exec', container, command])
if args:
command.extend(args)
call(command)
<file_sep>/library/minikube.py
import os
import sys
from subprocess import PIPE, CalledProcessError, call, check_output, run
from time import sleep
from typing import List
from library.common import WrapPrint, load_deployment_file, minikube_health_checker
from library.environment import Environment, NameFactory
class Minikube(Environment):
def __init__(self, info: dict, templates: dict):
super().__init__(info, templates)
self.image_name_factory = NameFactory(
self.templates.get('minikube_image_name', 'localhost:5000/$NAMESPACE/$APP/__CONTAINER__') + ':latest'
)
@minikube_health_checker
def build(self, containers=[]):
@WrapPrint('Starting local registry... ', 'done')
def start_local_registry():
call(['docker', 'run', '-d', '-p', '5000:5000', '--name', 'registry', 'registry:2'], stdout=PIPE)
# Local registry health check
while call(['curl', '-s', 'http://' + check_output(['minikube', 'ip']).decode('UTF-8').replace('\n', '') + ':5000']):
sleep(0.1)
@WrapPrint('Stopping local registry... ', 'done')
def stop_local_registry():
call(['docker', 'stop', 'registry'], stdout=PIPE)
call(['docker', 'rm', 'registry'], stdout=PIPE)
start_local_registry()
# Build and push images to local registry
for container in containers:
image_name = self.image_name_factory.make({'__CONTAINER__': container})
call(['docker', 'build', '--force-rm', '--rm', '--file', container + '/' + self.dockerfile_filename, '-t', image_name, os.getcwd() + '/' + container])
call(['docker', 'push', image_name])
stop_local_registry()
@WrapPrint('Loading image names... ', 'done')
def _load_image_names(self, containers):
for container in containers:
image_name = self.image_name_factory.make({'__CONTAINER__': container})
try:
os.environ[container.upper() + '_IMAGE_NAME'] = check_output(['docker', 'image', 'inspect', image_name, '-f', '{{index .RepoDigests 0}}']).decode('UTF-8').replace('\n', '')
except CalledProcessError as e:
pass
@minikube_health_checker
def config(self, containers):
self._load_image_names(containers)
print('\n' + load_deployment_file(self.deployment_filename) + '\n')
@minikube_health_checker
def run(self, containers):
self._load_image_names(containers)
run(['kubectl', 'apply', '-f', '-'], input=load_deployment_file(self.deployment_filename), encoding='UTF-8')
@minikube_health_checker
@WrapPrint('Cleaning up... ', 'done')
def clean_up(self, containers: List[str]):
untagged_images = []
for container in containers:
image_name = self.image_name_factory.make({'__CONTAINER__': container})
untagged_images.extend (
check_output(
['docker', 'images', image_name, '-f', 'dangling=true', '-q']
).decode('UTF-8').splitlines()
)
if untagged_images:
command = ['docker', 'rmi']
command.extend(untagged_images)
call(command, stdout=PIPE)
@minikube_health_checker
def stop(self, containers):
self._load_image_names(containers)
run(['kubectl', 'delete', '-f', '-'], input=load_deployment_file(self.deployment_filename), encoding='UTF-8')
@minikube_health_checker
def namespace(self):
current_context = check_output(['kubectl', 'config', 'current-context']).decode('UTF-8').replace('\n', '')
call(['kubectl', 'config', 'set-context', current_context, '--namespace=' + os.getenv('NAMESPACE')])
@minikube_health_checker
def logs(self, containers=[], pod=None, container=None, follow=False):
command = ['kubectl', 'logs', pod, container]
if follow:
command.append('-f')
try:
call(command)
except KeyboardInterrupt:
print('')
sys.exit(0)
@minikube_health_checker
def ssh(self, pod=None, container=None, command=None, args=None):
command = ['kubectl', 'exec', '-it', pod, '--container=' + container, '--', command]
if args:
command.extend(args)
call(command)
<file_sep>/kubesh.py
#! /usr/bin/env python3
import json
import os
import sys
from argparse import ArgumentParser
from pathlib import Path
# dir_path = os.path.dirname(os.path.realpath(__file__)) + '/'
# sys.path.append(dir_path + 'library')
from library.argparser import KubeshArgumentParser
from library.aks import AKS
from library.common import get_containers_from_yaml, load_environment_file, load_environment_variables
from library.docker import Docker
from library.kubernetes import Kubernetes
from library.gke import GKE
from library.minikube import Minikube
from library.environment import Environment
from library.config import Config
parser = KubeshArgumentParser(Config().settings)
args = parser.run()
Config().environment = args.environment
class_map = {
'docker': Docker,
'minikube': Minikube,
'kubernetes': {
'azure': AKS,
'google': GKE
}
}
klass = class_map[Config().current_setting['type']]
if isinstance(klass, dict):
klass = klass[Config().current_setting['cloud_service']]
instance = klass(Config().current_setting, Config().settings.get('templates', {}))
method = getattr(instance, args.operation)
kwargs = vars(args)
kwargs.pop('environment', None)
kwargs.pop('operation', None)
method(**kwargs)<file_sep>/library/argparser.py
import os
import sys
import yaml
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from subprocess import call
class KubeshArgumentParser():
def __init__(self, settings):
self.settings = settings
self.__parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
epilog='''
Clipboard:
Starting minikube:
minikube start && eval $(minikube docker-env)
Stopping minikube:
minikube stop && eval $(minikube docker-env -u)
'''
)
self.__setup_environment_parsers()
def __setup_environment_parsers(self):
subparsers = self.__parser.add_subparsers(title='Environments', dest='environment', required=True, help='Environment')
for id, setting in self.settings['environments'].items():
parser = subparsers.add_parser(id, help=setting['description'])
self.__setup_operation_parsers(parser, setting['type'], setting['containers']['all'], setting['containers']['buildable'])
def __setup_operation_parsers(self, parent_parser, type, all_containers, buildable_containers):
subparsers = parent_parser.add_subparsers(title='Operations', dest='operation', required=True, help='Operation to execute')
# Build
parser = subparsers.add_parser('build', help='Build, tag and push image(s).')
parser.add_argument('-c', '--containers', nargs='+', choices=buildable_containers, default=buildable_containers, help='Containers to build')
# Config
parser = subparsers.add_parser('config', help='Show deployment config yaml.')
if type != 'docker':
parser.add_argument('--containers', action='store_const', const=False, default=buildable_containers)
# Image pull secret
if type == 'kubernetes':
parser = subparsers.add_parser('image_pull_secret', help='Creates an image pull secret.')
if type == 'docker':
containers = all_containers
else:
containers = buildable_containers
# Run
parser = subparsers.add_parser('run', help='Run deployment.')
parser.add_argument('-c', '--containers', nargs='+', choices=containers, default=containers, help='Containers to run')
# Remove untagged images
parser = subparsers.add_parser('clean_up', help='Remove untagged images.')
parser.add_argument('-c', '--containers', nargs='+', choices=all_containers, default=all_containers, help='Containers to clean')
# Stop
parser = subparsers.add_parser('stop', help='Stop deployment.')
parser.add_argument('-c', '--containers', nargs='+', choices=containers, default=containers, help='Containers to stop')
# Namespace
if type != 'docker':
parser = subparsers.add_parser('namespace', help='Sets kubectl to the environment\'s namespace.')
# Logs
parser = subparsers.add_parser('logs', help='Show logs of container in deployment.')
if type == 'docker':
parser.add_argument('containers', nargs='+', choices=all_containers, help='Containers to show the logs')
else:
parser.add_argument('pod', help='Pod to show the logs')
parser.add_argument('container', choices=all_containers, help='Container to show the logs')
parser.add_argument('-f', '--follow', action='store_true', help='Follow log output')
# SSH
parser = subparsers.add_parser('ssh', help='Tunnel into container of the deployment.')
if type != 'docker':
parser.add_argument('pod', help='Pod to tunnel into')
parser.add_argument('container', choices=all_containers, help='Container to tunnel into')
parser.add_argument('command', help='Command to execute')
parser.add_argument('args', nargs='*', help='Command arguments')
# Auth and cluster
if type == 'kubernetes':
# Auth
subparsers.add_parser('auth', help='Authenticate this machine.')
# Cluster
subparsers.add_parser('cluster', help='Switch cluster.')
def run(self):
return self.__parser.parse_args()
<file_sep>/library/config.py
import json
import os
import sys
import yaml
from pathlib import Path
from subprocess import check_output
from library.common import load_environment_file
class Config(object):
__instance = None
def __new__(cls):
if Config.__instance is None:
Config.__instance = object.__new__(cls)
Config.__instance.__load_kubesh_json()
Config.__instance.__load_containers()
return Config.__instance
@property
def environment(self):
return self._environment
@environment.setter
def environment(self, value: str):
self._environment = value
load_environment_file(self.current_setting['environment_filename'])
@property
def current_setting(self):
return self.settings['environments'][self.environment]
def __load_kubesh_json(self):
if Path("kubesh.json").is_file():
with open('kubesh.json') as data:
self.settings = json.load(data)
else:
if getattr(sys, 'frozen', False):
dir_path = os.path.dirname(os.path.realpath(sys.executable)) + '/'
else:
dir_path = os.path.dirname(os.path.realpath(__file__)) + '/'
with open(dir_path + 'kubesh.json') as data:
self.settings = json.load(data)
def __load_containers(self):
for id, setting in dict(self.settings['environments']).items():
if os.path.isfile(os.getcwd() + '/' + setting['environment_filename']):
load_environment_file(setting['environment_filename'])
if setting['type'] == 'docker':
all_containers = self.__get_docker_compose_containers(setting['deployment_filename'])
else:
all_containers = self.__get_deployment_containers(setting['deployment_filename'])
buildable_containers = self.__filter_buildable_containers(all_containers, setting['dockerfile_filename'])
self.settings['environments'][id]['containers'] = {
'all': all_containers,
'buildable': buildable_containers
}
else:
print('Error \'{}\' not found!'.format(setting['environment_filename']))
del self.settings['environments'][id]
def __get_docker_compose_containers(self, filenames: str):
def get_services(filename: str):
with open(filename, 'r') as stream:
try:
return [service for service, _ in yaml.load(stream, Loader=yaml.Loader)['services'].items()]
except yaml.YAMLError as error:
print(error)
exit(1)
if isinstance(filenames, str):
return get_services(filenames)
elif isinstance(filenames, list) and filenames:
containers = []
for filename in filenames:
for container in get_services(filename):
if container not in containers:
containers.append(container)
return containers
else:
raise ValueError('filenames should be str or list')
def __get_deployment_containers(self, deployment_filename: str):
def default_ctor(loader, tag_suffix, node):
return node.value
containers = []
with open(deployment_filename, 'r') as stream:
string = stream.read()
string = os.path.expandvars(string)
yaml.add_multi_constructor('', default_ctor)
for data in yaml.load_all(string, Loader=yaml.Loader):
if 'kind' in data:
if data['kind'] == 'Deployment':
try:
spec = data['spec']['template']['spec']
if 'initContainers' in spec:
for container in spec['initContainers']:
containers.append(container['name'])
for container in spec['containers']:
containers.append(container['name'])
except KeyError as error:
print(error)
exit(1)
elif data['kind'] == 'CronJob':
try:
spec = data['spec']['jobTemplate']['spec']['template']['spec']
for container in spec['containers']:
containers.append(container['name'])
except KeyError as error:
print(error)
exit(1)
return containers
def __filter_buildable_containers(self, all_containers: list, dockerfile_filename: str):
containers = []
for container in all_containers:
containers.extend(
check_output(
['find', '.', '-type', 'f', '-path', './' + container + '/*', '-maxdepth', '2', '-mindepth' ,'2', '-name', dockerfile_filename]
).decode('UTF-8').replace('./', '').replace('/' + dockerfile_filename, '').splitlines()
)
return containers<file_sep>/library/gke.py
import os
import sys
from subprocess import PIPE, CalledProcessError, call, check_output, run, DEVNULL
from time import sleep
from typing import List
from library.common import WrapPrint, load_environment_variables
from library.environment import NameFactory
from library.kubernetes import Kubernetes
class GKE(Kubernetes):
def __init__(self, info: dict, templates: dict):
super().__init__(info, templates)
self.image_name_factory = NameFactory(
self.templates.get('gcr_image_name', '$CONTAINER_REGISTRY/$PROJECT/$NAMESPACE/$APP/__CONTAINER__')
)
def get_build_image_name(self, container: str) -> str:
image_name = self.image_name_factory.make({'__CONTAINER__': container})
if not self.production:
image_name += ':latest'
else:
with open(container + '/tag') as tag:
image_name += ':' + tag.read()
return image_name
def get_deployment_image_name(self, container: str) -> str:
image_name = self.get_build_image_name(container)
try:
return check_output(['gcloud', 'container', 'images', 'describe', image_name, '--format', 'value(image_summary.fully_qualified_digest)'], stderr=DEVNULL).decode('UTF-8').replace('\n', '')
except CalledProcessError as _error:
return None
# return check_output(['gcloud', 'container', 'images', 'describe', image_name, '--format', 'value(image_summary.fully_qualified_digest)']).decode('UTF-8').replace('\n', '')
def container_built_and_pushed(self, container: str) -> bool:
image_name = self.image_name_factory.make({'__CONTAINER__': container})
with open(container + '/tag') as tag:
image_name += ':' + tag.read()
return call(['gcloud', 'container', 'images', 'describe', image_name], stdout=PIPE, stderr=PIPE) == 0
@WrapPrint('Creating image pull secret... ', 'done')
def image_pull_secret(self):
variables = load_environment_variables([
'IMAGE_PULL_SECRET_NAME', 'IMAGE_PULL_SECRET_SERVER', 'IMAGE_PULL_SECRET_USERNAME', 'IMAGE_PULL_SECRET_PASSWORD', 'IMAGE_PULL_SECRET_EMAIL'
])
name = variables['IMAGE_PULL_SECRET_NAME']
server = variables['IMAGE_PULL_SECRET_SERVER']
username = variables['IMAGE_PULL_SECRET_USERNAME']
with open(variables['IMAGE_PULL_SECRET_PASSWORD']) as text_file:
password = text_file.read()
email = variables['IMAGE_PULL_SECRET_EMAIL']
data = check_output(['kubectl', 'create', 'secret', 'docker-registry', name, '--docker-server', server, '--docker-username', username, '--docker-password', password, '--docker-email', email, '--dry-run', '-o', 'yaml']).decode('UTF-8')
run(['kubectl', 'apply', '-f', '-'], input=data, encoding='UTF-8', stdout=PIPE)
def clean_up(self, containers: List[str]):
untagged_images = []
for container in containers:
image_name = self.image_name_factory.make({'__CONTAINER__': container})
digests = check_output(
['gcloud', 'container', 'images', 'list-tags', image_name, '--filter=-tags:*', '--limit=unlimited', '--format=get(digest)']
).decode('UTF-8').splitlines()
untagged_images.extend(
[image_name + '@' + digest for digest in digests]
)
if untagged_images:
for untagged_image in untagged_images:
command = ['gcloud', 'container', 'images', 'delete', '--quiet', untagged_image]
call(command, stdout=PIPE)
else:
print('Nothing to clean')
def auth(self):
variables = load_environment_variables(['GOOGLE_AUTH_KEY_FILE', 'CONTAINER_REGISTRY'])
call(['gcloud', 'auth', 'activate-service-account', '--key-file', variables['GOOGLE_AUTH_KEY_FILE']])
with open(variables['GOOGLE_AUTH_KEY_FILE']) as text_file:
keyfile = text_file.read()
run(['docker', 'login', '-u', '_json_key', '--password-stdin',
'https://' + variables['CONTAINER_REGISTRY']], input=keyfile, encoding='UTF-8', stdout=PIPE)
def cluster(self):
variables = load_environment_variables(['CLUSTER', 'ZONE', 'PROJECT'])
call(['gcloud', 'container', 'clusters', 'get-credentials', variables['CLUSTER'], '--zone', variables['ZONE'], '--project', variables['PROJECT']])
<file_sep>/requirements.txt
altgraph==0.16.1
astroid==2.0.4
future==0.17.0
isort==4.3.4
lazy-object-proxy==1.3.1
macholib==1.11
mccabe==0.6.1
pefile==2018.8.8
PyInstaller==3.4
pylint==2.1.1
python-dotenv==0.9.1
PyYAML==5.1
six==1.11.0
wrapt==1.10.11
<file_sep>/helper/install_mac
#!/bin/bash
BASH_PROFILE=~/.bash_profile
HOME_PATH="$( cd "$(dirname "$0")" ; pwd -P )"
EXECUTABLE_PATH="$HOME_PATH/kubesh"
# BASH_COMPLETION_PATH="$HOME_PATH/scripts/completion.bash"
# No bash_profile, create it
if [ ! -f $BASH_PROFILE ]
then
touch $BASH_PROFILE
fi
# bash_profile is not empty, append with some newlines
if [ -s $BASH_PROFILE ]; then
printf '\n\n' >> $BASH_PROFILE
fi
printf '# Kubesh PATH\n' >> $BASH_PROFILE
printf 'if [ -f %s ]; then export PATH=%s:$PATH; fi' "'$EXECUTABLE_PATH'" "$HOME_PATH" >> ~/.bash_profile
# printf '\n\n# Kubesh bash completion\n' >> ~/.bash_profile
# printf 'if [ -f %s ]; then source %s; fi' "'$BASH_COMPLETION_PATH'" "'$BASH_COMPLETION_PATH'" >> ~/.bash_profile<file_sep>/make_exec
#!/bin/bash
root_directory=$PWD
# Build Linux executable
docker build -t kubesh_builder_image .
docker run -it --rm --name kubesh_builder -v "$PWD/dist":/usr/src/app/dist -v "$PWD/build":/usr/src/app/build kubesh_builder_image
cp helper/install_linux dist/install
cp kubesh.json dist/kubesh.json
cd $PWD/dist
tar -zcvf kubesh_linux.tar install kubesh kubesh.json
cd $root_directory
# Build MacOS executable
virtualenv kubesh
source kubesh/bin/activate
pip3 install -r requirements.txt
pyinstaller --clean kubesh.spec
cp helper/install_mac dist/install
cp kubesh.json dist/kubesh.json
cd $PWD/dist
tar -zcvf kubesh_mac.tar install kubesh kubesh.json
cd $root_directory
deactivate<file_sep>/library/environment.py
import os
from abc import ABC, abstractmethod
from typing import List
class Environment(ABC):
def __init__(self, info: dict, templates: dict):
super().__init__()
self.deployment_filename = info['deployment_filename']
self.dockerfile_filename = info['dockerfile_filename']
self.production = info['production']
self.templates = templates
@abstractmethod
def build(self, containers: List[str]=[]):
pass
@abstractmethod
def config(self):
pass
@abstractmethod
def run(self, containers: List[str]=[]):
pass
@abstractmethod
def clean_up(self, containers: List[str]=[]):
pass
@abstractmethod
def stop(self, containers: List[str]=[]):
pass
@abstractmethod
def logs(self, containers: List[str]=[], pod: str=None, container: str=None, follow: bool=False):
pass
@abstractmethod
def ssh(self, pod: str=None, container: str=None, command: str=None, args: List[str]=[]):
pass
class NameFactory(object):
def __init__(self, template: str):
self.template = template
def make(self, map: dict):
name = os.path.expandvars(self.template)
for k, v in map.items():
name = name.replace(k, v)
return name<file_sep>/library/common.py
import os
from functools import partial, wraps
from subprocess import CalledProcessError, check_output
from sys import exit
import yaml
from dotenv import load_dotenv
class WrapPrint(object):
def __init__(self, prefix, suffix):
self.prefix = prefix
self.suffix = suffix
def __call__(self, func):
def wrapper(*args, **kwargs):
print(self.prefix, end='', flush=True)
result = func(*args,**kwargs)
print(self.suffix)
return result
return wrapper
def load_environment_file(filename: str):
# Load general .env file
env_path = os.getcwd() + '/.env'
load_dotenv(dotenv_path=env_path, override=True)
# Load specific .env file
env_path = os.getcwd() + '/' + filename
load_dotenv(dotenv_path=env_path, override=True)
def load_environment_variables(variables=[]):
failed = False
results = {}
for variable in variables:
value = os.getenv(variable)
if value is None:
failed = True
print(variable + ' is not set')
else:
results[variable] = value
if failed:
exit(1)
return results
@WrapPrint('Loading deployment file... ', 'done')
def load_deployment_file(deployment_filename: str):
with open(deployment_filename, 'r') as deployment_file:
data = deployment_file.read()
return os.path.expandvars(data)
def minikube_health_checker(func):
def wrapper(*args, **kwargs):
try:
status = check_output(['minikube', 'status', '--format', '{{.Host}}']).decode('UTF-8')
except CalledProcessError as error:
status = error.output.decode('UTF-8')
if status != 'Running':
print('Minikube is not running, start it by running this command:')
print('minikube start && eval $(minikube docker-env)')
exit(1)
func(*args, **kwargs)
return wrapper
def get_services(deployment_filename: str):
with open(deployment_filename, 'r') as stream:
try:
return [service for service, details in yaml.load(stream, Loader=yaml.Loader)['services'].items()]
except yaml.YAMLError as error:
print(error)
exit(1)
def get_containers(dockerfile_filename):
return check_output(
['find', '.', '-type', 'f', '-maxdepth', '2', '-mindepth' ,'2', '-name', dockerfile_filename]
).decode('UTF-8').replace('./', '').replace('/' + dockerfile_filename, '').splitlines()
def get_containers_from_yaml(deployment_filename):
containers = []
with open(deployment_filename, 'r') as stream:
for data in yaml.safe_load_all(stream):
if 'kind' in data and data['kind'] == 'Deployment':
try:
spec = data['spec']['template']['spec']
if 'initContainers' in spec:
for container in spec['initContainers']:
containers.append(os.path.expandvars(container['name']))
for container in spec['containers']:
containers.append(os.path.expandvars(container['name']))
except KeyError as error:
print(error)
exit(1)
return containers<file_sep>/Dockerfile
FROM python:3.7
# RUN apk update && apk upgrade && apk add --no-cache zlib-dev musl-dev libc-dev gcc
WORKDIR /usr/src/app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY kubesh.py .
COPY kubesh.linux.spec .
COPY library library
ENTRYPOINT [ "pyinstaller", "--clean", "kubesh.linux.spec" ]<file_sep>/library/kubernetes.py
import os
import sys
from abc import abstractmethod
from subprocess import PIPE, call, check_output, run
from library.common import WrapPrint, load_deployment_file, load_environment_variables
from library.environment import Environment
class Kubernetes(Environment):
@abstractmethod
def get_build_image_name(self, container: str) -> str:
pass
@abstractmethod
def get_deployment_image_name(self, container: str) -> str:
pass
@abstractmethod
def container_built_and_pushed(self, container: str) -> bool:
pass
def build(self, containers):
for container in containers:
image_name = self.get_build_image_name(container)
if not (self.production and self.container_built_and_pushed(container)):
call(['docker', 'build', '--force-rm', '--no-cache', '--rm', '--file', container + '/' + self.dockerfile_filename, '-t', image_name, os.getcwd() + '/' + container])
call(['docker', 'push', image_name])
else:
print('Image ' + image_name + ' has already been built and pushed to the cloud.')
@WrapPrint('Loading image names... ', 'done')
def _load_image_names(self, containers):
for container in containers:
container_image_name = self.get_deployment_image_name(container)
if container_image_name:
os.environ[container.upper() + '_IMAGE_NAME'] = container_image_name
def config(self, containers):
self._load_image_names(containers)
print('\n' + load_deployment_file(self.deployment_filename) + '\n')
@WrapPrint('Creating image pull secret... ', 'done')
def image_pull_secret(self):
variables = load_environment_variables([
'IMAGE_PULL_SECRET_NAME', 'IMAGE_PULL_SECRET_SERVER', 'IMAGE_PULL_SECRET_USERNAME', 'IMAGE_PULL_SECRET_PASSWORD', 'IMAGE_PULL_SECRET_EMAIL'
])
name = variables['IMAGE_PULL_SECRET_NAME']
server = variables['IMAGE_PULL_SECRET_SERVER']
username = variables['IMAGE_PULL_SECRET_USERNAME']
password = variables['IMAGE_PULL_SECRET_PASSWORD']
email = variables['IMAGE_PULL_SECRET_EMAIL']
data = check_output(['kubectl', 'create', 'secret', 'docker-registry', name, '--docker-server', server, '--docker-username', username, '--docker-password', <PASSWORD>, '--docker-email', email, '--dry-run', '-o', 'yaml']).decode('UTF-8')
run(['kubectl', 'apply', '-f', '-'], input=data, encoding='UTF-8', stdout=PIPE)
def run(self, containers):
self._load_image_names(containers)
run(['kubectl', 'apply', '-f', '-'], input=load_deployment_file(self.deployment_filename), encoding='UTF-8')
def stop(self, containers):
self._load_image_names(containers)
run(['kubectl', 'delete', '-f', '-'], input=load_deployment_file(self.deployment_filename), encoding='UTF-8')
def namespace(self):
current_context = check_output(['kubectl', 'config', 'current-context']).decode('UTF-8').replace('\n', '')
call(['kubectl', 'config', 'set-context', current_context, '--namespace=' + os.getenv('NAMESPACE')])
def logs(self, containers=[], pod=None, container=None, follow=False):
command = ['kubectl', 'logs', pod, container]
if follow:
command.append('-f')
try:
call(command)
except KeyboardInterrupt:
print('')
sys.exit(0)
def ssh(self, pod=None, container=None, command=None, args=None):
command = ['kubectl', 'exec', '-it', pod, '--container=' + container, '--', command]
if args:
command.extend(args)
call(command)
@abstractmethod
def auth(self):
pass
@abstractmethod
def cluster(self):
pass<file_sep>/helper/completion.bash
#/usr/bin/env bash
_completions() {
HOME_PATH=$(which kubesh | sed -e 's|/kubesh||')
source "$HOME_PATH/.env"
if [ -f "kubesh.env" ]; then
source "kubesh.env"
fi
# Merge docker, minikube abd kube environments into one
MINIKUBE_AND_KUBE_ENVIRONMENTS=( "${MINIKUBE_ENVIRONMENTS[@]}" "${KUBE_ENVIRONMENTS[@]}" )
ALL_ENVIRONMENTS=( "${DOCKER_ENVIRONMENTS[@]}" "${MINIKUBE_AND_KUBE_ENVIRONMENTS[@]}" )
# Evaluate all environments
for i in "${ALL_ENVIRONMENTS[@]}"
do
eval $i
done
source "$HOME_PATH/scripts/variables.env"
source "$HOME_PATH/scripts/common.sh"
if [ "${#COMP_WORDS[@]}" -eq "2" ]; then
_main_completions
elif [ "${#COMP_WORDS[@]}" -eq "3" ]; then
_environments_completions
elif [ "${#COMP_WORDS[@]}" -eq "4" ]; then
if [ "${COMP_WORDS[2]}" == "$BUILD" ]; then
_build_completions
# elif [ "${COMP_WORDS[2]}" == "$SSH" ]; then
elif [ "${COMP_WORDS[2]}" == "$LOG" ]; then
_log_completions
fi
fi
}
complete -F _completions kubesh
_main_completions() {
local environment
local environments=()
for environment in "${ALL_ENVIRONMENTS[@]}"
do
IFS='=' read -ra strings <<< "$environment"
environments+=( ${strings[1]} )
done
local helpers=( "$DOCKER $GCLOUD $KUBERNETES" )
COMPREPLY=($(compgen -W "${environments[*]}" "${COMP_WORDS[1]}"))
COMPREPLY+=($(compgen -W "${helpers[*]}" "${COMP_WORDS[1]}"))
}
_environments_completions() {
local args
contains ${COMP_WORDS[1]} ${DOCKER_ENVIRONMENTS[@]}
if [ $? -eq 1 ]; then
args=( "$BUILD $RUN $STOP $SSH $LOG $LS" )
fi
contains ${COMP_WORDS[1]} ${MINIKUBE_ENVIRONMENTS[@]}
if [ $? -eq 1 ]; then
args=( "$BUILD $RUN $STOP $SSH $LOG $LS $URL" )
fi
contains ${COMP_WORDS[1]} ${KUBE_ENVIRONMENTS[@]}
if [ $? -eq 1 ]; then
args=( "$CLUSTER_COMMAND $BUILD $RUN $STOP $SSH $LOG $LS $URL" )
fi
if [ "${COMP_WORDS[1]}" == "$DOCKER" ]; then
args=( "$CLEANUP $KILL" )
fi
if [ "${COMP_WORDS[1]}" == "$GCLOUD" ]; then
args=( "$AUTH" )
fi
if [ "${COMP_WORDS[1]}" == "$KUBERNETES" ]; then
args=( "$IMAGE_PULL_SECRET" )
fi
COMPREPLY=($(compgen -W "${args[*]}" "${COMP_WORDS[2]}"))
}
_build_completions() {
load_containers ${COMP_WORDS[1]}
COMPREPLY=($(compgen -W "${CONTAINERS[*]}" "${COMP_WORDS[3]}"))
}
_log_completions() {
env_file=$(get_config ${COMP_WORDS[1]} "_ENV" ${ALL_ENVIRONMENTS[@]})
if [ -f $env_file ]; then
source $env_file
local pod_array=($(kubectl get pods -o json | jq '.items[].metadata.name' | grep $APP))
local i
local args=()
for i in "${pod_array[@]}"
do
i="${i%\"}"
i="${i#\"}"
args+=( $i )
done
COMPREPLY=($(compgen -W "${args[*]}" "${COMP_WORDS[3]}"))
fi
} | ba7d7ccd7e684277e644d1afe8acfacdf7d1d81e | [
"Python",
"Text",
"Dockerfile",
"Shell"
] | 15 | Python | yinkeet/kubesh | 1994beb62a726c9413bc89a20befe51ad6da601d | dd3689753d2d0c288efd5a2ecdcce00189320f15 |
refs/heads/master | <file_sep># -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.define "lamp" do |lamp|
lamp.vm.network :private_network, ip: "172.21.12.10"
lamp.vm.box = "ubuntu/xenial64"
lamp.vm.hostname = "lamp"
lamp.vm.synced_folder "./html", "/var/www/html"
end
config.vm.provider "virtualbox" do |vb|
vb.memory = "512"
end
config.vm.provision "shell" do |s|
s.name = "install lamp-server"
s.path = "provision.sh"
end
end
<file_sep># Vagrant-Create-Lamp
- Vagrant 2.2.4
- Version 5.2.28
```
git clone https://github.com/ahmadajis/Vagrant-Create-Lamp.git Vagrant_Lamp
cd Vagrant_Lamp
Vagrant up
```
<file_sep>#!/bin/bash
# Allow SSH Password Authentication
sed -i -e 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
systemctl restart sshd.service
# Update
apt-get update -y
apt-get upgrade -y
apt-get dist-upgrade -y
# Install MySQL
echo "mysql-server mysql-server/root_password password vagrant" | debconf-set-selections
echo "mysql-server mysql-server/root_password_again password vagrant" | debconf-set-selections
apt-get install -y mysql-server
# Install Apache & PHP
apt-get install -y apache2 php libapache2-mod-php php-mcrypt php-mysql
# Install PHPMyAdmin
echo "phpmyadmin phpmyadmin/internal/skip-preseed boolean true" | debconf-set-selections
echo "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2" | debconf-set-selections
echo "phpmyadmin phpmyadmin/dbconfig-install boolean true" | debconf-set-selections
echo "phpmyadmin phpmyadmin/app-password-confirm password <PASSWORD>" | debconf-set-selections
echo "phpmyadmin phpmyadmin/mysql/admin-pass password <PASSWORD>" | debconf-set-selections
echo "phpmyadmin phpmyadmin/mysql/app-pass password <PASSWORD>" | debconf-set-selections
apt-get install -y phpmyadmin
# Securing Apache & PHP
sed -i -e 's/ServerTokens OS/ServerTokens Prod/g' /etc/apache2/conf-available/security.conf
sed -i -e 's/ServerSignature On/ServerSignature Off/g' /etc/apache2/conf-available/security.conf
sed -i -e 's/expose_php = On/expose_php = Off/g' /etc/php/7.0/cli/php.ini
systemctl restart apache2.service
# Remove unused package & files
apt-get autoremove -y
apt-get clean
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* | 0f410b2d6111779498534a4fcb73194cc8002f45 | [
"Markdown",
"Ruby",
"Shell"
] | 3 | Ruby | santoadji21/Vagrant-Create-Lamp | 1597791b185eb27544dc8da46672f00354a193f8 | be5d5d9e1cf8e92fbc8172efec36fb8b106e809a |
refs/heads/master | <repo_name>thesyncim/go-tarutil<file_sep>/README.md
go-tarutil
==========
tar utility to compress directories
<file_sep>/archive.go
package tarutil
import (
"archive/tar"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
type MakeTar struct {
Input string //directory or file
TarWriter *tar.Writer //
TarHdr *tar.Header //reusable file header
}
func NewTarFromDir(input string) *MakeTar {
return &MakeTar{
Input: input,
TarHdr: &tar.Header{},
TarWriter: &tar.Writer{},
}
}
func (c *MakeTar) WriteTo(w io.Writer) (err error) {
c.TarWriter = tar.NewWriter(w)
err = filepath.Walk(c.Input, func(path string, fi os.FileInfo, err error) error {
if fi.IsDir() {
return nil
}
name := path[len(c.Input):]
if strings.HasPrefix(name, string(filepath.Separator)) {
name = name[1:]
}
target, _ := os.Readlink(path)
c.TarHdr, err = tar.FileInfoHeader(fi, target)
if err != nil {
return err
}
c.TarHdr.Name = name
err = c.TarWriter.WriteHeader(c.TarHdr)
if err != nil {
return fmt.Errorf("Error writing file %q: %v", name, err)
}
r, err := os.Open(path)
if err != nil {
return err
}
defer r.Close()
_, err = io.Copy(c.TarWriter, r)
return err
})
if err != nil {
return err
}
if err := c.TarWriter.Close(); err != nil {
return err
}
return nil
}
| b3c2c073b15a604f4b262faa4cfb160f62e90d1b | [
"Markdown",
"Go"
] | 2 | Markdown | thesyncim/go-tarutil | 9a4011636ac2991f65e43f82fbb41a720cd1e63f | 59f1d7c11bf37f5033b57f3a1d41ae9771c3c498 |
refs/heads/master | <file_sep>export const ROUTES = {
main: "/dashboard",
users: "/users",
agents: "/agents",
maintenance: "/maintenance",
category: "/category",
activity: "/activity",
publication: '/publication',
orders: "/orders",
customers: "/customers",
inventory: "/inventory",
};
<file_sep>import { DrawerItem } from '../ts';
import { ROUTES } from './routes';
import DashboardIcon from '@material-ui/icons/Dashboard';
import CollectionsBookmarkIcon from '@material-ui/icons/CollectionsBookmark';
import PeopleRoundedIcon from '@material-ui/icons/PeopleRounded';
import AccountBoxRoundedIcon from '@material-ui/icons/AccountBoxRounded';
import AlternateEmailRoundedIcon from '@material-ui/icons/AlternateEmailRounded';
import SettingsRoundedIcon from '@material-ui/icons/SettingsRounded';
import ViewHeadlineRoundedIcon from '@material-ui/icons/ViewHeadlineRounded';
export const DRAWER_LIST: DrawerItem[] = [
{
route: ROUTES.main,
literal: 'Dashboard',
Icon: DashboardIcon,
},
{
route: ROUTES.users,
literal: 'Users',
Icon: PeopleRoundedIcon
},
{
route: ROUTES.publication,
literal: 'Publication',
Icon: CollectionsBookmarkIcon
},
{
route: ROUTES.agents,
literal: 'Agents',
Icon: AccountBoxRoundedIcon
},
{
route: ROUTES.category,
literal: 'Category/Tags',
Icon: AlternateEmailRoundedIcon
},
{
route: ROUTES.maintenance,
literal: 'Maintenance',
Icon: SettingsRoundedIcon
},
{
route: ROUTES.activity,
literal: 'Activity Log',
Icon: ViewHeadlineRoundedIcon
}
]
| 8533d17eb8499cce2d8d4d53bacfde18844f3e9b | [
"TypeScript"
] | 2 | TypeScript | DavidAkinJames/Gains-FrontEnd-Task | 8cc7b2ab26da5a8a5e1560e16832164be1a220f1 | 9b59e28075a8d19224d5b2b9b102643cd40b8eaf |
refs/heads/master | <repo_name>irori/BlokusFS<file_sep>/src/Makefile
FUSEFLAGS = $(shell pkg-config fuse --cflags)
FUSELIBS = $(shell pkg-config fuse --libs)
CXXFLAGS = $(FUSEFLAGS) -O2 -Wall
blokusfs: blokusfs.o board.o opening.o piece.o
$(CXX) $(CXXFLAGS) -o $@ $^ $(FUSELIBS)
piece.cpp: piece.rb
ruby piece.rb >$@
blokusfs.o: blokusfs.cpp board.h opening.h
board.o: board.cpp piece.h opening.h board.h
opening.o: opening.cpp opening.h
piece.o: piece.cpp piece.h
clean:
rm -f *.o blokusfs
<file_sep>/interface/play
#!/bin/sh
set -e
usage() {
echo "Usage: $0 [-v violet_prog] [-o orange_prog] blokusfs_root"
exit 1
}
is_dir() {
test -d $1
}
is_violet_turn() {
expr $turn % 2 = 0 >/dev/null
}
show_board() {
echo " 123456789ABCDE"
perl -ne 's/1+/\x1B[45m$&\x1B[0m/g; s/2+/\x1B[43m$&\x1B[0m/g; printf("%X %s", $., $_)' $dir/board
echo 'violet\norange' |paste - $dir/score $dir/piece |awk -F '\t' '{print $1, "(" $2 "):", $3}'
}
get_move() {
if is_violet_turn && [ "$violet_prog" != "" ]; then
echo "Violet is thinking..."
move=`DIR=$dir $violet_prog`
echo "violet($(($turn + 1))): $move"
return
fi
if ! is_violet_turn && [ "$orange_prog" != "" ]; then
echo "Orange is thinking..."
move=`DIR=$dir $orange_prog`
echo -n "orange($(($turn + 1))): $move"
return
fi
while true; do
echo
if is_violet_turn; then
echo -n "violet($(($turn + 1))): "
else
echo -n "orange($(($turn + 1))): "
fi
read move
if [ -d "$dir/$move" ]; then
return
fi
echo "$move: invalid move"
done
}
game_end() {
show_board $dir
read vscore <$dir/score
oscore=`tail -n1 $dir/score`
[ $vscore -gt $oscore ] && echo "Game End - Violet wins!"
[ $vscore -lt $oscore ] && echo "Game End - Orange wins!"
[ $vscore -eq $oscore ] && echo "Game End - Draw"
}
while getopts v:o: OPT; do
case $OPT in
v) violet_prog="$OPTARG" ;;
o) orange_prog="$OPTARG" ;;
\?) usage
esac
done
shift $((OPTIND - 1))
if [ "$1" = "" ]; then usage; fi
dir=$1
if [ ! -d "$dir" ]; then
echo "$0: $dir is not a directory" 1>&2
exit 1
fi
turn=0
while is_dir $dir/????; do
show_board $dir
get_move
if [ ! -d "$dir/$move" ]; then
echo "$move: invalid move"
exit 1
fi
dir="$dir/$move"
echo $dir
turn=$(($turn + 1))
done
game_end
<file_sep>/ai/negaalpha.mk
# Negaalpha search
# usage: make -f ai/negaalpha.mk DIR=blokusfs_dir [DEPTH=N]
.SILENT:
ifndef DIR
$(error Please set DIR= parameter)
endif
DEPTH := 2
depth-1 := $(word $(DEPTH), 0 1 2 3 4 5 6 7 8 9)
ifeq ($(MAKELEVEL), $(depth-1))
negaalpha: $(DIR)
awk 'BEGIN{getline < "$(RESULT)"; b=$$3; x=-99999} {v=-$$1;if(x<v){x=v;if(b<=x){exit 0}}} END{print x > "$(RESULT)"}' $(DIR)/*/value || cp $(DIR)/value $(RESULT)
else
ifeq ($(MAKELEVEL), 0)
RESULT := $(shell mktemp)
$(shell echo -99999 -99999 99999 >$(RESULT))
endif
tempfile := $(shell mktemp)
subdirs := $(wildcard $(DIR)/????)
.PHONY: negaalpha $(subdirs)
negaalpha: $(subdirs)
rm $(tempfile)
ifeq ($(words $(subdirs)), 0)
cp $(DIR)/value $(RESULT)
endif
ifeq ($(MAKELEVEL), 0)
cat $(RESULT) 1>&2
awk '{print $$4}' $(RESULT)
rm $(RESULT)
endif
$(subdirs):
awk '{print -99999,-$$3,-$$2}' $(RESULT) >$(tempfile)
-$(MAKE) -f ai/negaalpha.mk DIR=$@ RESULT=$(tempfile) >/dev/null
awk 'BEGIN{getline < "$(tempfile)"; v=-$$1} {print v<$$1?$$1:v, v<$$2?$$2:v, $$3, v<=$$1?$$4:"$(@F)" >"$(RESULT)"; if ($$3<=v) {system("rm $(tempfile)"); exit 1} }' $(RESULT)
endif
<file_sep>/src/blokusfs.cpp
#define FUSE_USE_VERSION 26
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include "board.h"
using std::string;
Move parse_move(string fourcc)
{
if (fourcc == "----")
return PASS;
int x, y, d;
char c;
if (fourcc.length() == 4 &&
sscanf(fourcc.c_str(), "%1X%1X%c%1d", &x, &y, &c, &d) == 4 &&
x >= 1 && x <= 14 && y >= 1 && y <= 14 &&
tolower(c) >= 'a' && tolower(c) <= 'u' &&
d >= 0 && d <= 7)
return Move(fourcc.c_str());
else
return INVALID_MOVE;
}
bool parse_path(const char* path, Board* b, string* name)
{
if (path[0] != '/')
return false;
if (path[1] == '\0') {
name->clear();
return true;
}
std::istringstream ss(path + 1);
string s;
while (std::getline(ss, s, '/') && !ss.eof()) {
Move m = parse_move(s);
if (m == INVALID_MOVE || !b->is_valid_move(m))
return false;
b->do_move(m);
}
*name = s;
return true;
}
string score(const Board& b)
{
char buf[64];
sprintf(buf, "%d\n%d\n", b.violet_score(), b.orange_score());
return string(buf);
}
string value(const Board& b)
{
char buf[64];
sprintf(buf, "%d\n", b.nega_eval());
return string(buf);
}
int blokus_getattr(const char *path, struct stat *stbuf)
{
memset(stbuf, 0, sizeof(struct stat));
Board b;
string name;
if (!parse_path(path, &b, &name))
return -ENOENT;
if (name.empty()) {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
return 0;
} else if (name == "board") {
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
stbuf->st_size = 14 * 15;
return 0;
} else if (name == "piece") {
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
stbuf->st_size = b.pieces().length();
return 0;
} else if (name == "score") {
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
stbuf->st_size = score(b).length();
return 0;
} else if (name == "value") {
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
stbuf->st_size = value(b).length();
return 0;
} else {
Move m = parse_move(name);
if (m != INVALID_MOVE && b.is_valid_move(m)) {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
return 0;
}
}
return -ENOENT;
}
int blokus_readdir(const char *path,
void *buf,
fuse_fill_dir_t filler,
off_t offset,
struct fuse_file_info *fi)
{
Board b;
string name;
if (!parse_path(path, &b, &name))
return -ENOENT;
if (!name.empty()) {
Move m = parse_move(name);
if (m == INVALID_MOVE || !b.is_valid_move(m))
return -ENOENT;
b.do_move(m);
}
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
filler(buf, "board", NULL, 0);
filler(buf, "piece", NULL, 0);
filler(buf, "score", NULL, 0);
filler(buf, "value", NULL, 0);
Move movables[1500];
int nmove = b.movables(movables);
if (nmove == 1 && movables[0] == PASS) {
b.do_pass();
int n = b.movables(movables);
if (n == 1 && movables[0] == PASS)
return 0; // End of the game
movables[0] = PASS;
}
for (int i = 0; i < nmove; i++)
filler(buf, movables[i].fourcc().c_str(), NULL, 0);
return 0;
}
int blokus_read(const char *path,
char *buf,
size_t size,
off_t offset,
struct fuse_file_info *fi)
{
Board b;
string name;
if (!parse_path(path, &b, &name))
return -ENOENT;
string content;
if (name == "board")
content = b.to_str();
else if (name == "piece")
content = b.pieces();
else if (name == "score")
content = score(b);
else if (name == "value")
content = value(b);
else
return -ENOENT;
size_t len = content.length();
if (static_cast<size_t>(offset) < len) {
if ((offset + size) > len)
size = len - offset;
memcpy(buf, content.c_str() + offset, size);
} else {
size = 0;
}
return size;
}
static struct fuse_operations blokus_oper;
int main(int argc, char *argv[])
{
blokus_oper.getattr = blokus_getattr;
blokus_oper.readdir = blokus_readdir;
blokus_oper.read = blokus_read;
return fuse_main(argc, argv, &blokus_oper, NULL);
}
<file_sep>/ai/negamax.mk
# Negamax search
# usage: make -f ai/negamax.mk DIR=blokusfs_dir [DEPTH=N]
.SILENT:
ifndef DIR
$(error Please set DIR= parameter)
endif
DEPTH := 2
depth-1 := $(word $(DEPTH), 0 1 2 3 4 5 6 7 8 9)
ifeq ($(MAKELEVEL), $(depth-1))
negamax: $(DIR)
(sort -n $(DIR)/*/value || cat $(DIR)/value) |head -n1
else
subdirs := $(wildcard $(DIR)/????)
.PHONY: negamax $(subdirs)
ifeq ($(words $(subdirs)), 0)
negamax:
cat $(DIR)/value
else
tempfile := $(shell mktemp)
negamax: $(subdirs)
ifeq ($(MAKELEVEL), 0)
sort -r -n $(tempfile) |head -n1 |cut -f2
else
sort -r -n $(tempfile) |head -n1 |sed -e 's/^/-/' -e 's/^--//'
endif
rm $(tempfile)
$(subdirs):
ifeq ($(MAKELEVEL), 0)
$(MAKE) DIR=$@ -f ai/negamax.mk |sed 's/$$/ $(@F)/' >>$(tempfile)
else
$(MAKE) DIR=$@ -f ai/negamax.mk >>$(tempfile)
endif
endif
endif
<file_sep>/ai/negaalpha.sh
#!/bin/sh
# Negaalpha search
set -e
usage() {
echo "usage: $0 blokusfs_dir [depth]" 1>&2
exit 1
}
negaalpha() { # args: node depth alpha beta
if [ $2 -eq 0 ]; then
read result < $1/value
else
local best=99999
local alpha=$3
local best_move
local m
cd -- $1
for m in ????; do
if [ $m = "????" ]; then
# no children - game end
read result < value # FIXME: use score instead of value
m="----"
else
negaalpha $m $(($2 - 1)) $((- $4)) $((- $alpha))
fi
if [ $result -lt $best ]; then
best=$result
best_move=$m
if [ $2 -eq $initial_depth ]; then echo $best_move $best 1>&2; fi
if [ $result -lt $alpha ]; then
alpha=$result
if [ $alpha -le $4 ]; then
result=$(($best * -1))
cd ..
return
fi
fi
fi
done
cd ..
result=$(($best * -1))
result_move=$best_move
fi
}
if [ "$1" != "" ]; then
dir="$1"
else
[ "$DIR" = "" ] && usage
dir="$DIR"
fi
if [ ! -d "$dir" ]; then
echo "$0: $dir is not a directory" 1>&2
exit 1
fi
initial_depth=${2-2}
negaalpha "$dir" $initial_depth 99999 -99999
echo $result_move
| f56ba5cf9c48bc43d3ce7b6643b1ed103aeb5363 | [
"Makefile",
"C++",
"Shell"
] | 6 | Makefile | irori/BlokusFS | 3d280651a50094ba6901f4753343510fadc74077 | 90ca07f6c80a023edf4552fb839f25c97c46ca0f |
refs/heads/master | <file_sep>package io.github.hobbstech.fuel_station_locator_backend;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FuelLevelUpdateRestController {
private final FuelUpdaterService fuelUpdaterService;
public FuelLevelUpdateRestController(FuelUpdaterService fuelUpdaterService) {
this.fuelUpdaterService = fuelUpdaterService;
}
@PostMapping("/v1/fuel-level")
public void updateFuel(@RequestBody UpdateFuelDto updateFuelDto){
fuelUpdaterService.updateFuelStatus(updateFuelDto);
}
}
| 799bbc2a4e1f1b99613a510b897ca2d14fd7194a | [
"Java"
] | 1 | Java | hobbstech/fuel-store-locator-backend | aaf165f1cfd27b2e3b1d0d2f39867a0300c3caa6 | 9a50c8e31dec09d89c8816b1ecef7e90f3de1091 |
refs/heads/master | <repo_name>TThanushan/space-td<file_sep>/Space TD/Assets/Assets/Scripts/SpawnerScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnerScript : MonoBehaviour {
public static SpawnerScript instance;
public Transform spawnPosition;
public EnemyType[] enemyTypes;
public BossType[] bossTypes;
public int numberOfWaves;
public int enemiesRemainingAlive;
public int currentWaveNumber = 0;
// [HideInInspector]
public int enemiesNumberToSpawn;
// [HideInInspector]
public int enemiesRemainingToSpawn;
// [HideInInspector]
public float nextWaveTime;
PoolObjectScript poolScript;
public bool allWavesDone = false;
void Awake()
{
if (instance == null)
instance = this;
poolScript = GameObject.FindGameObjectWithTag("Data").GetComponent<PoolObjectScript>();
}
void Start ()
{
nextWaveTime = 10;
if (numberOfWaves > 0)
NextWaveFunc();
}
void Update ()
{
if (UIScript.instance.playerLoose)
return;
foreach (EnemyType _currentEnemyType in enemyTypes)
{
SpawnEnemiesFunc(_currentEnemyType);
}
SpawnBoss();
NextWaveFunc();
if (nextWaveTime > 0 && enemiesRemainingAlive <= 0 && enemiesRemainingToSpawn <= 0)
nextWaveTime -= Time.deltaTime;
}
void SpawnEnemiesFunc(EnemyType currentEnemyType)
{
if (currentWaveNumber < currentEnemyType.waveStart)
return;
if (Time.time >= currentEnemyType.nextEnemySpawnTime && currentEnemyType.enemyCount > 0)
{
currentEnemyType.enemyCount--;
enemiesRemainingToSpawn--;
enemiesRemainingAlive++;
currentEnemyType.nextEnemySpawnTime = Time.time + currentEnemyType.timeBetweenSpawn;
GameObject newUnit = poolScript.GetPoolObject(currentEnemyType.enemie);
newUnit.GetComponent<ProgressBarScript>().currentHealth = newUnit.GetComponent<ProgressBarScript>().maxHealth;
newUnit.GetComponent<ProgressBarScript>().OnDeath += OnEnemyDeath;
newUnit.transform.position = spawnPosition.position;
}
}
int GetEnemyTypeWeight(float weight)
{
int enemyNumber = (int)(enemiesNumberToSpawn * weight);
if (enemyNumber < 1)
{
enemyNumber = 1;
}
return enemyNumber;
}
void OnEnemyDeath()
{
enemiesRemainingAlive--;
}
void IsThereWavesRemaining()
{
//Is there waves remaining ?
if (currentWaveNumber >= numberOfWaves )
{
allWavesDone = true;
nextWaveTime = 0;
return;
}
}
void IsThisTheLastWave()
{
if (currentWaveNumber == numberOfWaves - 1)
{
UIScript.instance.DisplayText("Last Wave !!!", new Vector2(0, 0), 15, Color.red, true);
nextWaveTime = 0;
}
}
void NextWaveFunc()
{
IsThereWavesRemaining();
if (enemiesRemainingAlive <= 0 && enemiesRemainingToSpawn <= 0 && nextWaveTime <= 0)
{
if (allWavesDone)
{
currentWaveNumber++;
return;
}
currentWaveNumber++;
if(currentWaveNumber != numberOfWaves - 1)
nextWaveTime = 10;
enemiesNumberToSpawn = currentWaveNumber + 10;
foreach (EnemyType currentEnemyType in enemyTypes)
{
if (currentEnemyType.waveStart > currentWaveNumber)
continue;
currentEnemyType.enemyCount = GetEnemyTypeWeight(currentEnemyType.weight);
enemiesRemainingToSpawn += currentEnemyType.enemyCount;
}
}
}
[System.Serializable]
public class EnemyType
{
public GameObject enemie;
public int waveStart;
public float weight;
public float timeBetweenSpawn;
public int enemyCount;
public float nextEnemySpawnTime;
}
[System.Serializable]
public class BossType
{
public GameObject enemie;
public int waveStart;
public bool bossIsDead = false;
}
void SpawnBoss()
{
foreach (BossType _currentBossType in bossTypes)
{
if (_currentBossType.bossIsDead == false && currentWaveNumber >= _currentBossType.waveStart)
{
enemiesRemainingAlive++;
GameObject newUnit = poolScript.GetPoolObject(_currentBossType.enemie);
newUnit.GetComponent<ProgressBarScript>().currentHealth = newUnit.GetComponent<ProgressBarScript>().maxHealth;
newUnit.GetComponent<ProgressBarScript>().OnDeath += OnEnemyDeath;
newUnit.transform.position = spawnPosition.position;
_currentBossType.bossIsDead = true;
}
if (_currentBossType.bossIsDead == false && enemiesRemainingAlive <= 0 && enemiesRemainingToSpawn <= 0 && currentWaveNumber >= _currentBossType.waveStart - 1 && GameObject.FindGameObjectWithTag("SpecialText") == null)
{
UIScript.instance.DisplayText("Warning Boss Incoming !", new Vector2(0, -8), 10, Color.red, true);
AudioManager.instance.Play("SMS2", false);
}
}
}
}
<file_sep>/README.md
# space-td
Tower defense game, project first started in 2017
<file_sep>/Space TD/Assets/Assets/Scripts/PoolObjectScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolObjectScript : MonoBehaviour {
public static PoolObjectScript instance;
[Header("Data")]
public GameObject[] enemies;
public GameObject endNode;
public string enemyTag;
[Space(30)]
[Space]
//Size to start with.
public int poolSize;
public List<GameObject> unitPool;
Transform binTransform;
void Start () {
binTransform = GameObject.FindGameObjectWithTag("Bin").GetComponent<Transform>();
endNode = GameObject.FindGameObjectWithTag("End");
}
void Update () {
FindEnemyFunc();
}
void FindEnemyFunc()
{
enemies = GameObject.FindGameObjectsWithTag("Enemy");
}
public GameObject GetPoolObject(GameObject unitP)
{
// print(unitP.name);
foreach (GameObject currentUnit in unitPool)
{
if (currentUnit.activeInHierarchy == false && currentUnit.name == unitP.name)
{
currentUnit.SetActive(true);
return currentUnit;
}
}
GameObject newUnit = (GameObject)Instantiate(unitP, transform.position, transform.rotation, binTransform);
newUnit.name = unitP.name;
newUnit.SetActive(true);
unitPool.Add(newUnit);
return newUnit;
}
void Awake()
{
if (instance != null)
return;
instance = this;
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/DisableScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisableScript : MonoBehaviour {
public float destroyTime = 1f;
void OnEnable() {
Invoke("Destroy", destroyTime);
}
void Update () {
}
void Destroy()
{
gameObject.SetActive(false);
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/TurretBluePrintScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class TurretBluePrintScript{
public GameObject prefab;
public int cost;
public GameObject upgradePrefab;
public int upgradeCost;
public int GetSellAmount(bool _upgraded)
{
if (!_upgraded)
{
return (int)(cost * 0.8f);
}
else
return (int)((cost + upgradeCost) * 0.8f);
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/SpecialFuncScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpecialFuncScript : MonoBehaviour {
public static SpecialFuncScript instance;
// Use this for initialization
void Awake() {
if (instance == null)
instance = this;
}
// Update is called once per frame
void Update () {
}
public static void DisplayPanel(Animator anim, GameObject gameObject)
{
if (gameObject.activeSelf == false)
gameObject.SetActive(true);
if (!anim.GetBool("Display"))
{
anim.SetBool("Display", true);
}
else
{
anim.SetBool("Display", false);
}
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/UIScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class UIScript : MonoBehaviour {
public static UIScript instance;
public GameObject printedText;
public GameObject impactEffect;
public GameObject deathEffect;
public GameObject bossDeathEffect;
public GameObject skipButton;
public Color orangeColor;
public GameObject restartSprite;
public GameObject gameoverPanel;
public GameObject looseEffect;
public GameObject endNode;
public GameObject burnEnemyEffect;
public GameObject electricEnemyEffect;
public GameObject slowEnemyEffect;
public GameObject gameCompleteEffect;
public bool playerLoose = false;
public float newMainVolume = 0.01f;
public Camera camera;
//Fade Restart.
public SpriteRenderer black;
public Animator anim;
//Fade Restart.
//GameOver Panel.
public Animator gameOverAnim;
public GameObject gameOverPanel;
//GameOver Panel.
//Option
public Animator optionAnim;
public GameObject optionPanel;
//FPS Var.
public float fps;
float deltaTime;
bool showFPS = false;
//Button image
public Image standardTurretImage;
public Image fastTurretImage;
public Image multiTurretImage;
public Image slowTurretImage;
public Image burnTurretImage;
public Image electricTurretImage;
public Image superMultiTurretImage;
public Image laserTurretImage;
Text lifeText;
Text moneyText;
Text waveNumberText;
Text waveTimeText;
float cameraSizeSave;
bool gameComplete = false;
void Awake() {
lifeText = gameObject.transform.Find("lifeText").GetComponent<Text>();
moneyText = gameObject.transform.Find("moneyText").GetComponent<Text>();
waveNumberText = gameObject.transform.Find("waveNumber").GetComponent<Text>();
waveTimeText = gameObject.transform.Find("waveTime").GetComponent<Text>();
endNode = GameObject.FindGameObjectWithTag("End").gameObject;
if (gameOverPanel == null)
gameoverPanel = GameObject.Find("GameOver Panel").gameObject;
if (gameOverAnim == null)
gameoverPanel.GetComponent<Animator>();
if (instance == null)
instance = this;
}
void Start()
{
camera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}
void Update () {
lifeText.text = PlayerStatsScript.instance.life.ToString();
moneyText.text = PlayerStatsScript.instance.money.ToString() + " $";
waveNumberText.text = "Wave : " + SpawnerScript.instance.currentWaveNumber.ToString();
if (SpawnerScript.instance.nextWaveTime > 0 && SpawnerScript.instance.enemiesRemainingAlive <= 0 && SpawnerScript.instance.enemiesRemainingToSpawn <= 0)
{
skipButton.SetActive(true);
waveTimeText.text = "Next Wave : " + SpawnerScript.instance.nextWaveTime.ToString("0");
}
else
{
skipButton.SetActive(false);
waveTimeText.text = "";
}
MainGameOverFunc();
PlayerInputs();
HighlightTowerButton(standardTurretImage, ShopScript.instance.standardTurret.cost);
HighlightTowerButton(fastTurretImage, ShopScript.instance.fastTurret.cost);
HighlightTowerButton(multiTurretImage, ShopScript.instance.multiTurret.cost);
HighlightTowerButton(slowTurretImage, ShopScript.instance.slowTurret.cost);
HighlightTowerButton(burnTurretImage, ShopScript.instance.burnTurret.cost);
HighlightTowerButton(electricTurretImage, ShopScript.instance.electricTurret.cost);
HighlightTowerButton(superMultiTurretImage, ShopScript.instance.superMultiTurret.cost);
HighlightTowerButton(laserTurretImage, ShopScript.instance.laserTurret.cost);
if (SpawnerScript.instance.currentWaveNumber >= SpawnerScript.instance.numberOfWaves + 1 && gameComplete == false)
StartCoroutine(GameComplete());
}
void PlayerInputs()
{
if (Input.GetKeyDown(KeyCode.F))
showFPS = !showFPS;
}
void HighlightTowerButton(Image _image, float _cost)
{
if (_image == null)
return;
if (_cost <= PlayerStatsScript.instance.money)
_image.color = new Color(0f, 0.352f, 0.176f);
else
_image.color = Color.black;
}
public GameObject DisplayImpactEffect(GameObject effect)
{
if (effect == null)
return null;
GameObject newEffect = PoolObjectScript.instance.GetPoolObject(effect);
return newEffect;
}
void MainGameOverFunc()
{
//If the player got 0 or less life then instantiate effect and display the gameOver panel.
if (PlayerStatsScript.instance.life <= 0 && !playerLoose)
{
PoolObjectScript.instance.GetPoolObject(looseEffect).transform.position = endNode.transform.position;
AudioManager.instance.Play("Boom3", false);
Time.timeScale = 0.2f;
Invoke("GameOverFunc", 1f);
playerLoose = true;
ShakeCamera.instance.Shake(0.2f, 0.5f);
}
}
public void ChangeMainVolume(float _volume)
{
AudioManager.instance.ChangeMainVolume(_volume);
}
void HideUI(bool value)
{
if(value)
transform.position = new Vector3(transform.position.x, transform.position.y, -10);
else
transform.position = new Vector3(transform.position.x, transform.position.y, 0);
}
public void SpeedButton(Transform spriteGroup)
{
if (Time.timeScale == 1)
{
spriteGroup.Find("Sprite1").gameObject.SetActive(true);
spriteGroup.Find("Sprite2").gameObject.SetActive(true);
spriteGroup.Find("Sprite3").gameObject.SetActive(false);
Time.timeScale = 1.7f;
}
else if (Time.timeScale == 1.7f)
{
spriteGroup.Find("Sprite1").gameObject.SetActive(true);
spriteGroup.Find("Sprite2").gameObject.SetActive(true);
spriteGroup.Find("Sprite3").gameObject.SetActive(true);
Time.timeScale = 2.3f;
}
else
{
spriteGroup.Find("Sprite1").gameObject.SetActive(true);
spriteGroup.Find("Sprite2").gameObject.SetActive(false);
spriteGroup.Find("Sprite3").gameObject.SetActive(false);
Time.timeScale = 1;
}
}
public void MuteSfxVolume(GameObject _image)
{
AudioManager.instance.MuteSfxVolume(_image);
}
public void MuteMusicVolume(GameObject _image)
{
AudioManager.instance.MuteMusicVolume(_image);
}
void GameOverFunc()
{
gameoverPanel.transform.Find("waveNumber").GetComponent<Text>().text = waveNumberText.text;
SpecialFuncScript.DisplayPanel(gameOverAnim, gameoverPanel);
}
public void SkipWaveTime()
{
int moneyGiven = (int)(SpawnerScript.instance.nextWaveTime) * 2;
PlayerStatsScript.instance.money += moneyGiven;
DisplayText("+" + moneyGiven.ToString() + "$", new Vector2(0, 8), 10, Color.green);
SpawnerScript.instance.nextWaveTime = 0;
AudioManager.instance.Play("Tiny Button", true);
}
public void StartOption()
{
StartCoroutine(Option());
AudioManager.instance.Play("Jump", true);
}
IEnumerator Option()
{
if (Time.timeScale != 0)
{
SpecialFuncScript.DisplayPanel(optionAnim, optionPanel);
yield return new WaitUntil(() => optionAnim.GetCurrentAnimatorStateInfo(0).IsName("Over"));
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
SpecialFuncScript.DisplayPanel(optionAnim, optionPanel);
}
}
public void StartRestart(int sceneIndex)
{
Time.timeScale = 1;
StartCoroutine(Restart(SceneManager.GetActiveScene().buildIndex));
AudioManager.instance.Play("Jump", true);
}
public void Quit(int sceneIndex)
{
Time.timeScale = 1;
StartCoroutine(Restart(sceneIndex));
AudioManager.instance.Play("Jump", true);
}
IEnumerator GameComplete()
{
Time.timeScale = 1;
HideUI(true);
gameComplete = true;
PoolObjectScript.instance.GetPoolObject(gameCompleteEffect).transform.position = GameObject.FindGameObjectWithTag("SpawnerNode").gameObject.transform.position;
AudioManager.instance.Play("Boom3", false);
anim.SetBool("Fade", true);
yield return new WaitUntil(() => black.color.a == 1);
SceneManager.LoadScene(2);
}
IEnumerator Restart(int sceneIndex)
{
HideUI(true);
anim.SetBool("Fade", true);
yield return new WaitUntil(()=>black.color.a == 1);
SceneManager.LoadScene(sceneIndex);
}
public void DisplayText(string text, Vector2 textPosition, int textSize, Color textColor, bool special = false)
{
if(special == false)
printedText = Resources.Load("PrintedTextCanvas") as GameObject;
else
printedText = Resources.Load("PrintedTextCanvas Special") as GameObject;
GameObject newCanvasTextG = PoolObjectScript.instance.GetPoolObject(printedText);
GameObject newTextG = newCanvasTextG.transform.Find("Text").gameObject;
newTextG.GetComponent<Text>().text = text;
newTextG.GetComponent<Text>().color = textColor;
newCanvasTextG.transform.position = textPosition;
newTextG.transform.localScale = new Vector2(textSize, textSize);
// newTextG.GetComponent<Text>().color = textColor;
}
void OnGUI()
{
if (!showFPS || Time.timeScale == 0)
return;
int w = Screen.width, h = Screen.height;
Rect rect = new Rect(0, 700, w, h);
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.UpperLeft;
style.fontSize = h * 2 / 100;
style.normal.textColor = new Color(1f, 1f, 1f, 1f);
deltaTime += (Time.deltaTime - deltaTime) * 0.1f;
float msec = deltaTime * 1000.0f;
fps = 1.0f / deltaTime;
string text = string.Format("{0:0.0} ms ({1:0.} fps)", msec, fps);
GUI.Label(rect, text, style);
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/PathPointsScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathPointsScript : MonoBehaviour {
public Transform[] points;
void Awake ()
{
//Create a new array with X length.
points = new Transform[transform.childCount];
//Add each of them in the array.
for (int i = 0; i < points.Length; i++)
{
points[i] = gameObject.transform.GetChild(i);
}
}
void Update () {
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/BulletScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript : MonoBehaviour {
public float attackRange = 1;
public float moveSpeed = 1;
public float attackDamage = 1;
public GameObject target;
void Start () {
}
void FixedUpdate()
{
AttackTarget();
}
void Update () {
MoveToTarget();
}
void MoveToTarget()
{
if (target != null)
{
Vector2 dir = target.transform.position - transform.position;
transform.Translate(dir.normalized * moveSpeed * Time.deltaTime);
}
}
void AttackTarget()
{
Vector2 dir = target.transform.position - transform.position;
float distanceThisFrame = moveSpeed * Time.deltaTime;
if(dir.magnitude <= distanceThisFrame)
{
if (target.GetComponent<ProgressBarScript>() == null)
{
gameObject.SetActive(false);
return;
}
target.GetComponent<ProgressBarScript>().currentHealth -= attackDamage;
gameObject.SetActive(false);
// UIScript.instance.DisplayImpactEffect(UIScript.instance.impactEffect).transform.position = transform.position;
// AudioManager.instance.Play("HitSFX2", true);
}
if(target == null)
{
gameObject.SetActive(false);
// UIScript.instance.DisplayImpactEffect(UIScript.instance.impactEffect).transform.position = transform.position;
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/Special/SpawnObject.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnObject : MonoBehaviour {
public GameObject[] prefabs;
public float timeBetweenSpawn = 1;
public Transform positionA;
public Transform positionB;
public float sizeA;
public float sizeB;
//Does it need to choose a prefab randomly ?
public bool randomPrefabs;
//Does it need to generate a random position for the prefabs ?
public bool randomPos;
public bool randomSize;
float positionX;
float positionY;
void Start () {
InvokeRepeating("SpawnPrefabFunc", 0f, timeBetweenSpawn);
}
void Update () {
}
void SpawnPrefabFunc()
{
if (positionA == null && positionB == null)
return;
GameObject newPrefab = null;
if (randomPrefabs)
{
int i = Random.Range(0, prefabs.Length);
newPrefab = PoolObjectScript.instance.GetPoolObject(prefabs[i]);
}
else
{
foreach (GameObject currentPrefabs in prefabs)
newPrefab = PoolObjectScript.instance.GetPoolObject(currentPrefabs);
}
RandomPosition(newPrefab);
RandomSize(newPrefab);
}
void RandomSize(GameObject newPrefabs)
{
if (randomSize)
{
float newRandomSize = Random.Range(sizeA, sizeB);
newPrefabs.transform.localScale = new Vector2(newRandomSize, newRandomSize);
}
}
void RandomPosition(GameObject newPrefabs)
{
if (randomPos)
{
positionX = Random.Range(positionA.position.x, positionB.position.x);
positionY = Random.Range(positionA.position.y, positionB.position.y);
newPrefabs.transform.position = new Vector2(positionX, positionY);
}
else
newPrefabs.transform.position = new Vector2(positionA.position.x, positionA.position.y);
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/ButtonScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonScript : MonoBehaviour {
public string clipName = "Balloon Popping";
void OnMouseEnter()
{
if (clipName == "")
return;
print("pop");
AudioManager.instance.Play(clipName, true);
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/ClearTrailRendererScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClearTrailRendererScript : MonoBehaviour {
void Start () {
}
void OnDisable()
{
if (GetComponent<TrailRenderer>() == true)
{
GetComponent<TrailRenderer>().Clear();
}
}
void Update () {
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/BuildManagerScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class BuildManagerScript : MonoBehaviour {
public GameObject standardTurretPrefabs;
public GameObject FastTurretPrefab;
public GameObject MultiTurretPrefab;
public static BuildManagerScript instance;
private TurretBluePrintScript turretToBuild;
private Node selectedNode;
public NodeUI nodeUI;
public bool mouseOverNode;
private void Update()
{
if (!mouseOverNode && Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
{
print("close");
nodeUI.Hide();
}
}
void Awake()
{
nodeUI = GameObject.Find("NodeUI").GetComponent<NodeUI>();
if (instance != null)
{
print("There is already a build Manager !");
return;
}
else
instance = this;
}
public bool CanBuild{ get { return turretToBuild != null; } }
public bool HasMoney { get { return PlayerStatsScript.instance.money >= turretToBuild.cost; } }
public void SetTurretToBuild(TurretBluePrintScript turret)
{
turretToBuild = turret;
DeselectNode();
}
public void SetTurretToBuild(GameObject turret, int cost)
{
turretToBuild = new TurretBluePrintScript();
turretToBuild.prefab = turret;
turretToBuild.cost = cost;
}
public Node GetSelectedNode
{
get
{
return selectedNode;
}
}
public void DeselectNode()
{
selectedNode = null;
nodeUI.Hide();
}
public void SelectNode(Node node)
{
if (selectedNode == node)
{
DeselectNode();
return;
}
selectedNode = node;
nodeUI.SetTarget(node);
}
public TurretBluePrintScript GetTurretToBuild()
{
return turretToBuild;
}
void Start () {
turretToBuild = ShopScript.instance.standardTurret;
// SetTurretToBuild(standardTurretPrefabs, 15);
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/ProgressBarScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class ProgressBarScript : MonoBehaviour {
public enum Type{basic, Boss}
public Type type = Type.basic;
public float maxHealth;
public float currentHealth;
public GameObject Healthbar;
public Text healthText;
public float moneyGiven;
public event System.Action OnDeath;
void OnEnable()
{
Healthbar.transform.localScale = new Vector3(0, Healthbar.transform.localScale.y, Healthbar.transform.localScale.z);
currentHealth = maxHealth;
}
void Start () {
currentHealth = maxHealth;
}
void Update () {
if(Healthbar != null)
SetHealthBarFunc();
if (healthText)
healthText.text = (System.Math.Round(currentHealth,1)).ToString();
Death();
}
void Death()
{
if (currentHealth <= 0)
{
if (OnDeath != null)
{
OnDeath();
OnDeath = null;
}
gameObject.SetActive(false);
if (type == Type.basic)
{
//Given money When i die.
if (moneyGiven > 0)
{
UIScript.instance.DisplayText("+" + moneyGiven + " $", transform.position, 6, Color.green);
PlayerStatsScript.instance.money += moneyGiven;
}
UIScript.instance.DisplayImpactEffect(UIScript.instance.deathEffect).transform.position = transform.position;
AudioManager.instance.Play("Slime Splash", true);
}
else if (type == Type.Boss)
{
//Given money When i die.
if (moneyGiven > 0)
{
UIScript.instance.DisplayText("+" + moneyGiven + " $", transform.position, 18, Color.green);
PlayerStatsScript.instance.money += moneyGiven;
}
UIScript.instance.DisplayImpactEffect(UIScript.instance.bossDeathEffect).transform.position = transform.position;
AudioManager.instance.Play("Boom", true);
ShakeCamera.instance.Shake(0.5f, 1f);
}
}
}
void OnDisable()
{
if (OnDeath != null)
{
OnDeath();
OnDeath = null;
}
}
void SetHealthBarFunc()
{
float barLenght = currentHealth / maxHealth;
Healthbar.transform.localScale = new Vector3(barLenght, Healthbar.transform.localScale.y, Healthbar.transform.localScale.z);
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/NodeUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NodeUI : MonoBehaviour {
private Node target;
public GameObject uI;
public GameObject rangeSprite;
public static NodeUI instance;
public GameObject upgradeEffect;
public GameObject SellingEffect;
void Awake()
{
if (instance == null)
instance = this;
}
void Start()
{
rangeSprite = transform.Find("Canvas/Range Sprite").gameObject;
uI = transform.Find("Canvas/Buttons").gameObject;
if (target == null)
Hide();
}
void Update()
{
}
public Node GetTarget
{
get
{
return target;
}
}
public void SetTarget(Node _node)
{
target = _node;
Text upgradeText = transform.Find("Canvas/Buttons/UpgradeButton/Text").GetComponent<Text>();
Text sellText = transform.Find("Canvas/Buttons/SellButton/Text").GetComponent<Text>();
// sellText.text = BuildManagerScript.instance.GetTurretToBuild().GetSellAmount(_node.isUpgraded).ToString() + "$";
sellText.text = _node.turretBlueprint.GetSellAmount(_node.isUpgraded) + "$";
if(!target.isUpgraded)
upgradeText.text = _node.turretBlueprint.upgradeCost.ToString() + "$";
else
upgradeText.text = "Done";
transform.position = target.GetBuildPosition();
uI.SetActive(true);
DisplayTurretRange(target ,true);
}
public void Hide()
{
if(target != null)
DisplayTurretRange(target, false);
uI.SetActive(false);
}
public void Upgrade()
{
target.UpgradeTurret();
Text sellText = transform.Find("Canvas/Buttons/SellButton/Text").GetComponent<Text>();
sellText.text = BuildManagerScript.instance.GetTurretToBuild().GetSellAmount(target.isUpgraded).ToString() + "$";
}
public void Sell()
{
target.SellTurret();
}
public void DisplayTurretRange(Node _node, bool state)
{
//If the _node is null or the rangeSprite is disable.
if (_node == null || rangeSprite.activeSelf == false || _node.turret == null)
return;
// 1.65f
rangeSprite.transform.position = _node.turret.transform.position;
if (state == true)
{
rangeSprite.transform.localScale = new Vector3(_node.turret.GetComponent<TowerScript>().attackRange * 200,
_node.turret.GetComponent<TowerScript>().attackRange * 200, 0);
}
else
rangeSprite.transform.localScale = Vector3.zero;
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/AudioManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class AudioManager : MonoBehaviour {
public static AudioManager instance;
public List<Sound> sounds;
public bool musicMuted = false;
public bool SFXMuted = false;
void Start()
{
Play("Theme", false);
Play("Brown Noise Ambient", false);
if (instance == null)
instance = this;
else
{
Destroy(gameObject);
return;
}
AudioListener.volume = 0.10f;
}
void Update()
{
}
void Awake()
{
DontDestroyOnLoad(gameObject);
for (int i = 0; i < 1; i++)
{
foreach (Sound s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
}
public void Play(string _name, bool randomPitch)
{
if (SFXMuted == true)
return;
Sound newS = sounds.Find(Sound => Sound.name == _name && Sound.name == _name && Sound.source.isPlaying == false);
//Was the sound already playing ?
if (newS == null)
{
//Get a model of the sound.
Sound s = sounds.Find(Sound => Sound.name == _name);
if (s != null)
{
//Create and add the new Sound to the list.
newS = AddSound(s.name, s.clip, s.volume, s.pitch, s.loop);
}
//It means that the name is wrong !
else
{
Debug.LogWarning("Sound name : " + _name + " not found !");
return;
}
}
if (newS != null)
{
if (randomPitch == true)
newS.source.pitch = UnityEngine.Random.Range(0.8f, 1.8f);
newS.source.Play();
}
}
public void MuteSfxVolume(GameObject _image)
{
SFXMuted = !SFXMuted;
if (_image != null)
{
_image.SetActive(SFXMuted);
}
}
public void MuteMusicVolume(GameObject _image)
{
sounds.Find(Sound => Sound.name == "Theme").source.mute = !sounds.Find(Sound => Sound.name == "Theme").source.mute;
sounds.Find(Sound => Sound.name == "Brown Noise Ambient").source.mute = !sounds.Find(Sound => Sound.name == "Brown Noise Ambient").source.mute;
musicMuted = !musicMuted;
if (_image != null)
{
_image.SetActive(musicMuted);
}
}
public void ChangeMainVolume(float _volume)
{
AudioListener.volume = _volume;
}
Sound AddSound(string name, AudioClip clip, float volume, float pitch, bool loop)
{
Sound s = new Sound();
s.source = gameObject.AddComponent<AudioSource>();
s.name = name;
s.clip = clip;
s.volume = volume;
s.pitch = pitch;
s.loop = loop;
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
sounds.Add(s);
return s;
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/MoveScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveScript : MonoBehaviour {
public float moveSpeedX = 1;
public float moveSpeedY = 0;
public int wayX = 1;
public int wayY = 1;
void Update () {
transform.Translate(new Vector2(moveSpeedX * wayX * Time.deltaTime, moveSpeedY * wayY * Time.deltaTime));
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/MenuScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MenuScript : MonoBehaviour {
public Animator creditsAnim;
public GameObject credits;
public Animator fadeAnim;
public SpriteRenderer black;
void Start () {
}
void Update () {
}
public void StartPlay(int sceneIndex)
{
StartCoroutine(Play(sceneIndex));
}
public void ShowPanel(GameObject panel)
{
panel.SetActive(!panel.activeSelf);
}
IEnumerator Play(int sceneIndex)
{
fadeAnim.SetBool("Fade", true);
AudioManager.instance.Play("Jump", true);
yield return new WaitUntil(() => black.color.a == 1);
SceneManager.LoadScene(sceneIndex);
}
public void Quit()
{
Application.Quit();
}
public void StartDisplayCredits()
{
AudioManager.instance.Play("Jump", true);
if (credits.activeSelf == false)
credits.SetActive(true);
if (!creditsAnim.GetBool("Display"))
{
creditsAnim.SetBool("Display", true);
}
else
{
creditsAnim.SetBool("Display", false);
}
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/Node.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Node : MonoBehaviour {
[Header ("Color Settings")]
public Color highLightColor;
public Color buildHighLightColor;
public Vector3 positionOffSet;
public float colorLerpSpeed;
[HideInInspector]
public GameObject turret;
[HideInInspector]
public TurretBluePrintScript turretBlueprint;
[HideInInspector]
public bool isUpgraded = false;
BuildManagerScript buildManager;
SpriteRenderer sprite;
//First color of the sprite.
Color startColor;
bool lerpActivated = false;
float startTime;
float t;
void Start()
{
buildManager = BuildManagerScript.instance;
}
void Update()
{
//Change the color of the sprite.
ColorLerp(startColor, highLightColor);
}
void Awake()
{
lerpActivated = false;
if (gameObject.GetComponent<SpriteRenderer>() != null)
{
sprite = gameObject.GetComponent<SpriteRenderer>();
startColor = sprite.color;
}
}
void BuildTurret(TurretBluePrintScript bluePrint)
{
if (PlayerStatsScript.instance.money >= bluePrint.cost && bluePrint.prefab != null)
{
UIScript.instance.DisplayText("-" + bluePrint.cost.ToString() + " $", Camera.main.ScreenToWorldPoint(Input.mousePosition), 6, UIScript.instance.orangeColor);
PlayerStatsScript.instance.money -= bluePrint.cost;
GameObject newTurret = PoolObjectScript.instance.GetPoolObject(bluePrint.prefab);
newTurret.transform.position = transform.position;
turret = newTurret;
turretBlueprint = bluePrint;
DisplayEffect(NodeUI.instance.upgradeEffect);
AudioManager.instance.Play("Cash Register", true);
ShakeCamera.instance.Shake(0.1f, 0.05f);
}
else
{
AudioManager.instance.Play("SMS", false);
UIScript.instance.DisplayText("Not enough money !", Camera.main.ScreenToWorldPoint(Input.mousePosition), 6, Color.red);
}
}
public void UpgradeTurret()
{
if (isUpgraded == true)
{
UIScript.instance.DisplayText("Upgrade Done !", Camera.main.ScreenToWorldPoint(Input.mousePosition) + Vector3.up, 6, Color.red);
AudioManager.instance.Play("SMS", false);
}
else if (PlayerStatsScript.instance.money >= turretBlueprint.upgradeCost && turretBlueprint.upgradePrefab != null)
{
UIScript.instance.DisplayText("-" + turretBlueprint.upgradeCost.ToString() + " $", Camera.main.ScreenToWorldPoint(Input.mousePosition), 6, UIScript.instance.orangeColor);
PlayerStatsScript.instance.money -= turretBlueprint.upgradeCost;
//Get rid of the old turret.
turret.SetActive(false);
turret = null;
//Build a new one.
GameObject newTurret = PoolObjectScript.instance.GetPoolObject(turretBlueprint.upgradePrefab);
newTurret.transform.position = transform.position;
turret = newTurret;
isUpgraded = true;
NodeUI.instance.DisplayTurretRange(NodeUI.instance.GetTarget, true);
NodeUI.instance.SetTarget(this);
//Display an effect.
DisplayEffect(NodeUI.instance.upgradeEffect);
AudioManager.instance.Play("Upgrade", true);
ShakeCamera.instance.Shake(0.1f, 0.05f);
}
else if (turretBlueprint.upgradePrefab == null)
UIScript.instance.DisplayText("Error 404 !", Camera.main.ScreenToWorldPoint(Input.mousePosition), 6, Color.red);
else
{
AudioManager.instance.Play("SMS", false);
UIScript.instance.DisplayText("Not enough money to Upgrade !", Camera.main.ScreenToWorldPoint(Input.mousePosition), 6, Color.red);
}
}
void DisplayEffect(GameObject _effect)
{
if (_effect == null)
return;
GameObject newEffect = PoolObjectScript.instance.GetPoolObject(_effect);
newEffect.transform.position = transform.position;
}
public void SellTurret()
{
if (turret == null)
return;
//Get the money given back to the player.
int sellAmount = turretBlueprint.GetSellAmount(isUpgraded);
//Give the money to the player.
PlayerStatsScript.instance.money += sellAmount;
//Display the money given back.
UIScript.instance.DisplayText("+" + sellAmount + "$" , Camera.main.ScreenToWorldPoint(Input.mousePosition), 6, Color.green);
//Reset the isUpgraded variable.
isUpgraded = false;
buildManager.DeselectNode();
turret.SetActive(false);
turret = null;
turretBlueprint = null;
DisplayEffect(NodeUI.instance.SellingEffect);
AudioManager.instance.Play("Balloon Popping", true);
ShakeCamera.instance.Shake(0.1f, 0.2f);
}
void OnMouseDown()
{
if (EventSystem.current.IsPointerOverGameObject())
return;
if (!buildManager.CanBuild)
return;
if (turret != null)
{
buildManager.SelectNode(this);
return;
}
buildManager.nodeUI.Hide();
BuildTurret(buildManager.GetTurretToBuild());
}
//When the mouse cursor is on the object.
void OnMouseEnter ()
{
buildManager.mouseOverNode = true;
if (!buildManager.GetSelectedNode)
buildManager.nodeUI.DisplayTurretRange(this, true);
lerpActivated = true;
startTime = Time.time;
if (!Input.GetKey(KeyCode.Mouse0))
return;
if (EventSystem.current.IsPointerOverGameObject())
return;
if (!buildManager.CanBuild)
return;
if (turret != null)
{
buildManager.SelectNode(this);
return;
}
buildManager.nodeUI.Hide();
BuildTurret(buildManager.GetTurretToBuild());
}
void ColorLerp(Color startColor, Color endColor)
{
//Change the color of the sprite.
t = (Time.time - startTime) * colorLerpSpeed;
if (lerpActivated)
{
sprite.color = Color.Lerp(startColor, endColor, t);
}
else
sprite.color = Color.Lerp(endColor, startColor, t);
//Change the color of the sprite.
}
public Vector2 GetBuildPosition()
{
return new Vector2(transform.position.x, transform.position.y + 0.5f);
}
void OnMouseExit ()
{
buildManager.mouseOverNode = false;
if (!buildManager.GetSelectedNode)
buildManager.nodeUI.DisplayTurretRange(this, false);
lerpActivated = false;
ColorLerp(highLightColor, startColor);
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/IAScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IAScript : MonoBehaviour {
public float moveSpeed;
public int damage = 1;
public Transform[] pathArray;
//The index of the point to go.
int pathPointIndex = 0;
float startMoveSpeed;
GameObject endNode;
void Start() {
pathArray = GameObject.FindGameObjectWithTag("PathPoints").GetComponent<PathPointsScript>().points;
endNode = GameObject.FindGameObjectWithTag("Data").GetComponent<PoolObjectScript>().endNode;
}
void Awake()
{
startMoveSpeed = moveSpeed;
}
void OnEnable()
{
pathPointIndex = 0;
}
public float GetMoveSpeed
{
get
{
return startMoveSpeed;
}
}
public void Slow(float slowAmount)
{
moveSpeed = startMoveSpeed - (startMoveSpeed * slowAmount);
}
void Update () {
haveIReachedTheEndFunc();
MoveOnPathFunc();
MoveToNextPoint();
moveSpeed = startMoveSpeed;
}
void MoveOnPathFunc()
{
Vector2 dir = pathArray[pathPointIndex].position - transform.position;
transform.Translate(dir.normalized * Time.deltaTime * moveSpeed);
}
void MoveToNextPoint()
{
Vector2 dir = pathArray[pathPointIndex].position - transform.position;
float distanceThisFrame = moveSpeed * Time.deltaTime;
if (dir.magnitude <= distanceThisFrame)
{
if (pathPointIndex >= pathArray.Length - 1)
{
return;
}
pathPointIndex++;
}
}
void haveIReachedTheEndFunc()
{
Vector2 dir = endNode.transform.position - transform.position;
float distanceThisFrame = moveSpeed * Time.deltaTime;
if (dir.magnitude <= distanceThisFrame)
{
UIScript.instance.DisplayText("-" + damage.ToString(), transform.position, 15, Color.red);
PlayerStatsScript.instance.life -= damage;
AudioManager.instance.Play("Boom", true);
ShakeCamera.instance.Shake(0.2f, 0.2f);
gameObject.SetActive(false);
}
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/PlayerStatsScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerStatsScript : MonoBehaviour {
public static PlayerStatsScript instance;
public int life = 10;
public float money = 40;
void Awake() {
if (instance == null)
instance = this;
}
void Update () {
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/ShopScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShopScript : MonoBehaviour {
public TurretBluePrintScript standardTurret;
public TurretBluePrintScript fastTurret;
public TurretBluePrintScript multiTurret;
public TurretBluePrintScript slowTurret;
public TurretBluePrintScript burnTurret;
public TurretBluePrintScript electricTurret;
public TurretBluePrintScript superMultiTurret;
public TurretBluePrintScript laserTurret;
public static ShopScript instance;
GameObject shopCursor;
BuildManagerScript buildManager;
/// <summary>
/// Shop Cursor
/// </summary>
public Vector3 newShopCursorPosition;
void Awake()
{
if(instance == null)
instance = this;
}
void Start()
{
shopCursor = gameObject.transform.Find("shopCursor").gameObject;
buildManager = BuildManagerScript.instance;
newShopCursorPosition = shopCursor.transform.position;
}
void Update()
{
shopCursor.transform.position = Vector2.Lerp(shopCursor.transform.position, newShopCursorPosition, Time.deltaTime * 6);
}
public void MoveShopCursor(float yPosition)
{
newShopCursorPosition = new Vector2(shopCursor.transform.position.x, yPosition);
AudioManager.instance.Play("Jump", true);
}
public void SelectStandardTurret()
{
buildManager.SetTurretToBuild(standardTurret);
}
public void SelectFastTurret()
{
buildManager.SetTurretToBuild(fastTurret);
}
public void SelectMultiTurret()
{
buildManager.SetTurretToBuild(multiTurret);
}
public void SelectSlowTurret()
{
buildManager.SetTurretToBuild(slowTurret);
}
public void SelectBurnTurret()
{
buildManager.SetTurretToBuild(burnTurret);
}
public void SelectElectricTurret()
{
buildManager.SetTurretToBuild(electricTurret);
}
public void selectSuperMultiTurret()
{
buildManager.SetTurretToBuild(superMultiTurret);
}
public void selectLaserTurret()
{
buildManager.SetTurretToBuild(laserTurret);
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/ShakeCamera.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShakeCamera : MonoBehaviour {
public static ShakeCamera instance;
public float intensity;
public float duration;
public float fadeSpeed;
float startTime;
float t;
public float durationRemaining;
bool isShaking;
bool fading = false;
Vector3 initialPosition;
// Use this for initialization
void Awake ()
{
if (instance == null)
instance = this;
initialPosition = transform.position;
}
// Update is called once per frame
void Update ()
{
if (isShaking)
{
durationRemaining -= Time.deltaTime;
transform.position = initialPosition + new Vector3(Random.Range(-intensity, intensity), Random.Range(-intensity, intensity), initialPosition.z);
SlowDownShaking();
}
else
StopShaking();
}
public void Shake(float _intensity = 1, float _duration = 1)
{
// startTime = Time.time;
durationRemaining = _duration;
intensity = _intensity;
duration = _duration;
isShaking = true;
fading = false;
CancelInvoke();
Invoke("StopShaking", duration);
}
void SlowDownShaking()
{
if (durationRemaining > 1)
return;
if (fading == false)
{
fading = true;
startTime = Time.time;
}
t = (Time.time - startTime) * fadeSpeed;
intensity = Mathf.Lerp(intensity, 0, t);
}
public void StopShaking()
{
isShaking = false;
transform.position = initialPosition;
}
}
<file_sep>/Space TD/Assets/Assets/Scripts/TowerScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TowerScript : MonoBehaviour {
public enum TowerTargetMod {singleTarget, multipleTarget, special}
public enum TowerEffect {noEffect, slowTarget, BurnTarget, Electric, LaserBeam}
[Header("Main Data")]
public float attackDamage = 1;
public float attackSpeed;
public float attackRange;
[Space]
[Header("Others")]
public float bulletSpeed = 1;
[Range(0, 100)]
public float slowAmount = 1;
public float rotateSpeed;
public GameObject shootPos;
public GameObject bulletG;
public List<GameObject> enemiesToAttack;
public TowerTargetMod towerTargetMod = TowerTargetMod.singleTarget;
public TowerEffect towerEffect = TowerEffect.noEffect;
Transform partToRotate;
GameObject target;
GameObject[] enemies;
PoolObjectScript poolScript;
float nextAttackTime;
GameObject[] newEnemie;
[Header("Use Laser")]
[HideInInspector]
public LineRenderer lineRenderer;
//Particle System
public GameObject burnTurretEffectG;
ParticleSystem particleSystem;
void Awake() {
poolScript = GameObject.FindGameObjectWithTag("Data").GetComponent<PoolObjectScript>();
}
void Start()
{
//For burnTurret.
if (burnTurretEffectG != null)
particleSystem = burnTurretEffectG.GetComponent<ParticleSystem>();
if (towerEffect == TowerEffect.Electric || towerEffect == TowerEffect.LaserBeam)
lineRenderer = GetComponent<LineRenderer>();
partToRotate = transform.Find("Sprite").transform;
InvokeRepeating("LookAtEnemy", 0f, 1 * Time.deltaTime);
}
void Update () {
TowerManager();
}
void TowerManager()
{
if (towerEffect == TowerEffect.slowTarget)
{
SlowEnemy();
}
if (towerEffect == TowerEffect.BurnTarget)
{
BurnEnemy();
}
if (towerEffect == TowerEffect.Electric)
{
ThrowLightning();
}
if (towerEffect == TowerEffect.LaserBeam)
{
LaserBeam();
}
if (towerTargetMod == TowerTargetMod.singleTarget)
{
FindEnemies();
LookAtEnemy();
AttackEnemy();
IsTheEnemyStillAlive();
}
else if(towerTargetMod == TowerTargetMod.multipleTarget)
{
AttackAllNearEnemy();
}
}
List<GameObject> FindAllNearEnemy()
{
enemies = poolScript.enemies;
List<GameObject> enemiesToReturn = new List<GameObject>();
if (Time.time > nextAttackTime)
{
nextAttackTime = Time.time + attackSpeed;
foreach (GameObject enemy in enemies)
{
float distance = Vector2.Distance(enemy.transform.position, transform.position);
if (enemy.activeSelf == true)
{
if (distance <= attackRange)
enemiesToReturn.Add(enemy);
else
enemiesToReturn.Remove(enemy);
}
}
}
else
enemiesToReturn = null;
return enemiesToReturn;
}
void AttackAllNearEnemy()
{
List<GameObject> enemies = FindAllNearEnemy();
if (enemies == null)
return;
foreach (GameObject enemy in enemies)
{
GameObject newBullet = poolScript.GetPoolObject(bulletG);
BulletScript newBulletScript = newBullet.GetComponent<BulletScript>();
newBulletScript.target = enemy;
newBulletScript.attackDamage = attackDamage;
newBulletScript.moveSpeed = bulletSpeed;
newBullet.transform.position = shootPos.transform.position;
AudioManager.instance.Play("Tower Shoot", true);
}
}
void FindEnemies()
{
enemies = poolScript.enemies;
GameObject closestEnemy = null;
float lowestDistance = Mathf.Infinity;
foreach (GameObject enemy in enemies)
{
float Distance = Vector2.Distance(transform.position, enemy.transform.position);
if (Distance < lowestDistance)
{
lowestDistance = Distance;
closestEnemy = enemy;
}
if (lowestDistance < attackRange && closestEnemy != null && closestEnemy.activeSelf)
{
target = closestEnemy;
}
else
{
target = null;
}
}
}
void LookAtEnemy()
{
if (target != null)
{
//Calculate the direction.
Vector3 dir = target.transform.position - partToRotate.position;
float angle;
//Calculate the angle to rotate to face the target.
angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion newQuaternion = Quaternion.AngleAxis(angle, Vector3.forward);
//Rotate for X degre
partToRotate.rotation = Quaternion.Lerp(partToRotate.rotation, newQuaternion, rotateSpeed * Time.deltaTime);
}
}
//Check if the enemy is still active in the scene.
void IsTheEnemyStillAlive()
{
if (target != null && target.GetComponent<ProgressBarScript>().currentHealth <= 0)
target = null;
}
//Slow enemy within range.
void SlowEnemy()
{
List<GameObject> enemies = FindAllNearEnemy();
if (enemies == null)
return;
foreach (GameObject enemy in enemies)
{
IAScript enemyScript = enemy.GetComponent<IAScript>();
enemyScript.Slow(slowAmount / 100f);
UIScript.instance.DisplayImpactEffect(UIScript.instance.slowEnemyEffect).transform.position = enemy.transform.position;
}
}
void BurnEnemy()
{
List<GameObject> enemies = FindAllNearEnemy();
ActivateEffect();
if (enemies == null || enemies.Count == 0)
return;
foreach (GameObject enemy in enemies)
{
ProgressBarScript progressBarScript = enemy.GetComponent<ProgressBarScript>();
progressBarScript.currentHealth -= attackDamage;
}
}
void ThrowLightning()
{
List<GameObject> enemies = FindAllNearEnemy();
ActivateEffect();
List<Vector3> lightningPositions = new List<Vector3>();
//Null means that the turret is reloading.
if (enemies == null)
{
return;
}
//If there is not enemy, erase the line.
if (enemies.Count == 0)
{
GetComponent<Animator>().SetBool("Attacking", false);
lineRenderer.positionCount = 0;
return;
}
GetComponent<Animator>().SetBool("Attacking", true);
GetComponent<Animator>().Play("ElectricTurretAttack", 0);
lightningPositions.Add(transform.position);
foreach (GameObject enemy in enemies)
{
// lineRenderer.SetPosition(1, enemy.transform.position);w²
lightningPositions.Add(enemy.transform.position);
lightningPositions.Add(enemy.transform.position + new Vector3(Random.Range(0f, 2f), Random.Range(0f, 2f), 0));
// print(enemy.transform.position +new Vector3(Random.Range(0, 2), Random.Range(0, 2), 0));
ProgressBarScript progressBarScript = enemy.GetComponent<ProgressBarScript>();
progressBarScript.currentHealth -= attackDamage;
UIScript.instance.DisplayImpactEffect(UIScript.instance.electricEnemyEffect).transform.position = enemy.transform.position;
AudioManager.instance.Play("Punch", true);
}
lineRenderer.positionCount = lightningPositions.Count;
foreach (Vector3 pos in lightningPositions)
{
lineRenderer.SetPosition(lightningPositions.IndexOf(pos), pos);
}
// ITS WORKING , ATTACK ONLY ONE ENEMY AT THE TIME.
// FindEnemies();
//
// if (target == null)
// {
// lineRenderer.SetPosition(0, shootPos.transform.position);
// lineRenderer.SetPosition(1, shootPos.transform.position);
//
// return;
// }
// target.GetComponent<ProgressBarScript>().currentHealth -= attackDamage;
//
// lineRenderer.SetPosition(0, shootPos.transform.position);
// lineRenderer.SetPosition(1, target.transform.position);
//
// UIScript.instance.DisplayImpactEffect(UIScript.instance.electricEnemyEffect).transform.position = target.transform.position;
}
void LaserBeam()
{
List<GameObject> enemies = FindAllNearEnemy();
ActivateEffect();
List<Vector3> lightningPositions = new List<Vector3>();
//Null means that the turret is reloading.
if (enemies == null)
{
return;
}
//If there is not enemy, erase the line.
if (enemies.Count == 0)
{
lineRenderer.positionCount = 0;
return;
}
lightningPositions.Add(transform.position);
foreach (GameObject enemy in enemies)
{
lightningPositions.Add(transform.position);
lightningPositions.Add(enemy.transform.position);
ProgressBarScript progressBarScript = enemy.GetComponent<ProgressBarScript>();
progressBarScript.currentHealth -= attackDamage;
}
lineRenderer.positionCount = lightningPositions.Count;
int i = 0;
foreach (Vector3 pos in lightningPositions)
{
lineRenderer.SetPosition(i, pos);
i++;
}
}
void ActivateEffect()
{
if (particleSystem == null)
return;
if (particleSystem.isPlaying == true && SpawnerScript.instance.enemiesRemainingAlive <= 0 && SpawnerScript.instance.enemiesRemainingToSpawn <= 0)
particleSystem.Stop();
else if(particleSystem.isPlaying == false)
particleSystem.Play();
}
void AttackEnemy()
{
if (Time.time > nextAttackTime && target != null && target.activeSelf)
{
nextAttackTime = Time.time + attackSpeed;
GameObject newBullet = poolScript.GetPoolObject(bulletG);
BulletScript newBulletScript = newBullet.GetComponent<BulletScript>();
newBulletScript.target = target;
newBulletScript.attackDamage = attackDamage;
newBulletScript.moveSpeed = bulletSpeed;
newBullet.transform.position = shootPos.transform.position;
AudioManager.instance.Play("Tower Shoot", true);
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}
| 7334ff58881c84e5195956107434da57988378f8 | [
"Markdown",
"C#"
] | 24 | C# | TThanushan/space-td | 33c96339060162f87304c90e9e3a5a31a90f011d | 2bf54e44ad7aefb604d0995fdbc9da9b906a06fc |
refs/heads/master | <file_sep>//1 导包
const express = require('express');
const router = require('./router');
const bodyParser = require('body-parser');
//2 配置包
const app = express();
//3 路由配置
app.use('/public',express.static('./public'));
app.use('/node_modules',express.static('./node_modules'));
app.engine('html', require('express-art-template'));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(router);
//4 配置端口
app.listen(12345,()=>{
console.log('running--------');
}) | 5639fa8d3792e78de3f50eb4e36956b217341201 | [
"JavaScript"
] | 1 | JavaScript | Cherries-tong/newssql | ecd35bbe4d4dc2ff6c0dbf4f407e8431bccf4a4c | c3329f91123c32d1a319ccb0b8ca2131e200e373 |
refs/heads/master | <repo_name>faskowit/app-hcp-acpc-alignment<file_sep>/hcpAlignACPC.sh
#!/bin/bash
## This app will align a T1w image to the ACPC plane (specifically, the MNI152_T1_1mm template from
## FSL using a 6 DOF alignment via FSL commands. This protocol was adapted from the HCP Preprocessing
## Pipeline (https://github.com/Washington-University/HCPpipelines.git). Requires a T1w image input
## and outputs an acpc_aligned T1w image.
echo "Grabbing input T1w image"
# Grab the config.json inputs
t1=`jq -r '.t1' config.json`;
echo "Files loaded"
# Possibly reorient 2 std
if [ -f t1_reor.nii.gz ] ; then
echo "File exists. Skipping"
else
echo "reorienting"
# saving matrix
fslreorient2std ${t1} | tee reor.xfm
# actual reorient
fslreorient2std ${t1} t1_reor.nii.gz
fi
# Crop FOV
if [ -f "t1_robustfov.nii.gz" ];then
echo "File exists. Skipping"
else
echo "Cropping FOV"
robustfov -i t1_reor.nii.gz \
-m roi2full.mat \
-r t1_robustfov.nii.gz;
ret=$?
if [ ! $ret -eq 0 ]; then
echo "Cropping failed"
echo $ret > finished
exit $ret
fi
fi
# Invert matrix
if [ -f "full2roi.mat" ];then
echo "File exists. Skipping"
else
echo "Inverting matrix (full FOV to ROI)"
convert_xfm -omat full2roi.mat \
-inverse roi2full.mat;
ret=$?
if [ ! $ret -eq 0 ]; then
echo "Matrix inversion failed"
echo $ret > finished
exit $ret
fi
fi
# Register cropped image to MNI152 (12 DOF)
if [ -f "t1_acpc_mni.nii.gz" ];then
echo "File exists. Skipping"
else
echo "Registering image to MNI152 (12 DOF)"
flirt -interp spline \
-in t1_robustfov.nii.gz \
-ref ${FSLDIR}/data/standard/MNI152_T1_1mm \
-omat roi2std.mat \
-out t1_acpc_mni.nii.gz;
ret=$?
if [ ! $ret -eq 0 ]; then
echo "12 DOF Registration failed"
echo $ret > finished
exit $ret
fi
fi
# Concatenate matrices to get full FOV to MNI
if [ -f "full2std.mat" ];then
echo "File exists. Skipping"
else
echo "Concatenate matrices to get full FOV to MNI"
convert_xfm -omat full2std.mat \
-concat roi2std.mat full2roi.mat;
ret=$?
if [ ! $ret -eq 0 ]; then
echo "Matrix concatenation failed"
echo $ret > finished
exit $ret
fi
fi
# Get 6 DOF approximation ACPC alignment
if [ -f "outputmatrix" ];then
echo "File exists. Skipping"
else
echo "ACPC Alignment"
aff2rigid full2std.mat \
outputmatrix;
ret=$?
if [ ! $ret -eq 0 ]; then
echo "ACPC alignment failed"
echo $ret > finished
exit $ret
fi
fi
# Resample ACPC aligned image
if [ -f "t1.nii.gz" ];then
echo "File exists. Skipping"
else
echo "Resampling"
applywarp --rel \
--interp=spline \
-i ${t1} \
-r ${FSLDIR}/data/standard/MNI152_T1_1mm \
--premat=outputmatrix \
-o t1.nii.gz;
ret=$?
if [ ! $ret -eq 0 ]; then
echo "Resampling failed"
echo $ret > finished
exit $ret
fi
fi
echo "ACPC Alignment Pipeline complete"
<file_sep>/main
#!/bin/bash
#PBS -l nodes=1:ppn=1,walltime=0:25:00
#PBS -N hcpacpc
#PBS -V
module load singularity 2> /dev/null
singularity exec -e docker://brainlife/fsl:5.0.9 ./hcpAlignACPC.sh
if [ ! -s t1.nii.gz ];
then
echo "output missing"
exit 1
fi
| 08b006f00181303cc4d8693f0e5eec4b08c6bed3 | [
"Shell"
] | 2 | Shell | faskowit/app-hcp-acpc-alignment | 936b8b2da3166ca39c57999fe5487b8e6715ff92 | 0f9fdc33976c9f588dd3b629f598d06a5b93bf51 |
refs/heads/master | <repo_name>IdanAvior/Trivia<file_sep>/README.md
# Trivia
A trivia app for Android users
<file_sep>/app/src/main/java/com/avior/idan/trivia/TriviaScreen.java
package com.avior.idan.trivia;
import android.content.Intent;
import android.graphics.Color;
import android.preference.PreferenceActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.Collections;
import cz.msebera.android.httpclient.Header;
public class TriviaScreen extends AppCompatActivity implements QuestionFragment.QuestionFragmentActivity{
String correctAnswer;
final int numberOfQuestions = 10;
final int pointsPerEasyQuestion = 20;
final int pointsPerMediumQuestion = 50;
final int pointsPerHardQuestion = 100;
int numberOfAnswers;
int points;
int pointsPerCorrectAnswer;
int questionNumber;
String difficulty;
String quizType;
String categoryName;
String token;
TextView questionNumberTextView;
TextView pointsTextView;
TextView difficultyTextView;
AsyncHttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trivia_screen);
questionNumberTextView = (TextView) findViewById(R.id.question_number);
pointsTextView = (TextView) findViewById(R.id.points);
pointsTextView.setText("Score: 0");
difficultyTextView = (TextView) findViewById(R.id.difficulty);
difficultyTextView.setText("Easy");
difficultyTextView.setTextColor(Color.GREEN);
String rawType = getIntent().getStringExtra("type");
if (rawType.equals("Multiple Choice")) {
quizType = "multiple";
numberOfAnswers = 4;
}
else {
quizType = "boolean";
numberOfAnswers = 2;
}
categoryName = getIntent().getStringExtra("subject");
client = new AsyncHttpClient();
startNewGame();
}
public void updateActivity(String s)
{
if (s == null)
Toast.makeText(this,"No answer selected", Toast.LENGTH_SHORT).show();
else {
if (s.equals(correctAnswer)) {
Toast.makeText(this, "Correct!", Toast.LENGTH_SHORT).show();
points+=pointsPerCorrectAnswer;
pointsTextView.setText("Score: " + points);
if (points == 3*pointsPerEasyQuestion) {
difficulty = "medium";
difficultyTextView.setText("Medium");
difficultyTextView.setTextColor(Color.YELLOW);
pointsPerCorrectAnswer = pointsPerMediumQuestion;
}
if (points == 3*pointsPerEasyQuestion + 4*pointsPerMediumQuestion) {
difficulty = "hard";
difficultyTextView.setText("Hard");
difficultyTextView.setTextColor(Color.RED);
pointsPerCorrectAnswer = pointsPerHardQuestion;
}
}
else
Toast.makeText(this, "Wrong!", Toast.LENGTH_SHORT).show();
if (questionNumber == numberOfQuestions + 1){
Intent intent = new Intent(TriviaScreen.this, GameOverScreen.class);
intent.putExtra("score", points);
startActivity(intent);
}
else
getNewQuestion();
}
}
public void getNewQuestion(){
if (token == null)
retrieveToken();
final String urlStart = "https://opentdb.com/api.php?amount=1&category=";
final String urlMiddle = "&difficulty=";
final String urlEnd = "&type=";
final String constructedUrl = urlStart + getCategoryNumberByName(categoryName) + urlMiddle + difficulty + urlEnd + quizType;
questionNumberTextView.setText("Question " + questionNumber++ + "/" + numberOfQuestions);
client.get(constructedUrl, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response){
try{
String question = response.getJSONArray("results").getJSONObject(0).getString("question");
correctAnswer = response.getJSONArray("results").getJSONObject(0).getString("correct_answer");
String[] answers = new String[numberOfAnswers];
for (int i = 0; i < numberOfAnswers - 1; i++)
answers[i] = response.getJSONArray("results").getJSONObject(0).getJSONArray("incorrect_answers").getString(i);
answers[numberOfAnswers - 1] = correctAnswer;
Collections.shuffle(Arrays.asList(answers));
getSupportFragmentManager().beginTransaction().replace(R.id.question_space, QuestionFragment.newInstance(question, answers)).commit();
} catch (JSONException e){
e.printStackTrace();
}
}
});
}
public int getCategoryNumberByName(String name){
switch(name) {
case "General Knowledge":
return 9;
case "Entertainment: Books":
return 10;
case "Entertainment: Film":
return 11;
case "Entertainment: Music":
return 12;
case "Entertainment: Musicals and Theatres":
return 13;
case "Entertainment: Television":
return 14;
case "Entertainment: Video Games":
return 15;
case "Entertainment: Board Games":
return 16;
case "Science and Nature":
return 17;
case "Science: Computers":
return 18;
case "Science: Mathematics":
return 19;
case "Mythology":
return 20;
case "Sports":
return 21;
case "Geography":
return 22;
case "History":
return 23;
case "Politics":
return 24;
case "Art":
return 25;
case "Celebrities":
return 26;
case "Animals":
return 27;
default:
return 0;
}
}
public void startNewGame(){
points = 0;
pointsPerCorrectAnswer = 20;
difficulty = "easy";
questionNumber = 1;
retrieveToken();
getNewQuestion();
}
public void retrieveToken(){
client.get("https://opentdb.com/api_token.php?command=request", new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response){
try{
token = response.getString("token");
} catch (JSONException e){
e.printStackTrace();
}
}
});
}
}
<file_sep>/app/src/main/java/com/avior/idan/trivia/QuestionFragment.java
package com.avior.idan.trivia;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import org.w3c.dom.Text;
public class QuestionFragment extends Fragment {
public static QuestionFragment newInstance(String question, String[] answers) {
QuestionFragment fragment = new QuestionFragment();
Bundle args = new Bundle();
args.putString("question", question);
args.putStringArray("answers", answers);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_question, container, false);
TextView question =(TextView) view.findViewById(R.id.question);
question.setText(Html.fromHtml(getArguments().getString("question")));
question.setTextSize(25);
final String[] answers = getArguments().getStringArray("answers");
final RadioGroup radioGroup = new RadioGroup(getContext());
if (answers.length > 2) {
for (int i = 0; i < answers.length; i++) {
RadioButton radioButton = new RadioButton(getContext());
radioButton.setId(i + 1);
radioButton.setText(Html.fromHtml(answers[i]));
radioButton.setTextSize(20);
radioGroup.addView(radioButton);
}
}
else{
RadioButton trueRadioButton = new RadioButton(getContext());
RadioButton falseRadioButton = new RadioButton(getContext());
trueRadioButton.setId(0+1);
falseRadioButton.setId(0+2);
trueRadioButton.setText("True");
falseRadioButton.setText("False");
trueRadioButton.setTextSize(20);
falseRadioButton.setTextSize(20);
radioGroup.addView(trueRadioButton);
radioGroup.addView(falseRadioButton);
}
ViewGroup viewGroup = (ViewGroup) view;
viewGroup.addView(radioGroup);
Button button = new Button(getContext());
button.setText("Submit");
button.setTextSize(20);
button.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
button.setTextColor(getResources().getColor(R.color.colorPrimary));
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String answer = null;
for (int i = 0; i < answers.length; i++) {
RadioButton button = (RadioButton) radioGroup.getChildAt(i);
if (button.isChecked()) {
Spanned htmlText = Html.fromHtml(button.getText().toString());
answer = htmlText.toString();
}
}
((TriviaScreen)getActivity()).updateActivity(answer);
}
});
viewGroup.addView(button);
return view;
}
public static interface QuestionFragmentActivity{
public void updateActivity(String s);
}
}
<file_sep>/app/src/main/java/com/avior/idan/trivia/MainActivity.java
package com.avior.idan.trivia;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Spinner subjectSpinner = (Spinner) findViewById(R.id.subject_spinner);
ArrayAdapter<CharSequence> subjectAdapter = ArrayAdapter.createFromResource(this,
R.array.subjects_array, android.R.layout.simple_spinner_item);
subjectAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
subjectSpinner.setAdapter(subjectAdapter);
final Spinner typeSpinner = (Spinner) findViewById(R.id.type_spinner);
ArrayAdapter<CharSequence> typeAdapter = ArrayAdapter.createFromResource(this,
R.array.quiz_types_array, android.R.layout.simple_spinner_item);
typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
typeSpinner.setAdapter(typeAdapter);
Button proceedButton = (Button) findViewById(R.id.proceed_button);
proceedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TriviaScreen.class);
intent.putExtra("subject", subjectSpinner.getSelectedItem().toString());
intent.putExtra("type", typeSpinner.getSelectedItem().toString());
startActivity(intent);
}
});
}
}
| c66abb30e13390dd283bcd32d0a763fd516dccac | [
"Markdown",
"Java"
] | 4 | Markdown | IdanAvior/Trivia | a172b15c2f2c8a7be067b2b59c255954c5be9d3d | 9da9d0caca795ab911924408358301b3fc7bf6da |
refs/heads/master | <repo_name>bumkaka/modx.evo.custom<file_sep>/manager/includes/extenders/modifiers.extenders.inc.php
<?php
if (class_exists('modifiers') ) return;
class modifiers{
public function parse($output, $key, $modifiers){
global $modx;
if ( !preg_match('/^\.*-*_*\w*\d*(:)/mi',$modifiers) ) return $output;
if (preg_match_all('~:([^:=]+)(?:=`(.*?)`(?=:[^:=]+|$))?~s',$modifiers, $matches)) {
$count = count($matches[1]);
$condition = array();
for($i=0; $i<$count; $i++) {
$output = trim($output);
$modifier_cmd = $matches[1][$i]; // modifier command
$modifier_value = $matches[2][$i]; // modifier value
$value = $modifier_value;
switch ($modifier_cmd) {
case "lcase":
case "strtolower":
$output = strtolower($output);
break;
case "ucase":
case "strtoupper":
$output = mb_strtoupper($output, $modx->config['modx_charset']);
break;
case "htmlent":
case "htmlentities":
$output = htmlentities($output,ENT_QUOTES,$modx->config['modx_charset']);
break;
case "html_entity_decode":
$output = html_entity_decode($output,ENT_QUOTES,$modx->config['modx_charset']);
break;
case "esc":
$output = preg_replace("/&(#[0-9]+|[a-z]+);/i", "&$1;", htmlspecialchars($output));
$output = str_replace(array("[","]","`"),array("[","]","`"),$output);
break;
case "strip":
$output = preg_replace("~([\n\r\t\s]+)~"," ",$output);
break;
case "notags":
case "strip_tags": $output = strip_tags($output);
break;
case "length":
case "len":
case "strlen":
$output = mb_strlen($output,$modx->config['modx_charset']);
break;
case "reverse":
case "strrev":
$output = iconv("UTF-16LE", $modx->config['modx_charset'], strrev(iconv($modx->config['modx_charset'], "UTF-16BE", $output)));
break;
case "wordwrap":
$wrapat = intval($modifier_value) ? intval($modifier_value) : 70;
$output = preg_replace("~(\b\w+\b)~e","wordwrap('\\1',\$wrapat,' ',1)",$output);
break;
case "limit":
$limit = intval($modifier_value) ? intval($modifier_value) : 100;
$output = substr($output,0,$limit);
break;
case "str_word_count":
case "word_count":
case "wordcount":
$output = str_word_count($output);
break;
case "ucfirst":
case "lcfirst":
case "ucwords":
case "addslashes":
case "ltrim":
case "rtrim":
case "trim":
case "nl2br":
case "md5":
$output = $modifier_cmd($output);
break;
case "math":
$filter = preg_replace("~([a-zA-Z\n\r\t\s])~","",$modifier_value);
$filter = str_replace("?",$output,$filter);
$output = eval("return ".$filter.";");
break;
case "date":
$output = strftime($modifier_value,0+$output);
break;
default:
$snippetName = 'modifier:'.$modifier_cmd;
if( isset($modx->snippetCache[$snippetName]) ) {
$snippet = $modx->snippetCache[$snippetName];
} else {
$prfx = $modx->db->config['table_prefix'];
$esc_name = $modx->db->escape($snippetName);
$result= $modx->db->select('snippet',"{$prfx}site_snippets","name='{$esc_name}'");
if ($modx->db->getRecordCount($result) == 1) {
$row= $modx->db->getRow($result);
$snippet= $modx->snippetCache[$row['name']]= $row['snippet'];
} else if ($modx->db->getRecordCount($result) == 0){ // If snippet not found, look in the modifiers folder
$filename = $modx->config['base_path'] . 'assets/modifiers/'.$modifier_cmd.'.modifier.php';
if (@is_file($filename)) {
$file_contents = @file_get_contents($filename);
$file_contents = str_replace('<'.'?php', '', $file_contents);
$file_contents = str_replace('?'.'>', '', $file_contents);
$file_contents = str_replace('<?', '', $file_contents);
$snippet = $modx->snippetCache[$snippetName] = $file_contents;
$modx->snippetCache[$snippetName.'Props'] = '';
}
}
}
$cm = $snippet;
// end //
ob_start();
$options = $modifier_value;
$custom = eval($cm);
$msg = ob_get_contents();
$output = $msg.$custom;
ob_end_clean();
break;
}
}
}
return $output;
}
}
$this->modifiers = new modifiers;
<file_sep>/assets/plugins/codemirror/cm/review.config.inc.php
<?php
$settings['display'] = 'vertical';
$settings['fields'] = array(
'name' => array(
'caption' => 'Имя',
'type' => 'text'
),
'rewiev' => array(
'caption' => 'Отзыв',
'type' => 'textarea'
));
| 05536c860821d8d3b8094cc73093f1c77a5c9af4 | [
"PHP"
] | 2 | PHP | bumkaka/modx.evo.custom | 2197a483b195d64cc7d466ecae3d558ac840dba5 | a857700f8a0a834bd141181f4de32cd0e1c2d0e4 |
refs/heads/master | <file_sep>WTForms~=2.3.3
Flask~=2.0.2
redis~=3.5.3<file_sep>$().ready(function() {
initLeftNavHeight();
initMenu();
})
/**初始化左侧导航栏高度**/
function initLeftNavHeight() {
initHeight();
function initHeight() {
var total = document.documentElement.clientHeight;
var topHeight = $("#top").height();
$("#leftNav").height(total - topHeight);
}
document.body.onresize = function() {
initHeight();
}
}
/**初始化菜单选项**/
function initMenu() {
//配置第一个手风琴的基本参数
var config01 = {
//配置菜单的MenuBoxId
menuBoxId: "#menuBox01",
//是否可以打开多个上级菜单
multiple: true,
//初始化打开的
openIndex: [0,]
}
menuBox.init(config01);
//配置第二个手风琴的基本参数
// var config02 = {
// //配置菜单的MenuBoxId
// menuBoxId: "#menuBox02",
// //是否可以打开多个上级菜单
// multiple: false,
// //初始化打开的上级菜单的index数组
// openIndex: [-1, 1]
// }
// menuBox.init(config02);
}
/**
* 配置菜单
* 示例:
* 配置基本参数
* var config = {
* //配置菜单的MenuBoxId
* menuBoxId: "#menuBox01",
* //是否可以打开多个上级菜单
* multiple: true,
* //初始化打开的菜单数组
* openIndex: [1, 3, 5]
* }
* menuBox.init(config);
*/
! function($) {
if($ == undefined) {
throw new Error("please put your jquery.js top of menuBox.js!")
}
var menuBox = function() {};
//要配置的menuBox的菜单id
menuBox.menuBoxId = undefined;
//是否可以显示多个上级菜单的子菜单
menuBox.multiple = false;
//默认关闭所有一级菜单
menuBox.openIndex = [];
//menuBox初始化方法
menuBox.init = function(config) {
var cntMenuBox = new menuBox();
//定义上级菜单spMenu数组
var spMenus;
if(config.menuBoxId == undefined) {
throw new Error("your config has not 'menuBoxId', please make sure your menuBox is existed!");
} else {
cntMenuBox.menuBoxId = $(config.menuBoxId) ? config.menuBoxId : undefined;
}
if(config.multiple == undefined) {
console.warn("your config has not 'multiple', default value is false which means you can open only one spMenu at the same time!");
} else {
cntMenuBox.multiple = config.multiple;
}
if(config.openIndex == undefined) {
console.warn("your config has not 'openIndex', default value is a Array which's length is 0!");
} else if(!config.openIndex instanceof Array) {
throw new Error("your config 'openIndex' should be a number Array");
} else {
cntMenuBox.openIndex = unique(config.openIndex, false);
}
//确定对应的menuBox
cntMenuBox.menuBoxId = config.menuBoxId;
//是否打开其他某一个的时候关闭其他选项
var closeOthers = !cntMenuBox.multiple;
//初始化点击事件
initClickEvent(cntMenuBox, closeOthers);
//确定上级菜单数组
spMenus = $(cntMenuBox.menuBoxId + " .spMenu");
//打开传入的数组
for(var i in cntMenuBox.openIndex) {
var index = cntMenuBox.openIndex[i];
var spMenu = spMenus[index];
if(spMenu) {
openSpMenu(cntMenuBox.menuBoxId, index);
if(!cntMenuBox.multiple) {
break;
}
}
}
}
function unique(arr) {
var result = [],
hash = {};
for(var i = 0, elem;
(elem = arr[i]) != null; i++) {
if(!hash[elem]) {
result.push(elem);
hash[elem] = true;
}
}
return result;
}
//初始化点击事件
function initClickEvent(menuBox, closeOthers) {
$(menuBox.menuBoxId + " .spMenu").on("click", function() {
var cntSpMenu$ = $(this);
//要切换的元素
cntSpMenu$.next().slideToggle();
cntSpMenu$.parent().toggleClass("active")
var cntSpMenu = cntSpMenu$['context'];
if(closeOthers == true) {
var spMenus = $(menuBox.menuBoxId + " .spMenu");
$.each(spMenus, function(index, spMenu) {
if(cntSpMenu != spMenu) {
closeSpMenu(menuBox.menuBoxId, index);
}
});
}
});
}
//打开某一个item
function openSpMenu(menuBoxId, index) {
//要切换的元素
var spItem = $(menuBoxId + " .spMenu:eq(" + index + ")");
spItem.next().slideDown();
spItem.parent().addClass("active")
}
//关闭某一个item
function closeSpMenu(menuBoxId, index) {
//要切换的元素
var spItem = $(menuBoxId + " .spMenu:eq(" + index + ")");
spItem.next().slideUp();
spItem.parent().removeClass("active")
}
//切换某一个item
function toggleSpMenu(menuBoxId, index) {
//要切换的元素
var spItem = $(menuBoxId + " .spMenu:eq(" + index + ")");
spItem.next().slideToggle();
spItem.parent().toggleClass("active")
}
window.menuBox = menuBox;
}($);<file_sep>from flask import Flask, render_template, request, redirect, url_for, Response
from Config import config
from form.loginform import LoginForm
from form.register import RegisterForm
from tool import Secretkey
from gmssl.sm2 import CryptSM2
app = Flask(__name__)
app.config.from_object(config)
# app.config['STATIC_FOLDER'] = '..\tatic'
# app.config['STATIC_URL_PATH'] = 'static'
# app.config["DEVELOPMENT"] = True
# app.config['DEBUG'] = True
def decrypt_sm2(prikey,request):
cryptsm2 = CryptSM2(public_key=None,private_key=prikey)
dict_content = request.get_json()
dict_decrypt_content = dict()
for d in dict_content:
data_median_cuphertext = dict_content[d].encode(encoding = "ascii")
print(dict_content[d])
print(type(dict_content[d]))
print(data_median_cuphertext)
print(type(data_median_cuphertext))
# data_median_plainttext = cryptsm2.decrypt(dict_content[d])
data_median_plainttext = cryptsm2.decrypt(data_median_cuphertext)
print(data_median_plainttext)
data_plaintext = data_median_plainttext.decode(encoding = "utf-8")
dict_decrypt_content[d] = data_plaintext
return dict_decrypt_content
@app.route('/register',methods=['GET','POST'])
def register(name='register'):
form = RegisterForm()
resp = Response()
secretkey_sm = Secretkey()
# if form.validate_on_submit() and secretkey_sm.get_pubkey() == request.cookies['psw_sm']:
if request.method == "POST" and secretkey_sm.get_pubkey() == request.cookies['psw_sm']:
prikey = secretkey_sm.get_prikey()
dict_decrypt_content = decrypt_sm2(prikey,request)
print(dict_decrypt_content)
# return redirect(url_for('login'), code=302)
secretkey_sm.set_key()
resp.data = render_template('register.html',form=form)
resp.set_cookie('psw_sm',secretkey_sm.get_pubkey())
return resp
@app.route('/',methods=['GET'])
@app.route('/login',methods=['GET','POST'])
def login(name=None):
form = LoginForm()
if request.method == "GET":
return render_template('login.html',form=form)
# elif request.method == "POST" and form.validate():
elif form.validate_on_submit():
return 'nihao'
else:
pass
@app.route('/homepage')
def homepage():
return render_template("homepage.html")
@app.route('/index',methods=['GET','POST'])
def index(name=None):
if request.method == 'GET' and request.method == 'POST':
pass
if __name__ == '__main__':
app.run("192.168.255.128",5000)<file_sep>from flask_wtf import FlaskForm
class MyBaseForm(FlaskForm):
class Meta:
locals = ['zh']<file_sep>
class config(object):
DEBUG = True
TESTING = True
static_folder= '..\tatic'
static_url_path= 'static'
WTF_I18N_WNABLED = False
SECRET_KEY = 'yanguanghou'
RECAPTCHA_PUBLIC_KEY = "12345678"
RECAPTCHA_PRIVATE_KEY = 'yanguanghou'<file_sep>from form.baseform import MyBaseForm
from wtforms import TextField,StringField,PasswordField,BooleanField,SubmitField
from wtforms.validators import DataRequired
class LoginForm(MyBaseForm):
username = StringField('username',validators=[DataRequired(message=u'名字不能为空')])
password = PasswordField('<PASSWORD>',validators=[DataRequired(message=u'密码不能为空')])
remember = BooleanField('remember me')
submit = SubmitField('login in')<file_sep>from form.baseform import MyBaseForm
from wtforms import TextField, StringField, PasswordField, BooleanField, SubmitField, IntegerField, widgets
from wtforms.validators import DataRequired, EqualTo
from flask_wtf import RecaptchaField
class RegisterForm(MyBaseForm):
username = StringField('账号', validators=[DataRequired()])
password = PasswordField('密码', validators=[DataRequired()], widget=widgets.PasswordInput())
password1 = PasswordField('<PASSWORD>', validators=[DataRequired(), EqualTo('password', message=u'两次密码不一致')],
widget=widgets.PasswordInput())
name = StringField('姓名', validators=[DataRequired()])
department = StringField('部门', validators=[DataRequired()])
drivingLicence_number = IntegerField('驾驶证编号', validators=[DataRequired()])
phone_number = IntegerField('手机号', validators=[DataRequired()])
# recaptcha = RecaptchaField()
submit = SubmitField('提交')
<file_sep>from gmssl import sm2,utils
from gmssl.sm2 import CryptSM2
import redis
# redis
def redis_u():
r = redis.Redis(host='localhost',port=6379,decode_responses=True)
return r
# sm2 密钥生成
class Secretkey:
def __init__(self):
self.priKey = utils.PrivateKey()
self.pubKey = self.priKey.publicKey()
self.r = redis_u()
def set_key(self):
pri = self.priKey.toString()
pub = self.pubKey.toString(False)
self.r.set('priKey',pri)
self.r.set('pubKey',pub)
def get_prikey(self):
priKey_str = self.r.get('priKey')
return priKey_str
def get_pubkey(self):
pubkey_str = self.r.get('pubKey')
return pubkey_str
| fbdcb62e74c293a7ce9b1685cebd63aeac11bcb9 | [
"JavaScript",
"Python",
"Text"
] | 8 | Text | AGJooJo/carManagerSystem | fec33a7d38d41dadf800e62734d71c433c3d84db | 78f81d799bb566dd64befca54ea35f36950459bc |
refs/heads/master | <repo_name>phase/TransformersMod<file_sep>/src/main/java/fiskfille/tf/common/item/ItemBassBlaster.java
package fiskfille.tf.common.item;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.command.IEntitySelector;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import fiskfille.tf.TransformersMod;
import fiskfille.tf.common.entity.EntityBassCharge;
import fiskfille.tf.helper.TFHelper;
public class ItemBassBlaster extends ItemSword
{
public static IIcon bassChargeIcon;
public ItemBassBlaster(ToolMaterial material)
{
super(material);
this.setCreativeTab(TransformersMod.tabTransformers);
this.setMaxDamage(1500);
}
public void onPlayerStoppedUsing(ItemStack stack, World world, EntityPlayer player, int time)
{
if (TFHelper.isPlayerSubwoofer(player) && !world.isRemote && (player.inventory.hasItem(TFItems.energonCrystalPiece) || player.capabilities.isCreativeMode))
{
stack.damageItem(1, player);
if (!player.capabilities.isCreativeMode)
{
player.inventory.consumeInventoryItem(TFItems.energonCrystalPiece);
}
}
}
public void onUsingTick(ItemStack stack, EntityPlayer player, int count)
{
int duration = this.getMaxItemUseDuration(stack) - count;
if (duration < 40)
{
if (player.inventory.hasItem(TFItems.energonCrystalPiece) || player.capabilities.isCreativeMode)
{
World world = player.worldObj;
world.playSound(player.posX, player.posY, player.posZ, "note.bassattack", 1.0F, 0.8F, true);
world.playSound(player.posX, player.posY, player.posZ, "note.bass", 1.0F, 0.8F, true);
if (!world.isRemote)
{
EntityBassCharge entity = new EntityBassCharge(world, player);
world.spawnEntityInWorld(entity);
}
}
}
}
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player)
{
if (TFHelper.isPlayerSubwoofer(player) && (player.inventory.hasItem(TFItems.energonCrystalPiece) || player.capabilities.isCreativeMode))
{
player.setItemInUse(stack, this.getMaxItemUseDuration(stack));
}
return stack;
}
public ItemStack onEaten(ItemStack stack, World world, EntityPlayer player)
{
return stack;
}
public int getMaxItemUseDuration(ItemStack stack)
{
return 72000;
}
public EnumAction getItemUseAction(ItemStack stack)
{
return EnumAction.none;
}
public List<Entity> getEntitiesNear(World world, double x, double y, double z, float par4)
{
List<Entity> list = world.selectEntitiesWithinAABB(EntityLivingBase.class, AxisAlignedBB.getBoundingBox(x - par4, y - par4, z - par4, x + par4, y + par4, z + par4), IEntitySelector.selectAnything);
return list;
}
public void registerIcons(IIconRegister iconRegister)
{
itemIcon = iconRegister.registerIcon(TransformersMod.modid + ":" + iconString);
bassChargeIcon = iconRegister.registerIcon(TransformersMod.modid + ":bass_charge");
}
}<file_sep>/src/main/java/fiskfille/tf/common/motion/VehicleMotion.java
package fiskfille.tf.common.motion;
public class VehicleMotion
{
private double forwardVelocity;
private double horizontalVelocity;
private int nitro;
private boolean boosting;
private float roll;
private float pitch;
private float yaw;
public VehicleMotion(int nitro, double forwardVelocity, double horizontalVelocity)
{
this.forwardVelocity = forwardVelocity;
this.nitro = nitro;
this.boosting = false;
this.horizontalVelocity = horizontalVelocity;
}
public boolean isBoosting()
{
return boosting;
}
public void setBoosting(boolean boosting)
{
this.boosting = boosting;
}
public double getForwardVelocity()
{
return forwardVelocity;
}
public double getHorizontalVelocity()
{
return horizontalVelocity;
}
public int getNitro()
{
return nitro;
}
public void setForwardVelocity(double vel)
{
this.forwardVelocity = vel;
}
public void setHorizontalVelocity(double vel)
{
this.horizontalVelocity = vel;
}
public void setNitro(int nitro)
{
this.nitro = nitro;
}
public void setRoll(float roll)
{
this.roll = roll;
}
public float getRoll()
{
return roll;
}
public float getPitch()
{
return pitch;
}
public void setPitch(float pitch)
{
this.pitch = pitch;
}
public float getYaw()
{
return yaw;
}
public void setYaw(float yaw)
{
this.yaw = yaw;
}
}
<file_sep>/src/Legacy/java/fiskfille/tf/item/ItemBasic.java
package fiskfille.tf.item;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import fiskfille.tf.main.MainClass;
public class ItemBasic extends Item
{
public ItemBasic()
{
super();
this.setCreativeTab(MainClass.tabTransformers);
}
public void registerIcons(IIconRegister par1IconRegister)
{
itemIcon = par1IconRegister.registerIcon(MainClass.modid + ":" + iconString);
}
}<file_sep>/src/main/java/fiskfille/tf/web/PastebinFileReader.java
package fiskfille.tf.web;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
public class PastebinFileReader
{
public static String pastebinURLPrefix = "http://pastebin.com/raw.php?i=";
public static List<String> readPastebinAsList(String pastebinFileName) throws MalformedURLException, IOException
{
return FileDownloader.downloadFileList(pastebinURLPrefix + pastebinFileName);
}
public static String readPastebin(String pastebinFileName) throws MalformedURLException, IOException
{
return FileDownloader.downloadFile(pastebinURLPrefix + pastebinFileName);
}
}
<file_sep>/src/main/java/fiskfille/tf/common/event/PlayerTransformEvent.java
package fiskfille.tf.common.event;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.event.entity.player.PlayerEvent;
public class PlayerTransformEvent extends PlayerEvent
{
public final boolean transformed;
public final boolean stealthForce;
public PlayerTransformEvent(EntityPlayer player, boolean transformed, boolean stealthForce)
{
super(player);
this.transformed = transformed;
this.stealthForce = stealthForce;
}
}
<file_sep>/src/Legacy/java/fiskfille/tf/server/TFPacketHandler.java
//package fiskfille.tf.server;
//
//import io.netty.buffer.ByteBuf;
//import io.netty.channel.ChannelHandlerContext;
//import io.netty.channel.SimpleChannelInboundHandler;
//
//import java.util.EnumMap;
//import java.util.LinkedList;
//import java.util.List;
//
//import net.minecraft.client.Minecraft;
//import net.minecraft.entity.player.EntityPlayer;
//import net.minecraft.entity.player.EntityPlayerMP;
//import net.minecraft.network.Packet;
//import net.minecraft.tileentity.TileEntity;
//import net.minecraft.world.World;
//import net.minecraftforge.common.util.ForgeDirection;
//import cpw.mods.fml.common.FMLCommonHandler;
//import cpw.mods.fml.common.network.FMLEmbeddedChannel;
//import cpw.mods.fml.common.network.FMLIndexedMessageToMessageCodec;
//import cpw.mods.fml.common.network.FMLOutboundHandler;
//import cpw.mods.fml.common.network.NetworkRegistry;
//import cpw.mods.fml.relauncher.Side;
//import cpw.mods.fml.relauncher.SideOnly;
//
///**
// * Handles the packet wrangling for IronChest
// *
// * @author cpw
// */
//public enum TFPacketHandler
//{
// INSTANCE;
//
// /**
// * Our channel "pair" from {@link NetworkRegistry}
// */
// private EnumMap<Side, FMLEmbeddedChannel> channels;
//
//
// /**
// * Make our packet handler, and add an {@link IronChestCodec} always
// */
// private TFPacketHandler()
// {
// // request a channel pair for IronChest from the network registry
// // Add the IronChestCodec as a member of both channel pipelines
// this.channels = NetworkRegistry.INSTANCE.newChannel("Transformers", new TEAltarCodec());
//
// if (FMLCommonHandler.instance().getSide() == Side.CLIENT)
// {
// addClientHandler();
// }
// }
//
// @SideOnly(Side.CLIENT)
// private void addClientHandler()
// {
// FMLEmbeddedChannel clientChannel = this.channels.get(Side.CLIENT);
//
// String tileAltarCodec = clientChannel.findChannelHandlerNameForType(TEAltarCodec.class);
// clientChannel.pipeline().addAfter(tileAltarCodec, "DisplayPillarHandler", new TEAltarMessageHandler());
// }
//
//
// /**
// * This class simply handles the {@link IronChestMessage} when it's received
// * at the client side It can contain client only code, because it's only run
// * on the client.
// *
// * @author cpw
// */
// private static class TEAltarMessageHandler extends SimpleChannelInboundHandler<TEAltarMessage>
// {
// @Override
// protected void channelRead0(ChannelHandlerContext ctx, TEAltarMessage msg) throws Exception
// {
// World world = AlchemicalWizardry.proxy.getClientWorld();
//// TileEntity te = world.getTileEntity(msg.x, msg.y, msgz);
// if (te instanceof TEAltar)
// {
// TEAltar altar = (TEAltar) te;
//
// altar.handlePacketData(msg.items, msg.fluids, msg.capacity);
// }
// }
// }
//
// public static class BMMessage
// {
// int index;
// }
//
// public static class TEAltarMessage extends BMMessage
// {
// int x;
// int y;
// int z;
//
// int[] items;
// int[] fluids;
// int capacity;
// }
//
// private class TEAltarCodec extends FMLIndexedMessageToMessageCodec<BMMessage>
// {
// public TEAltarCodec()
// {
// addDiscriminator(0, TEAltarMessage.class);
// }
//
// @Override
// public void encodeInto(ChannelHandlerContext ctx, BMMessage msg, ByteBuf target) throws Exception
// {
// target.writeInt(msg.index);
//
// switch (msg.index)
// {
// case 0:
// target.writeInt(((TEAltarMessage) msg).x);
// target.writeInt(((TEAltarMessage) msg).y);
// target.writeInt(((TEAltarMessage) msg).z);
//
// target.writeBoolean(((TEAltarMessage) msg).items != null);
// if (((TEAltarMessage) msg).items != null)
// {
// int[] items = ((TEAltarMessage) msg).items;
// for (int j = 0; j < items.length; j++)
// {
// int i = items[j];
// target.writeInt(i);
// }
// }
//
// target.writeBoolean(((TEAltarMessage) msg).fluids != null);
// if (((TEAltarMessage) msg).fluids != null)
// {
// int[] fluids = ((TEAltarMessage) msg).fluids;
// for (int j = 0; j < fluids.length; j++)
// {
// int i = fluids[j];
// target.writeInt(i);
// }
// }
//
// target.writeInt(((TEAltarMessage) msg).capacity);
//
// break;
//
// case 1:
// target.writeInt(((TEOrientableMessage) msg).x);
// target.writeInt(((TEOrientableMessage) msg).y);
// target.writeInt(((TEOrientableMessage) msg).z);
//
// target.writeInt(((TEOrientableMessage) msg).input);
// target.writeInt(((TEOrientableMessage) msg).output);
//
// break;
//
// case 2:
// target.writeInt(((TEPedestalMessage) msg).x);
// target.writeInt(((TEPedestalMessage) msg).y);
// target.writeInt(((TEPedestalMessage) msg).z);
//
// target.writeBoolean(((TEPedestalMessage) msg).items != null);
// if (((TEPedestalMessage) msg).items != null)
// {
// int[] items = ((TEPedestalMessage) msg).items;
// for (int j = 0; j < items.length; j++)
// {
// int i = items[j];
// target.writeInt(i);
// }
// }
//
// break;
//
// case 3:
// target.writeInt(((TEPlinthMessage) msg).x);
// target.writeInt(((TEPlinthMessage) msg).y);
// target.writeInt(((TEPlinthMessage) msg).z);
//
// target.writeBoolean(((TEPlinthMessage) msg).items != null);
// if (((TEPlinthMessage) msg).items != null)
// {
// int[] items = ((TEPlinthMessage) msg).items;
// for (int j = 0; j < items.length; j++)
// {
// int i = items[j];
// target.writeInt(i);
// }
// }
//
// break;
//
// case 4:
// target.writeInt(((TESocketMessage) msg).x);
// target.writeInt(((TESocketMessage) msg).y);
// target.writeInt(((TESocketMessage) msg).z);
//
// target.writeBoolean(((TESocketMessage) msg).items != null);
// if (((TESocketMessage) msg).items != null)
// {
// int[] items = ((TESocketMessage) msg).items;
// for (int j = 0; j < items.length; j++)
// {
// int i = items[j];
// target.writeInt(i);
// }
// }
//
// break;
//
// case 5:
// target.writeInt(((TETeleposerMessage) msg).x);
// target.writeInt(((TETeleposerMessage) msg).y);
// target.writeInt(((TETeleposerMessage) msg).z);
//
// target.writeBoolean(((TETeleposerMessage) msg).items != null);
// if (((TETeleposerMessage) msg).items != null)
// {
// int[] items = ((TETeleposerMessage) msg).items;
// for (int j = 0; j < items.length; j++)
// {
// int i = items[j];
// target.writeInt(i);
// }
// }
//
// break;
//
// case 6:
// target.writeInt(((TEWritingTableMessage) msg).x);
// target.writeInt(((TEWritingTableMessage) msg).y);
// target.writeInt(((TEWritingTableMessage) msg).z);
//
// target.writeBoolean(((TEWritingTableMessage) msg).items != null);
// if (((TEWritingTableMessage) msg).items != null)
// {
// int[] items = ((TEWritingTableMessage) msg).items;
// for (int j = 0; j < items.length; j++)
// {
// int i = items[j];
// target.writeInt(i);
// }
// }
//
// break;
//
// case 7:
// String str = ((ParticleMessage) msg).particle;
// target.writeInt(str.length());
// for (int i = 0; i < str.length(); i++)
// {
// target.writeChar(str.charAt(i));
// }
//
// target.writeDouble(((ParticleMessage) msg).xCoord);
// target.writeDouble(((ParticleMessage) msg).yCoord);
// target.writeDouble(((ParticleMessage) msg).zCoord);
//
// target.writeDouble(((ParticleMessage) msg).xVel);
// target.writeDouble(((ParticleMessage) msg).yVel);
// target.writeDouble(((ParticleMessage) msg).zVel);
//
// break;
//
// case 8:
// target.writeDouble(((VelocityMessage) msg).xVel);
// target.writeDouble(((VelocityMessage) msg).yVel);
// target.writeDouble(((VelocityMessage) msg).zVel);
//
// break;
//
// case 9:
// target.writeInt(((TEMasterStoneMessage) msg).x);
// target.writeInt(((TEMasterStoneMessage) msg).y);
// target.writeInt(((TEMasterStoneMessage) msg).z);
//
// String ritual = ((TEMasterStoneMessage) msg).ritual;
// target.writeInt(ritual.length());
// for (int i = 0; i < ritual.length(); i++)
// {
// target.writeChar(ritual.charAt(i));
// }
//
// target.writeBoolean(((TEMasterStoneMessage) msg).isRunning);
//
// break;
//
// case 10:
// target.writeInt(((TEReagentConduitMessage) msg).x);
// target.writeInt(((TEReagentConduitMessage) msg).y);
// target.writeInt(((TEReagentConduitMessage) msg).z);
//
// List<ColourAndCoords> list = ((TEReagentConduitMessage) msg).destinationList;
// target.writeInt(list.size());
//
// for (ColourAndCoords colourSet : list)
// {
// target.writeInt(colourSet.colourRed);
// target.writeInt(colourSet.colourGreen);
// target.writeInt(colourSet.colourBlue);
// target.writeInt(colourSet.colourIntensity);
// target.writeInt(colourSet.xCoord);
// target.writeInt(colourSet.yCoord);
// target.writeInt(colourSet.zCoord);
// }
//
// break;
// }
// }
//
//
// @Override
// public void decodeInto(ChannelHandlerContext ctx, ByteBuf dat, BMMessage msg)
// {
// int index = dat.readInt();
//
// switch (index)
// {
// case 0:
// ((TEAltarMessage) msg).x = dat.readInt();
// ((TEAltarMessage) msg).y = dat.readInt();
// ((TEAltarMessage) msg).z = dat.readInt();
// boolean hasStacks = dat.readBoolean();
//
// ((TEAltarMessage) msg).items = new int[TEAltar.sizeInv * 3];
// if (hasStacks)
// {
// ((TEAltarMessage) msg).items = new int[TEAltar.sizeInv * 3];
// for (int i = 0; i < ((TEAltarMessage) msg).items.length; i++)
// {
// ((TEAltarMessage) msg).items[i] = dat.readInt();
// }
// }
//
// boolean hasFluids = dat.readBoolean();
// ((TEAltarMessage) msg).fluids = new int[6];
// if (hasFluids)
// for (int i = 0; i < ((TEAltarMessage) msg).fluids.length; i++)
// {
// ((TEAltarMessage) msg).fluids[i] = dat.readInt();
// }
//
// ((TEAltarMessage) msg).capacity = dat.readInt();
//
// break;
// }
// }
// }
//
// //Packets to be obtained
// public static Packet getPacket(TEAltar tileAltar)
// {
// TEAltarMessage msg = new TEAltarMessage();
// msg.index = 0;
// msg.x = tileAltar.xCoord;
// msg.y = tileAltar.yCoord;
// msg.z = tileAltar.zCoord;
// msg.items = tileAltar.buildIntDataList();
// msg.fluids = tileAltar.buildFluidList();
// msg.capacity = tileAltar.getCapacity();
//
// return INSTANCE.channels.get(Side.SERVER).generatePacketFrom(msg);
// }
//
// public void sendTo(Packet message, EntityPlayerMP player)
// {
// this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
// this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
// this.channels.get(Side.SERVER).writeAndFlush(message);
// }
//
// public void sendToAll(Packet message)
// {
// this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);
// this.channels.get(Side.SERVER).writeAndFlush(message);
// }
//
// public void sendToAllAround(Packet message, NetworkRegistry.TargetPoint point)
// {
// this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);
// this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point);
// this.channels.get(Side.SERVER).writeAndFlush(message);
// }
//}<file_sep>/src/main/java/fiskfille/tf/donator/Money.java
package fiskfille.tf.donator;
import java.util.regex.Pattern;
public class Money
{
private double money;
private String moneyString;
public Money(String moneyString)
{
this.moneyString = moneyString;
this.money = fromString(moneyString);
}
public void setMoney(String amount)
{
this.moneyString = amount;
this.money = fromString(amount);
}
private double fromString(String moneyString)
{
return Double.parseDouble(moneyString.replaceAll(Pattern.quote("$"), "").replaceAll(",", ""));
}
public double getMoney()
{
return money;
}
@Override
public String toString()
{
return moneyString;
}
}
<file_sep>/src/main/java/fiskfille/tf/common/entity/EntityMiniMissile.java
package fiskfille.tf.common.entity;
import java.util.List;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IProjectile;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class EntityMiniMissile extends EntityArrow implements IProjectile
{
private int blockX = -1;
private int blockY = -1;
private int blockZ = -1;
private boolean inGround;
/** Seems to be some sort of timer for animating an arrow. */
public int missileShake;
/** The owner of this arrow. */
public Entity shootingEntity;
private int ticksInAir;
private double damage = 4.0D;
/** The amount of knockback an arrow applies when it hits a mob. */
private int knockbackStrength;
private boolean missileExplosions;
public EntityMiniMissile(World world)
{
super(world);
this.renderDistanceWeight = 10.0D;
this.setSize(0.4F, 0.4F);
}
public EntityMiniMissile(World world, double x, double y, double z)
{
super(world);
this.renderDistanceWeight = 10.0D;
this.setSize(0.5F, 0.5F);
this.setPosition(x, y, z);
this.yOffset = 0.0F;
}
public EntityMiniMissile(World world, EntityLivingBase shooter, EntityLivingBase p_i1755_3_, float p_i1755_4_, float p_i1755_5_)
{
super(world);
this.renderDistanceWeight = 10.0D;
this.shootingEntity = shooter;
if (shooter instanceof EntityPlayer)
{
this.canBePickedUp = 1;
}
this.posY = shooter.posY + (double)shooter.getEyeHeight() - 0.10000000149011612D;
double d0 = p_i1755_3_.posX - shooter.posX;
double d1 = p_i1755_3_.boundingBox.minY + (double)(p_i1755_3_.height / 3.0F) - this.posY;
double d2 = p_i1755_3_.posZ - shooter.posZ;
double d3 = (double)MathHelper.sqrt_double(d0 * d0 + d2 * d2);
if (d3 >= 1.0E-7D)
{
float f2 = (float)(Math.atan2(d2, d0) * 180.0D / Math.PI) - 90.0F;
float f3 = (float)(-(Math.atan2(d1, d3) * 180.0D / Math.PI));
double d4 = d0 / d3;
double d5 = d2 / d3;
this.setLocationAndAngles(shooter.posX + d4, this.posY, shooter.posZ + d5, f2, f3);
this.yOffset = 0.0F;
float f4 = (float)d3 * 0.2F;
this.setThrowableHeading(d0, d1 + (double)f4, d2, p_i1755_4_, p_i1755_5_);
}
}
public EntityMiniMissile(World world, EntityLivingBase shooter, float strength, boolean allowMissileExplosions)
{
super(world);
this.renderDistanceWeight = 10.0D;
this.shootingEntity = shooter;
if (shooter instanceof EntityPlayer)
{
this.canBePickedUp = 1;
}
this.setSize(0.5F, 0.5F);
this.setLocationAndAngles(shooter.posX, shooter.posY + (double)shooter.getEyeHeight(), shooter.posZ, shooter.rotationYawHead, shooter.rotationPitch);
double dZ;
double dX;
dZ = Math.cos((double)this.rotationYaw * Math.PI / 180.0D) * (1.2D + rand.nextFloat());
dX = -Math.sin((double)this.rotationYaw * Math.PI / 180.0D) * (1.2D + rand.nextFloat());
this.posX += dX;
this.posZ += dZ;
this.posY += 0.6D;
this.setPosition(this.posX, this.posY, this.posZ);
this.yOffset = 0.0F;
this.motionX = (double)(-MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
this.motionZ = (double)(MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
this.motionY = (double)(-MathHelper.sin(this.rotationPitch / 180.0F * (float)Math.PI));
this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, strength * 1.5F, shooter.rotationPitch);
this.missileExplosions = allowMissileExplosions;
}
protected void entityInit()
{
this.dataWatcher.addObject(16, Byte.valueOf((byte)0));
}
/**
* Similar to setArrowHeading, it's point the throwable entity to a x, y, z direction.
*/
public void setThrowableHeading(double x, double y, double z, float p1, float p2)
{
float f2 = MathHelper.sqrt_double(x * x + y * y + z * z);
x /= (double)f2;
y /= (double)f2;
z /= (double)f2;
x *= (double)p1;
y *= (double)p1;
z *= (double)p1;
this.motionX = x;
this.motionY = y;
this.motionZ = z;
float f3 = MathHelper.sqrt_double(x * x + z * z);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(x, z) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(y, (double)f3) * 180.0D / Math.PI);
}
/**
* Sets the position and rotation. Only difference from the other one is no bounding on the rotation. Args: posX,
* posY, posZ, yaw, pitch
*/
@SideOnly(Side.CLIENT)
public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int p_70056_9_)
{
this.setPosition(x, y, z);
this.setRotation(yaw, pitch);
}
/**
* Sets the velocity to the args. Args: x, y, z
*/
@SideOnly(Side.CLIENT)
public void setVelocity(double xVel, double yVel, double zVel)
{
this.motionX = xVel;
this.motionY = yVel;
this.motionZ = zVel;
if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F)
{
float f = MathHelper.sqrt_double(xVel * xVel + zVel * zVel);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(xVel, zVel) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(yVel, (double)f) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch;
this.prevRotationYaw = this.rotationYaw;
this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch);
}
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate()
{
if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F)
{
float f = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(this.motionY, (double)f) * 180.0D / Math.PI);
}
Block block = this.worldObj.getBlock(this.blockX, this.blockY, this.blockZ);
if (block.getMaterial() != Material.air)
{
block.setBlockBoundsBasedOnState(this.worldObj, this.blockX, this.blockY, this.blockZ);
AxisAlignedBB axisalignedbb = block.getCollisionBoundingBoxFromPool(this.worldObj, this.blockX, this.blockY, this.blockZ);
if (axisalignedbb != null && axisalignedbb.isVecInside(Vec3.createVectorHelper(this.posX, this.posY, this.posZ)))
{
this.inGround = true;
}
}
if (this.missileShake > 0)
{
--this.missileShake;
}
if (this.inGround)
{
this.motionX = 0;
this.motionY = 0;
this.motionZ = 0;
worldObj.createExplosion(this.shootingEntity, blockX, blockY, blockZ, 2, missileExplosions);
this.setDead();
}
else
{
++this.ticksInAir;
for (int i = 0; i < 10; ++i)
{
Random rand = new Random();
worldObj.spawnParticle("smoke", posX + (rand.nextFloat() / 4), posY + (rand.nextFloat() / 4), posZ + (rand.nextFloat() / 4), 0, 0, 0);
}
Vec3 vecPos = Vec3.createVectorHelper(this.posX, this.posY, this.posZ);
Vec3 movementVec = Vec3.createVectorHelper(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
MovingObjectPosition movingobjectposition = this.worldObj.func_147447_a(vecPos, movementVec, false, true, false);
vecPos = Vec3.createVectorHelper(this.posX, this.posY, this.posZ);
movementVec = Vec3.createVectorHelper(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
if (movingobjectposition != null)
{
movementVec = Vec3.createVectorHelper(movingobjectposition.hitVec.xCoord, movingobjectposition.hitVec.yCoord, movingobjectposition.hitVec.zCoord);
}
Entity entity = null;
List entities = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D));
double d0 = 0.0D;
int i;
float gravity;
for (i = 0; i < entities.size(); ++i)
{
Entity entity1 = (Entity)entities.get(i);
if (entity1.canBeCollidedWith() && (entity1 != this.shootingEntity || this.ticksInAir >= 5))
{
gravity = 0.2F;
AxisAlignedBB axisalignedbb1 = entity1.boundingBox.expand((double)gravity, (double)gravity, (double)gravity);
MovingObjectPosition movingobjectposition1 = axisalignedbb1.calculateIntercept(vecPos, movementVec);
if (movingobjectposition1 != null)
{
double d1 = vecPos.distanceTo(movingobjectposition1.hitVec);
if (d1 < d0 || d0 == 0.0D)
{
entity = entity1;
d0 = d1;
}
}
}
}
if (entity != null)
{
movingobjectposition = new MovingObjectPosition(entity);
}
Entity entityHit = null;
if (movingobjectposition != null)
{
entityHit = movingobjectposition.entityHit;
}
if (movingobjectposition != null && entityHit != null && entityHit instanceof EntityPlayer)
{
EntityPlayer entityplayer = (EntityPlayer)entityHit;
if (entityplayer.capabilities.disableDamage || this.shootingEntity instanceof EntityPlayer && !((EntityPlayer)this.shootingEntity).canAttackPlayer(entityplayer))
{
movingobjectposition = null;
}
}
float f2;
float f4;
if (movingobjectposition != null)
{
if (entityHit != null && entityHit != shootingEntity)
{
f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ);
int k = MathHelper.ceiling_double_int((double)f2 * this.damage);
if (this.getIsCritical())
{
k += this.rand.nextInt(k / 2 + 2);
}
DamageSource damagesource = null;
if (this.shootingEntity == null)
{
damagesource = DamageSource.causeArrowDamage(this, this);
}
else
{
damagesource = DamageSource.causeArrowDamage(this, this.shootingEntity);
}
if (this.isBurning() && !(entityHit instanceof EntityEnderman))
{
entityHit.setFire(5);
}
if (entityHit.attackEntityFrom(damagesource, (float)k))
{
worldObj.createExplosion(shootingEntity, entityHit.posX, entityHit.posY, entityHit.posZ, 2, missileExplosions);
this.setDead();
}
else
{
this.motionX *= -0.10000000149011612D;
this.motionY *= -0.10000000149011612D;
this.motionZ *= -0.10000000149011612D;
this.rotationYaw += 180.0F;
this.prevRotationYaw += 180.0F;
this.ticksInAir = 0;
}
}
else
{
this.blockX = movingobjectposition.blockX;
this.blockY = movingobjectposition.blockY;
this.blockZ = movingobjectposition.blockZ;
this.motionX = (double)((float)(movingobjectposition.hitVec.xCoord - this.posX));
this.motionY = (double)((float)(movingobjectposition.hitVec.yCoord - this.posY));
this.motionZ = (double)((float)(movingobjectposition.hitVec.zCoord - this.posZ));
f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ);
this.posX -= this.motionX / (double)f2 * 0.05000000074505806D;
this.posY -= this.motionY / (double)f2 * 0.05000000074505806D;
this.posZ -= this.motionZ / (double)f2 * 0.05000000074505806D;
this.inGround = true;
this.missileShake = 7;
Block hitBlock = worldObj.getBlock(blockX, blockY, blockZ);
if (hitBlock.getMaterial() != Material.air)
{
hitBlock.onEntityCollidedWithBlock(this.worldObj, this.blockX, this.blockY, this.blockZ, this);
}
}
}
this.posX += this.motionX;
this.posY += this.motionY;
this.posZ += this.motionZ;
f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
for (this.rotationPitch = (float)(Math.atan2(this.motionY, (double)f2) * 180.0D / Math.PI); this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F)
{
;
}
while (this.rotationPitch - this.prevRotationPitch >= 180.0F)
{
this.prevRotationPitch += 360.0F;
}
while (this.rotationYaw - this.prevRotationYaw < -180.0F)
{
this.prevRotationYaw -= 360.0F;
}
while (this.rotationYaw - this.prevRotationYaw >= 180.0F)
{
this.prevRotationYaw += 360.0F;
}
this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
float slow = 0.99F;
gravity = 0.15F;
if (this.isInWater())
{
for (int l = 0; l < 4; ++l)
{
f4 = 0.25F;
this.worldObj.spawnParticle("bubble", this.posX - this.motionX * (double)f4, this.posY - this.motionY * (double)f4, this.posZ - this.motionZ * (double)f4, this.motionX, this.motionY, this.motionZ);
}
slow = 0.8F;
}
if (this.isWet())
{
this.extinguish();
}
this.motionX *= (double)slow;
this.motionY *= (double)slow;
this.motionZ *= (double)slow;
this.motionY -= (double)gravity;
this.setPosition(this.posX, this.posY, this.posZ);
this.func_145775_I();
}
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound nbt)
{
nbt.setShort("xTile", (short)this.blockX);
nbt.setShort("yTile", (short)this.blockY);
nbt.setShort("zTile", (short)this.blockZ);
nbt.setByte("shake", (byte)this.missileShake);
nbt.setByte("inGround", (byte)(this.inGround ? 1 : 0));
nbt.setByte("pickup", (byte)this.canBePickedUp);
nbt.setDouble("damage", this.damage);
nbt.setBoolean("explosions", this.missileExplosions);
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound nbt)
{
this.blockX = nbt.getShort("xTile");
this.blockY = nbt.getShort("yTile");
this.blockZ = nbt.getShort("zTile");
this.missileShake = nbt.getByte("shake") & 255;
this.inGround = nbt.getByte("inGround") == 1;
this.missileExplosions = nbt.getBoolean("explosions");
if (nbt.hasKey("damage", 99))
{
this.damage = nbt.getDouble("damage");
}
if (nbt.hasKey("pickup", 99))
{
this.canBePickedUp = nbt.getByte("pickup");
}
else if (nbt.hasKey("player", 99))
{
this.canBePickedUp = nbt.getBoolean("player") ? 1 : 0;
}
}
/**
* Called by a player entity when they collide with an entity
*/
public void onCollideWithPlayer(EntityPlayer player)
{
}
/**
* returns if this entity triggers Block.onEntityWalking on the blocks they walk on. used for spiders and wolves to
* prevent them from trampling crops
*/
protected boolean canTriggerWalking()
{
return false;
}
@SideOnly(Side.CLIENT)
public float getShadowSize()
{
return 0.0F;
}
public void setDamage(double p_70239_1_)
{
this.damage = p_70239_1_;
}
public double getDamage()
{
return this.damage;
}
/**
* Sets the amount of knockback the arrow applies when it hits a mob.
*/
public void setKnockbackStrength(int p_70240_1_)
{
this.knockbackStrength = p_70240_1_;
}
/**
* If returns false, the item will not inflict any damage against entities.
*/
public boolean canAttackWithItem()
{
return false;
}
}<file_sep>/src/main/java/fiskfille/tf/client/particle/TFParticles.java
package fiskfille.tf.client.particle;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.world.World;
public class TFParticles
{
private static Minecraft mc = Minecraft.getMinecraft();
private static World theWorld = mc.theWorld;
public static EntityFX spawnParticle(TFParticleType particleType, double x, double y, double z, float motionX, float motionY, float motionZ)
{
if (mc != null && mc.renderViewEntity != null && mc.effectRenderer != null)
{
if(theWorld.isRemote)
{
int particleSetting = mc.gameSettings.particleSetting;
if (particleSetting == 1 && theWorld.rand.nextInt(3) == 0)
{
particleSetting = 2;
}
double diffX = mc.renderViewEntity.posX - x;
double diffY = mc.renderViewEntity.posY - y;
double diffZ = mc.renderViewEntity.posZ - z;
EntityFX particle = null;
double maxRenderDistance = 16.0D;
if (diffX * diffX + diffY * diffY + diffZ * diffZ > maxRenderDistance * maxRenderDistance)
{
return null;
}
else if (particleSetting > 1)
{
return null;
}
else
{
particle = new EntityTFFlameFX(theWorld, x, y, z, motionX, motionY, motionZ);
mc.effectRenderer.addEffect(particle);
return (EntityFX)particle;
}
}
}
return null;
}
}<file_sep>/src/Legacy/java/fiskfille/tf/gui/GuiDisplayPillar.java
package fiskfille.tf.gui;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fiskfille.tf.container.ContainerDisplayPillar;
import fiskfille.tf.main.MainClass;
import fiskfille.tf.tileentity.TileEntityDisplayPillar;
@SideOnly(Side.CLIENT)
public class GuiDisplayPillar extends GuiContainer
{
private ResourceLocation texture = new ResourceLocation(MainClass.modid, "textures/gui/container/display_pillar.png");
public TileEntityDisplayPillar thePillar;
public GuiDisplayPillar(InventoryPlayer inventoryplayer, TileEntityDisplayPillar tile)
{
super(new ContainerDisplayPillar(inventoryplayer, tile));
this.thePillar = tile;
}
public void onGuiClosed()
{
super.onGuiClosed();
}
protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
String s = this.thePillar.hasCustomInventoryName() ? this.thePillar.getInventoryName() : I18n.format(this.thePillar.getInventoryName(), new Object[0]);
this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752);
this.fontRendererObj.drawString(I18n.format("container.inventory", new Object[0]), 8, this.ySize - 96 + 2, 4210752);
}
protected void drawGuiContainerBackgroundLayer(float f, int i, int j)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(texture);
int l = (width - xSize) / 2;
int i1 = (height - ySize) / 2;
drawTexturedModalRect(l, i1, 0, 0, xSize, ySize);
}
}<file_sep>/src/Legacy/java/fiskfille/tf/entity/fx/EntityTireFX.java
//package fiskfille.tf.entity.fx;
//
//import net.minecraft.client.particle.EntityFX;
//import net.minecraft.client.particle.EntityFootStepFX;
//
//public class EntityTireFX extends EntityFX {
//EntityFootStepFX
//}
<file_sep>/src/main/java/fiskfille/tf/client/render/item/RenderItemDisplayVehicle.java
package fiskfille.tf.client.render.item;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.IItemRenderer;
import org.lwjgl.opengl.GL11;
import fiskfille.tf.TransformersAPI;
import fiskfille.tf.TransformersMod;
import fiskfille.tf.client.model.transformer.TFModelRegistry;
import fiskfille.tf.client.model.transformer.vehicle.ModelVehicleBase;
import fiskfille.tf.common.transformer.base.Transformer;
public class RenderItemDisplayVehicle implements IItemRenderer
{
public ModelVehicleBase getModelFromMetadata(int metadata)
{
Transformer transformer = TransformersAPI.getTransformers().get(metadata);
if(transformer != null)
{
return TFModelRegistry.getVehicleModel(transformer);
}
return null;
}
public String getTextureFromMetadata(int metadata)
{
Transformer transformer = TransformersAPI.getTransformers().get(metadata);
if(transformer != null)
{
String name = transformer.getName().toLowerCase().replaceAll(" ", "_");
return name + "/" + name + ".png";
}
return null;
}
public boolean handleRenderType(ItemStack item, ItemRenderType type)
{
return type != type.FIRST_PERSON_MAP;
}
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper)
{
return type == type.INVENTORY || type == type.ENTITY || type == type.EQUIPPED_FIRST_PERSON;
}
public void renderItem(ItemRenderType type, ItemStack item, Object... data)
{
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(TransformersMod.modid, "textures/models/" + getTextureFromMetadata(item.getItemDamage())));
ModelVehicleBase model = getModelFromMetadata(item.getItemDamage());
if (type == ItemRenderType.EQUIPPED_FIRST_PERSON)
{
GL11.glPushMatrix();
GL11.glRotatef(180, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(210, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(20, 0.0F, 0.0F, 1.0F);
GL11.glTranslatef(-0.6F, -2.0F, 0.7F);
float scale = 0.7F;
GL11.glScalef(scale, scale, scale);
model.render();
GL11.glPopMatrix();
}
else if (type == ItemRenderType.EQUIPPED)
{
GL11.glPushMatrix();
GL11.glRotatef(180, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(-45, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(-45, 0.0F, 0.0F, 1.0F);
GL11.glTranslatef(0.3F, -0.9F, -0.2F);
float scale = 0.7F;
GL11.glScalef(scale, scale, scale);
model.render();
GL11.glPopMatrix();
}
else if (type == ItemRenderType.INVENTORY)
{
GL11.glPushMatrix();
GL11.glRotatef(180, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(0, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(0, 0.0F, 0.0F, 1.0F);
GL11.glTranslatef(0.0F, -1.0F, 0.0F);
float scale = 1.0F;
GL11.glScalef(scale, scale, scale);
model.render();
GL11.glPopMatrix();
}
else if (type == ItemRenderType.ENTITY)
{
GL11.glPushMatrix();
GL11.glRotatef(180, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(0, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(0, 0.0F, 0.0F, 1.0F);
GL11.glTranslatef(0.0F, -0.5F, 0.0F);
float scale = 0.5F;
GL11.glScalef(scale, scale, scale);
model.render();
GL11.glPopMatrix();
}
}
}<file_sep>/src/Legacy/java/fiskfille/tf/main/MainClass.java
package fiskfille.tf.main;
import net.minecraft.client.Minecraft;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import cpw.mods.fml.common.FMLCommonHandler;
//Gegy is not as good as Fisk ;)
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import fiskfille.tf.entity.EntityLaser;
import fiskfille.tf.generator.OreWorldGenerator;
import fiskfille.tf.gui.GuiHandlerTF;
import fiskfille.tf.gui.GuiOverlay;
import fiskfille.tf.main.misc.CommonProxy;
import fiskfille.tf.main.misc.CreativeTabTransformers;
import fiskfille.tf.main.misc.TickHandler;
import fiskfille.tf.server.TFPacketPipeline;
@Mod(modid = MainClass.modid, name = "Transformers Mod", version = MainClass.version, guiFactory = "fiskfille.tf.gui.TFGuiFactory")
public class MainClass
{
@Instance(MainClass.modid)
public static MainClass instance;
public static Configuration configFile;
public static final String modid = "transformers";
public static final String version = "0.4";
public static TFPacketPipeline packetPipeline;
@SidedProxy(clientSide = "fiskfille.tf.main.misc.ClientProxy", serverSide = "fiskfille.tf.main.misc.CommonProxy")
public static CommonProxy proxy;
public TFConfig config = new TFConfig();
public TFItems items = new TFItems();
public TFBlocks blocks = new TFBlocks();
public static CreativeTabs tabTransformers = new CreativeTabTransformers();
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
configFile = new Configuration(event.getSuggestedConfigurationFile());
configFile.load();
config.load(configFile);
configFile.save();
items.load(config);
blocks.load(config);
TFRecipes.load();
// EntityRegistry.registerModEntity(EntityLaser.class, "laser", 305, MainClass.modid, 1, 10, true);
GameRegistry.registerWorldGenerator(new OreWorldGenerator(), 0);
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandlerTF());
proxy.registerRenderInformation();
proxy.registerKeyBinds();
proxy.registerTickHandler();
MinecraftForge.EVENT_BUS.register(new CommonEventHandler());
FMLCommonHandler.instance().bus().register(new CommonEventHandler());
FMLCommonHandler.instance().bus().register(new TickHandler());
if (event.getSide().isClient())
{
MinecraftForge.EVENT_BUS.register(new ClientEventHandler());
FMLCommonHandler.instance().bus().register(new ClientEventHandler());
MinecraftForge.EVENT_BUS.register(new GuiOverlay(Minecraft.getMinecraft()));
}
packetPipeline = new TFPacketPipeline();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
packetPipeline.initialize();
}
@EventHandler
public void postInit(FMLPostInitializationEvent event)
{
packetPipeline.postInitialize();
}
}<file_sep>/src/main/java/fiskfille/tf/common/packet/PacketSendFlying.java
package fiskfille.tf.common.packet;
import fiskfille.tf.TransformersMod;
import fiskfille.tf.client.tick.ClientTickHandler;
import fiskfille.tf.common.packet.base.TFPacketManager;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
public class PacketSendFlying implements IMessage
{
private int id;
private boolean flying;
public PacketSendFlying()
{
}
public PacketSendFlying(EntityPlayer player, boolean f)
{
id = player.getEntityId();
flying = f;
}
public void fromBytes(ByteBuf buf)
{
id = buf.readInt();
flying = buf.readBoolean();
}
public void toBytes(ByteBuf buf)
{
buf.writeInt(id);
buf.writeBoolean(flying);
}
public static class Handler implements IMessageHandler<PacketSendFlying, IMessage>
{
public IMessage onMessage(PacketSendFlying message, MessageContext ctx)
{
if (ctx.side.isClient())
{
EntityPlayer player = TransformersMod.proxy.getPlayer();
EntityPlayer from = null;
Entity entity = player.worldObj.getEntityByID(message.id);
if (entity instanceof EntityPlayer) from = (EntityPlayer) entity;
if (from != null && from != player)
{
from.capabilities.isFlying = message.flying;
}
}
return null;
}
}
}<file_sep>/src/Legacy/java/fiskfille/tf/model/vehicle/ModelVurpVehicle.java
package fiskfille.tf.model.vehicle;
import net.minecraft.client.model.ModelRenderer;
import fiskfille.tf.model.ModelChildBase;
public class ModelVurpVehicle extends ModelVehicleBase
{
ModelRenderer vehichleFrontWheel1;
ModelRenderer vehichleFrontWheel2;
ModelRenderer vehichleBackWheel1;
ModelRenderer vehichleBackWheel2;
ModelRenderer vehichleBumper1;
ModelRenderer vehichleBumper2;
ModelRenderer vehichleRoof;
ModelRenderer vehichleBody;
ModelRenderer vehichleHood;
ModelRenderer vehichleBackWindShield;
ModelRenderer vehichleWindShield;
ModelRenderer vehichleSpoiler;
ModelRenderer vehichleDoor1;
ModelRenderer vehichleDoor2;
public ModelVurpVehicle()
{
textureWidth = 64;
textureHeight = 128;
vehichleFrontWheel1 = new ModelRenderer(this, 0, 64);
vehichleFrontWheel1.addBox(-1F, -1F, -1F, 1, 2, 2);
vehichleFrontWheel1.setRotationPoint(-2.3F, 23F, -4.5F);
vehichleFrontWheel1.setTextureSize(64, 128);
vehichleFrontWheel1.mirror = true;
setRotation(vehichleFrontWheel1, 0F, 0F, 0F);
vehichleFrontWheel2 = new ModelRenderer(this, 0, 64);
vehichleFrontWheel2.addBox(0F, -1F, -1F, 1, 2, 2);
vehichleFrontWheel2.setRotationPoint(2.3F, 23F, -4.5F);
vehichleFrontWheel2.setTextureSize(64, 128);
vehichleFrontWheel2.mirror = true;
setRotation(vehichleFrontWheel2, 0F, 0F, 0F);
vehichleBackWheel1 = new ModelRenderer(this, 0, 64);
vehichleBackWheel1.addBox(-1F, -1F, -1F, 1, 2, 2);
vehichleBackWheel1.setRotationPoint(-2.3F, 23F, 4F);
vehichleBackWheel1.setTextureSize(64, 128);
vehichleBackWheel1.mirror = true;
setRotation(vehichleBackWheel1, 0F, 0F, 0F);
vehichleBackWheel2 = new ModelRenderer(this, 0, 64);
vehichleBackWheel2.addBox(0F, -1F, -1F, 1, 2, 2);
vehichleBackWheel2.setRotationPoint(2.3F, 23F, 4F);
vehichleBackWheel2.setTextureSize(64, 128);
vehichleBackWheel2.mirror = true;
setRotation(vehichleBackWheel2, 0F, 0F, 0F);
vehichleBumper1 = new ModelRenderer(this, 0, 68);
vehichleBumper1.addBox(-2.5F, -1.5F, -2F, 3, 2, 2);
vehichleBumper1.setRotationPoint(0F, 23F, -5F);
vehichleBumper1.setTextureSize(64, 128);
vehichleBumper1.mirror = true;
setRotation(vehichleBumper1, 0F, 0.2443461F, 0F);
vehichleBumper2 = new ModelRenderer(this, 0, 68);
vehichleBumper2.mirror = true;
vehichleBumper2.addBox(-0.5F, -1.5F, -2F, 3, 2, 2);
vehichleBumper2.setRotationPoint(0F, 23F, -5F);
vehichleBumper2.setTextureSize(64, 128);
setRotation(vehichleBumper2, 0F, -0.2443461F, 0F);
vehichleBumper2.mirror = true;
vehichleRoof = new ModelRenderer(this, 0, 78);
vehichleRoof.addBox(-2.5F, -0.5F, 0F, 5, 1, 2);
vehichleRoof.setRotationPoint(0F, 20.7F, -0.5F);
vehichleRoof.setTextureSize(64, 128);
vehichleRoof.mirror = true;
setRotation(vehichleRoof, 0F, 0F, 0F);
vehichleBody = new ModelRenderer(this, 0, 64);
vehichleBody.addBox(-3F, -1F, 0F, 6, 2, 12);
vehichleBody.setRotationPoint(0F, 22.5F, -6.2F);
vehichleBody.setTextureSize(64, 128);
vehichleBody.mirror = true;
setRotation(vehichleBody, 0F, 0F, 0F);
vehichleHood = new ModelRenderer(this, 0, 81);
vehichleHood.addBox(-2F, -1F, -2F, 4, 1, 3);
vehichleHood.setRotationPoint(0F, 22.3F, -3.7F);
vehichleHood.setTextureSize(64, 128);
vehichleHood.mirror = true;
setRotation(vehichleHood, 0F, 0F, 0F);
vehichleBackWindShield = new ModelRenderer(this, 14, 78);
vehichleBackWindShield.addBox(-2.5F, -0.5F, 0F, 5, 1, 3);
vehichleBackWindShield.setRotationPoint(0F, 20.7F, 1.3F);
vehichleBackWindShield.setTextureSize(64, 128);
vehichleBackWindShield.mirror = true;
setRotation(vehichleBackWindShield, -0.3839724F, 0F, 0F);
vehichleWindShield = new ModelRenderer(this, 14, 82);
vehichleWindShield.addBox(-2.5F, -1F, 0F, 5, 1, 3);
vehichleWindShield.setRotationPoint(0F, 22.4F, -2.7F);
vehichleWindShield.setTextureSize(64, 128);
vehichleWindShield.mirror = true;
setRotation(vehichleWindShield, 0.4537856F, 0F, 0F);
vehichleSpoiler = new ModelRenderer(this, 24, 64);
vehichleSpoiler.addBox(-2.5F, -1F, -1.5F, 5, 1, 3);
vehichleSpoiler.setRotationPoint(0F, 22F, 4.8F);
vehichleSpoiler.setTextureSize(64, 128);
vehichleSpoiler.mirror = true;
setRotation(vehichleSpoiler, 0.1919862F, 0F, 0F);
vehichleDoor1 = new ModelRenderer(this, 24, 68);
vehichleDoor1.addBox(-1F, -1F, -1.5F, 1, 1, 3);
vehichleDoor1.setRotationPoint(-1.8F, 21.7F, 0.5F);
vehichleDoor1.setTextureSize(64, 128);
vehichleDoor1.mirror = true;
setRotation(vehichleDoor1, 0F, 0F, 0.2268928F);
vehichleDoor2 = new ModelRenderer(this, 24, 68);
vehichleDoor2.addBox(0F, -1F, -1.5F, 1, 1, 3);
vehichleDoor2.setRotationPoint(1.8F, 21.7F, 0.5F);
vehichleDoor2.setTextureSize(64, 128);
vehichleDoor2.mirror = true;
setRotation(vehichleDoor2, 0F, 0F, -0.2268928F);
this.addChildTo(vehichleFrontWheel1, vehichleBody);
this.addChildTo(vehichleFrontWheel2, vehichleBody);
this.addChildTo(vehichleBackWheel1, vehichleBody);
this.addChildTo(vehichleBackWheel2, vehichleBody);
this.addChildTo(vehichleBumper1, vehichleBody);
this.addChildTo(vehichleBumper2, vehichleBody);
this.addChildTo(vehichleRoof, vehichleBody);
this.addChildTo(vehichleHood, vehichleBody);
this.addChildTo(vehichleBackWindShield, vehichleBody);
this.addChildTo(vehichleWindShield, vehichleBody);
this.addChildTo(vehichleSpoiler, vehichleBody);
this.addChildTo(vehichleDoor1, vehichleBody);
this.addChildTo(vehichleDoor2, vehichleBody);
}
public void render()
{
vehichleBody.render(0.0625F);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
}<file_sep>/src/Legacy/java/fiskfille/tf/model/ModelChildBase.java
package fiskfille.tf.model;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelRenderer;
public class ModelChildBase
{
public static class Base extends ModelBase
{
public float pi = (float)Math.PI;
protected void addChildTo(ModelRenderer child, ModelRenderer parent)
{
child.rotationPointX -= parent.rotationPointX;
child.rotationPointY -= parent.rotationPointY;
child.rotationPointZ -= parent.rotationPointZ;
child.rotateAngleX -= parent.rotateAngleX;
child.rotateAngleY -= parent.rotateAngleY;
child.rotateAngleZ -= parent.rotateAngleZ;
parent.addChild(child);
}
protected void addChildToWithoutPoint(ModelRenderer child, ModelRenderer parent)
{
child.rotateAngleX -= parent.rotateAngleX;
child.rotateAngleY -= parent.rotateAngleY;
child.rotateAngleZ -= parent.rotateAngleZ;
parent.addChild(child);
}
}
public static class Biped extends ModelBiped
{
public float pi = (float)Math.PI;
protected void addChildTo(ModelRenderer child, ModelRenderer parent)
{
child.rotationPointX -= parent.rotationPointX;
child.rotationPointY -= parent.rotationPointY;
child.rotationPointZ -= parent.rotationPointZ;
child.rotateAngleX -= parent.rotateAngleX;
child.rotateAngleY -= parent.rotateAngleY;
child.rotateAngleZ -= parent.rotateAngleZ;
parent.addChild(child);
}
protected void addChildToWithoutPoint(ModelRenderer child, ModelRenderer parent)
{
child.rotateAngleX -= parent.rotateAngleX;
child.rotateAngleY -= parent.rotateAngleY;
child.rotateAngleZ -= parent.rotateAngleZ;
parent.addChild(child);
}
}
}<file_sep>/src/main/java/fiskfille/tf/common/tileentity/TileEntityCrystal.java
package fiskfille.tf.common.tileentity;
import net.minecraft.tileentity.TileEntity;
public class TileEntityCrystal extends TileEntity{
}
<file_sep>/src/main/java/fiskfille/tf/client/model/item/ModelFlamethrower.java
package fiskfille.tf.client.model.item;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
/**
* Damn this is horrible code! @gegy1000
*/
public class ModelFlamethrower extends ModelBase
{
ModelRenderer box1;
ModelRenderer box2;
ModelRenderer box3;
ModelRenderer box4;
ModelRenderer box5;
ModelRenderer box6;
ModelRenderer box7;
ModelRenderer box8;
ModelRenderer box9;
ModelRenderer box10;
ModelRenderer box11;
ModelRenderer box12;
ModelRenderer box13;
ModelRenderer box14;
ModelRenderer box15;
ModelRenderer box16;
ModelRenderer box17;
public ModelFlamethrower()
{
textureWidth = 64;
textureHeight = 64;
box1 = new ModelRenderer(this, 0, 7);
box1.addBox(-3F, -3F, -1.5F, 6, 3, 3, 0F);
box1.setRotationPoint(0F, 0F, 0F);
box1.setTextureSize(512, 512);
box1.mirror = true;
setRotation(box1, 0F, 0F, 0F);
box2 = new ModelRenderer(this, 0, 13);
box2.addBox(3F, -1F, -1F, 6, 2, 2, 0F);
box2.setRotationPoint(0F, 0F, 0F);
box2.setTextureSize(512, 512);
box2.mirror = true;
setRotation(box2, 0F, 0F, 0F);
box3 = new ModelRenderer(this, 0, 17);
box3.addBox(-1F, -0.2F, -0.5F, 5, 2, 1, 0F);
box3.setRotationPoint(0F, 0F, 0F);
box3.setTextureSize(512, 512);
box3.mirror = true;
setRotation(box3, 0F, 0F, -0.19198622F);
box4 = new ModelRenderer(this, 0, 20);
box4.addBox(-2F, -3.5F, -0.5F, 12, 4, 1, 0F);
box4.setRotationPoint(0F, 0F, 0F);
box4.setTextureSize(512, 512);
box4.mirror = true;
setRotation(box4, 0F, 0F, 0F);
box5 = new ModelRenderer(this, 0, 25);
box5.addBox(6.35F, -3F, -1.5F, 3, 1, 3, 0F);
box5.setRotationPoint(0F, 0F, 0F);
box5.setTextureSize(512, 512);
box5.mirror = true;
setRotation(box5, 0F, 0F, 0F);
box6 = new ModelRenderer(this, 0, 29);
box6.addBox(-1F, -2F, -3F, 3, 1, 1, 0F);
box6.setRotationPoint(0F, 0F, 0F);
box6.setTextureSize(512, 512);
box6.mirror = true;
setRotation(box6, 0F, -0.59341195F, 0F);
box7 = new ModelRenderer(this, 0, 29);
box7.addBox(-1F, -2F, 2F, 3, 1, 1, 0F);
box7.setRotationPoint(0F, 0F, 0F);
box7.setTextureSize(512, 512);
box7.mirror = true;
setRotation(box7, 0F, 0.59341195F, 0F);
box8 = new ModelRenderer(this, 0, 29);
box8.addBox(-3F, -2F, 0F, 3, 1, 1, 0F);
box8.setRotationPoint(0F, 0F, 0F);
box8.setTextureSize(512, 512);
box8.mirror = true;
setRotation(box8, 0F, 0.59341195F, 0F);
box9 = new ModelRenderer(this, 0, 29);
box9.addBox(-3F, -2F, -1F, 3, 1, 1, 0F);
box9.setRotationPoint(0F, 0F, 0F);
box9.setTextureSize(512, 512);
box9.mirror = true;
setRotation(box9, 0F, -0.59341195F, 0F);
box10 = new ModelRenderer(this, 0, 31);
box10.addBox(9.35F, -3F, -1.5F, 1, 3, 3, 0F);
box10.setRotationPoint(0F, 0F, 0F);
box10.setTextureSize(512, 512);
box10.mirror = true;
setRotation(box10, 0F, 0F, 0F);
box11 = new ModelRenderer(this, 6, 29);
box11.addBox(10.35F, -2.5F, -1F, 1, 2, 2, 0F);
box11.setRotationPoint(0F, 0F, 0F);
box11.setTextureSize(512, 512);
box11.mirror = true;
setRotation(box11, 0F, 0F, 0F);
box12 = new ModelRenderer(this, 8, 0);
box12.addBox(1F, 1.8F, -1.5F, 3, 4, 3, 0F);
box12.setRotationPoint(0F, 0F, 0F);
box12.setTextureSize(512, 512);
box12.mirror = true;
setRotation(box12, 0F, 0F, -0.19198622F);
box13 = new ModelRenderer(this, 12, 25);
box13.addBox(-1F, 0F, -0.5F, 2, 4, 1, 0F);
box13.setRotationPoint(0F, 0F, 0F);
box13.setTextureSize(512, 512);
box13.mirror = true;
setRotation(box13, 0F, 0F, 0.83775804F);
box14 = new ModelRenderer(this, 0, 2);
box14.addBox(-4F, -4F, -1F, 2, 3, 2, 0F);
box14.setRotationPoint(0F, 0F, 0F);
box14.setTextureSize(512, 512);
box14.mirror = true;
setRotation(box14, 0F, 0F, 0F);
box15 = new ModelRenderer(this, 14, 15);
box15.addBox(8.5F, -4F, -1F, 1, 2, 2, 0F);
box15.setRotationPoint(0F, 0F, 0F);
box15.setTextureSize(512, 512);
box15.mirror = true;
setRotation(box15, 0F, 0F, 0F);
box16 = new ModelRenderer(this, 0, 0);
box16.addBox(10F, -0.5F, -0.5F, 3, 1, 1, 0F);
box16.setRotationPoint(0F, 0F, 0F);
box16.setTextureSize(512, 512);
box16.mirror = true;
setRotation(box16, 0F, 0F, 0F);
box17 = new ModelRenderer(this, 17, 0);
box17.addBox(12F, -0.5F, -0.5F, 1, 1, 1, 0F);
box17.setRotationPoint(0F, 0F, 0F);
box17.setTextureSize(512, 512);
box17.mirror = true;
setRotation(box17, 0F, 0F, -0.05235988F);
}
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5)
{
super.render(entity, f, f1, f2, f3, f4, f5);
setRotationAngles(f, f1, f2, f3, f4, f5, entity);
box1.render(f5);
box2.render(f5);
box3.render(f5);
box4.render(f5);
box5.render(f5);
box6.render(f5);
box7.render(f5);
box8.render(f5);
box9.render(f5);
box10.render(f5);
box11.render(f5);
box12.render(f5);
box13.render(f5);
box14.render(f5);
box15.render(f5);
box16.render(f5);
box17.render(f5);
}
public void render()
{
float f5 = 0.0625F;
box1.render(f5);
box2.render(f5);
box3.render(f5);
box4.render(f5);
box5.render(f5);
box6.render(f5);
box7.render(f5);
box8.render(f5);
box9.render(f5);
box10.render(f5);
box11.render(f5);
box12.render(f5);
box13.render(f5);
box14.render(f5);
box15.render(f5);
box16.render(f5);
box17.render(f5);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity)
{
super.setRotationAngles(f, f1, f2, f3, f4, f5, entity);
}
}
<file_sep>/src/main/java/fiskfille/tf/client/tick/ClientTickHandler.java
package fiskfille.tf.client.tick;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import org.lwjgl.input.Keyboard;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import fiskfille.tf.client.keybinds.TFKeyBinds;
import fiskfille.tf.client.particle.NitroParticleHandler;
import fiskfille.tf.client.render.entity.CustomEntityRenderer;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.motion.TFMotionManager;
import fiskfille.tf.common.motion.VehicleMotion;
import fiskfille.tf.common.packet.PacketCloudtrapJetpack;
import fiskfille.tf.common.packet.base.TFPacketManager;
import fiskfille.tf.common.playerdata.TFDataManager;
import fiskfille.tf.common.playerdata.TFPlayerData;
import fiskfille.tf.common.transformer.base.Transformer;
import fiskfille.tf.config.TFConfig;
import fiskfille.tf.helper.TFHelper;
public class ClientTickHandler
{
public static Map<EntityPlayer, Boolean> cloudtrapJetpacking = new HashMap<EntityPlayer, Boolean>();
private Minecraft mc = Minecraft.getMinecraft();
private boolean prevJetpacking;
public void onPlayerTick(EntityPlayer player)
{
ItemStack heldItem = player.getHeldItem();
Transformer transformer = TFHelper.getTransformer(player);
boolean inVehicleMode = TFDataManager.isInVehicleMode(player);
int transformationTimer = TFDataManager.getTransformationTimer(player);
int stealthModeTimer = TFDataManager.getStealthModeTimer(player);
if (stealthModeTimer < 5 && !TFDataManager.isInStealthMode(player))
{
TFDataManager.setStealthModeTimer(player, stealthModeTimer + 1);
}
else if (stealthModeTimer > 0 && TFDataManager.isInStealthMode(player))
{
TFDataManager.setStealthModeTimer(player, stealthModeTimer - 1);
}
if (TFHelper.isPlayerVurp(player) && heldItem != null && heldItem.getItem() == TFItems.vurpsSniper && TFKeyBinds.keyBindingZoom.getIsKeyPressed())
{
if (TFDataManager.getZoomTimer(player) < 10)
{
TFDataManager.setZoomTimer(player, TFDataManager.getZoomTimer(player) + 1);
}
}
else
{
if (TFDataManager.getZoomTimer(player) > 0)
{
TFDataManager.setZoomTimer(player, TFDataManager.getZoomTimer(player) - 1);
}
}
VehicleMotion transformedPlayer = TFMotionManager.getTransformerPlayer(player);
if (inVehicleMode && transformationTimer < 10)
{
player.setSprinting(false);
if (player == mc.thePlayer)
{
GameSettings gameSettings = mc.gameSettings;
if (Keyboard.isKeyDown(Keyboard.KEY_R) && mc.currentScreen == null)
{
gameSettings.thirdPersonView = 2;
}
else if (TFKeyBinds.keyBindingVehicleFirstPerson.getIsKeyPressed())
{
gameSettings.thirdPersonView = 0;
}
else
{
gameSettings.thirdPersonView = 3;
}
if(transformer != null)
{
transformer.updateMovement(player);
}
}
NitroParticleHandler.doNitroParticles(player);
}
else
{
if (transformer != null)
{
if (transformer.hasJetpack())
{
boolean isClientPlayer = mc.thePlayer == player;
boolean jetpacking = mc.gameSettings.keyBindJump.getIsKeyPressed();
if (isClientPlayer)
{
if (prevJetpacking != jetpacking)
{
TFPacketManager.networkWrapper.sendToServer(new PacketCloudtrapJetpack(player, jetpacking));
prevJetpacking = jetpacking;
}
}
else
{
if(cloudtrapJetpacking.get(player))
{
for (int i = 0; i < 20; ++i)
{
Random rand = new Random();
player.worldObj.spawnParticle("flame", player.posX, player.posY, player.posZ, rand.nextFloat() / 4 - 0.125F, -0.8F, rand.nextFloat() / 4 - 0.125F);
}
}
}
if (jetpacking)
{
player.motionY += 0.09F;
if (isClientPlayer)
{
for (int i = 0; i < 20; ++i)
{
Random rand = new Random();
player.worldObj.spawnParticle("flame", player.posX, player.posY - 1.5F, player.posZ, rand.nextFloat() / 4 - 0.125F, -0.8F, rand.nextFloat() / 4 - 0.125F);
}
}
}
}
}
player.stepHeight = 0.5F;
if (player.isPotionActive(Potion.resistance) && player.getActivePotionEffect(Potion.resistance).getDuration() < 1)
{
player.removePotionEffect(Potion.resistance.id);
}
}
int nitro = transformedPlayer == null ? 0 : transformedPlayer.getNitro();
boolean moveForward = mc.gameSettings.keyBindForward.getIsKeyPressed();
boolean nitroPressed = TFKeyBinds.keyBindingNitro.getIsKeyPressed() || mc.gameSettings.keyBindSprint.getIsKeyPressed();
if ((nitro < 160 && (player.capabilities.isCreativeMode || !((nitroPressed && !TFDataManager.isInStealthMode(player)) && moveForward && inVehicleMode && transformationTimer < 10))))
{
++nitro;
}
TFMotionManager.setNitro(player, nitro);
if(transformer == null && TFPlayerData.getData(player).vehicle)
{
TFDataManager.setInVehicleMode(player, false);
}
}
private float getCameraOffset(EntityPlayer player, Transformer transformer)
{
if (transformer != null)
{
if (TFDataManager.getTransformationTimer(player) > 10)
{
return transformer.getCameraYOffset(player);
}
else
{
return transformer.getVehicleCameraYOffset(player);
}
}
else
{
return -1;
}
}
public void handleTransformation(EntityPlayer player)
{
Transformer transformer = TFHelper.getTransformer(player);
int transformationTimer = TFDataManager.getTransformationTimer(player);
boolean inVehicleMode = TFDataManager.isInVehicleMode(player);
VehicleMotion transformedPlayer = TFMotionManager.getTransformerPlayer(player);
float offsetY = getCameraOffset(player, transformer) + (float)transformationTimer / 20;
CustomEntityRenderer.setOffsetY(player, offsetY);
if (transformationTimer < 20 && !inVehicleMode)
{
transformationTimer++;
TFDataManager.setTransformationTimer(player, transformationTimer);
if(transformer != null)
{
transformer.transformationTick(player, transformationTimer);
}
TFMotionManager.setForwardVelocity(player, 0.0D);
if (transformationTimer == 19)
{
if (mc.thePlayer == player)
{
mc.gameSettings.thirdPersonView = TFConfig.firstPersonAfterTransformation ? 0 : mc.gameSettings.thirdPersonView;
}
}
}
else if (transformationTimer > 0 && inVehicleMode)
{
transformationTimer--;
TFDataManager.setTransformationTimer(player, transformationTimer);
if(transformer != null)
{
transformer.transformationTick(player, transformationTimer);
}
}
}
public void onTickEnd()
{
EntityPlayer player = mc.thePlayer;
try
{
Transformer transformer = TFHelper.getTransformer(player);
float thirdPersonDistance = 4.0F - (2.0F - (float)TFDataManager.getTransformationTimer(player) / 10);
if (transformer != null && (transformer.canZoom(player)) && TFDataManager.isInVehicleMode(player) && TFKeyBinds.keyBindingZoom.getIsKeyPressed())
{
thirdPersonDistance = transformer.getZoomAmount(player);
}
else
{
thirdPersonDistance = transformer.getThirdPersonDistance(player);
}
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, mc.entityRenderer, thirdPersonDistance, new String[]{"thirdPersonDistance", "E", "field_78490_B"});
}
catch (Exception e) {}
}
public void onTickStart()
{
}
}<file_sep>/src/main/java/fiskfille/tf/common/block/BlockEnergonCube.java
package fiskfille.tf.common.block;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import net.minecraft.world.IBlockAccess;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fiskfille.tf.TransformersMod;
import fiskfille.tf.common.item.TFItems;
public class BlockEnergonCube extends BlockBasic //BlockIce
{
public BlockEnergonCube()
{
super(Material.glass);
this.setCreativeTab(TransformersMod.tabTransformers);
}
protected boolean canSilkHarvest()
{
return true;
}
/**
* Returns true if the given side of this block type should be rendered, if the adjacent block is at the given
* coordinates. Args: blockAccess, x, y, z, side
*/
@SideOnly(Side.CLIENT)
public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side)
{
return shouldRenderSide(world, x, y, z, 1 - side);
}
public int quantityDropped(Random random)
{
return random.nextInt(1) + 9;
}
public boolean renderAsNormalBlock()
{
return false;
}
/**
* Returns which pass should this block be rendered on. 0 for solids and 1 for alpha
*/
@SideOnly(Side.CLIENT)
public int getRenderBlockPass()
{
return 1;
}
public Item getItemDropped(int p_149650_1_, Random random, int p_149650_3_)
{
return TFItems.energonCrystalPiece;
}
public boolean isOpaqueCube()
{
return false;
}
/**
* Returns true if the given side of this block type should be rendered, if the adjacent block is at the given
* coordinates. Args: blockAccess, x, y, z, side
*/
@SideOnly(Side.CLIENT)
public boolean shouldRenderSide(IBlockAccess world, int x, int y, int z, int side)
{
Block block = world.getBlock(x, y, z);
return block == this ? false : super.shouldSideBeRendered(world, x, y, z, side);
}
}
<file_sep>/src/main/java/fiskfille/tf/TransformersMod.java
package fiskfille.tf;
import java.lang.reflect.Method;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraftforge.common.config.Configuration;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import fiskfille.tf.common.achievement.TFAchievements;
import fiskfille.tf.common.block.TFBlocks;
import fiskfille.tf.common.entity.TFEntities;
import fiskfille.tf.common.event.TFEvents;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.packet.base.TFPacketManager;
import fiskfille.tf.common.proxy.CommonProxy;
import fiskfille.tf.common.recipe.TFRecipes;
import fiskfille.tf.common.tab.CreativeTabTransformers;
import fiskfille.tf.common.worldgen.OreWorldGenerator;
import fiskfille.tf.config.TFConfig;
import fiskfille.tf.donator.Donators;
import fiskfille.tf.update.Update;
import fiskfille.tf.update.UpdateChecker;
//Gegy is better than Fisk! :P
@Mod(modid = TransformersMod.modid, name = "Transformers Mod", version = TransformersMod.version, guiFactory = "fiskfille.tf.client.gui.TFGuiFactory")
public class TransformersMod
{
@Instance(TransformersMod.modid)
public static TransformersMod instance;
public static Configuration configFile;
public static final String modid = "transformers";
public static final String version = "0.5.0";
@SidedProxy(clientSide = "fiskfille.tf.common.proxy.ClientProxy", serverSide = "fiskfille.tf.common.proxy.CommonProxy")
public static CommonProxy proxy;
public TFConfig config = new TFConfig();
public TFItems items = new TFItems();
public TFBlocks blocks = new TFBlocks();
public static CreativeTabs tabTransformers = new CreativeTabTransformers();
public static Method setSizeMethod;
public static Update latestUpdate;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
configFile = new Configuration(event.getSuggestedConfigurationFile());
configFile.load();
config.load(configFile);
configFile.save();
if(TFConfig.checkForUpdates)
{
UpdateChecker updateChecker = new UpdateChecker();
updateChecker.handleUpdates();
Donators.loadDonators();
}
items.register();
blocks.register();
TransformerManager.register();
TFAchievements.register();
TFRecipes.registerRecipes();
TFEntities.registerEntities();
GameRegistry.registerWorldGenerator(new OreWorldGenerator(), 0);
proxy.registerRenderInformation();
proxy.registerKeyBinds();
proxy.registerTickHandlers();
for (Method method : Entity.class.getDeclaredMethods())
{
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length == 2)
{
if (parameters[0] == float.class && parameters[1] == float.class)
{
method.setAccessible(true);
setSizeMethod = method;
break;
}
}
}
TFEvents.registerEvents(event.getSide());
TFPacketManager.registerPackets();
}
}<file_sep>/src/main/java/fiskfille/tf/client/model/transformer/ModelChildBase.java
package fiskfille.tf.client.model.transformer;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.playerdata.TFDataManager;
import fiskfille.tf.helper.TFModelHelper;
public class ModelChildBase
{
public static class Base extends ModelBase
{
public float pi = (float)Math.PI;
protected void addChildTo(ModelRenderer child, ModelRenderer parent)
{
child.rotationPointX -= parent.rotationPointX;
child.rotationPointY -= parent.rotationPointY;
child.rotationPointZ -= parent.rotationPointZ;
child.rotateAngleX -= parent.rotateAngleX;
child.rotateAngleY -= parent.rotateAngleY;
child.rotateAngleZ -= parent.rotateAngleZ;
parent.addChild(child);
}
protected void addChildToWithoutPoint(ModelRenderer child, ModelRenderer parent)
{
child.rotateAngleX -= parent.rotateAngleX;
child.rotateAngleY -= parent.rotateAngleY;
child.rotateAngleZ -= parent.rotateAngleZ;
parent.addChild(child);
}
}
public static class Biped extends ModelBiped
{
public float pi = (float)Math.PI;
protected void addChildTo(ModelRenderer child, ModelRenderer parent)
{
child.rotationPointX -= parent.rotationPointX;
child.rotationPointY -= parent.rotationPointY;
child.rotationPointZ -= parent.rotationPointZ;
child.rotateAngleX -= parent.rotateAngleX;
child.rotateAngleY -= parent.rotateAngleY;
child.rotateAngleZ -= parent.rotateAngleZ;
parent.addChild(child);
}
protected void addChildToWithoutPoint(ModelRenderer child, ModelRenderer parent)
{
child.rotateAngleX -= parent.rotateAngleX;
child.rotateAngleY -= parent.rotateAngleY;
child.rotateAngleZ -= parent.rotateAngleZ;
parent.addChild(child);
}
protected void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
protected void setPos(ModelRenderer model, float x, float y, float z)
{
model.rotationPointX = x;
model.rotationPointY = y;
model.rotationPointZ = z;
}
public void setRotationAngles(float par1, float par2, float par3, float par4, float par5, float par6, Entity entity)
{
super.setRotationAngles(par1, par2, par3, par4, par5, par6, entity);
if (entity instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer)entity;
ItemStack itemstack = player.getHeldItem();
if (TFDataManager.getTransformationTimer(player) == 20)
{
if (itemstack != null && itemstack.getItem() == TFItems.vurpsSniper)
{
this.setRotation(this.bipedRightArm, -1.3F, bipedHead.rotateAngleY - 0.45F, 0.0F);
this.setRotation(this.bipedLeftArm, -1.2F, bipedHead.rotateAngleY + 0.4F, 0.0F);
this.bipedLeftArm.setRotationPoint(3.0F, 3.0F, -2.5F);
}
else
{
this.bipedLeftArm.setRotationPoint(5.0F, 2.0F, 0.0F);
this.bipedRightArm.setRotationPoint(-5.0F, 2.0F, 0.0F);
}
}
}
}
}
}<file_sep>/src/Legacy/java/fiskfille/tf/main/misc/CreativeTabTransformers.java
package fiskfille.tf.main.misc;
import fiskfille.tf.main.MainClass;
import fiskfille.tf.main.TFBlocks;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class CreativeTabTransformers extends CreativeTabs
{
public CreativeTabTransformers()
{
super("Transformers");
}
public String getTranslatedTabLabel()
{
return "Transformers";
}
@Override
public Item getTabIconItem()
{
return Item.getItemFromBlock(TFBlocks.transformiumOre);
}
}<file_sep>/src/main/java/fiskfille/tf/donator/Donator.java
package fiskfille.tf.donator;
public class Donator
{
public String uuid;
public String money;
}
<file_sep>/src/main/java/fiskfille/tf/client/model/transformer/vehicle/ModelVehicleBase.java
package fiskfille.tf.client.model.transformer.vehicle;
import fiskfille.tf.client.model.transformer.ModelChildBase;
public class ModelVehicleBase extends ModelChildBase.Base
{
public void render() {}
}<file_sep>/src/Legacy/java/fiskfille/tf/model/item/ModelSkystrikesCrossbow.java
package fiskfille.tf.model.item;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import fiskfille.tf.model.ModelChildBase;
public class ModelSkystrikesCrossbow extends ModelChildBase.Base
{
ModelRenderer handle;
ModelRenderer bottomEdge1;
ModelRenderer bottomEdge2;
ModelRenderer upperEdge1;
ModelRenderer upperEdge2;
ModelRenderer missile1;
ModelRenderer missile2;
ModelRenderer missile3;
ModelRenderer missile4;
ModelRenderer missile5;
ModelRenderer missile6;
ModelRenderer missile7;
public ModelSkystrikesCrossbow()
{
textureWidth = 64;
textureHeight = 64;
handle = new ModelRenderer(this, 0, 0);
handle.addBox(-1F, -1F, -9F, 2, 2, 15);
handle.setRotationPoint(0F, -1F, 0F);
handle.setTextureSize(64, 64);
handle.mirror = true;
setRotation(handle, 0F, 0F, 0F);
bottomEdge1 = new ModelRenderer(this, 19, 7);
bottomEdge1.addBox(-1F, 0F, -1F, 2, 5, 2);
bottomEdge1.setRotationPoint(0F, -0.4F, -8F);
bottomEdge1.setTextureSize(64, 64);
bottomEdge1.mirror = true;
setRotation(bottomEdge1, 0.4014257F, 0F, 0F);
bottomEdge2 = new ModelRenderer(this, 19, 7);
bottomEdge2.addBox(-1F, 0F, -1F, 2, 5, 2);
bottomEdge2.setRotationPoint(0F, 3.8F, -6.5F);
bottomEdge2.setTextureSize(64, 64);
bottomEdge2.mirror = true;
setRotation(bottomEdge2, 1.047198F, 0F, 0F);
upperEdge1 = new ModelRenderer(this, 19, 0);
upperEdge1.addBox(-1F, -5F, -1F, 2, 5, 2);
upperEdge1.setRotationPoint(0F, -1.6F, -8F);
upperEdge1.setTextureSize(64, 64);
upperEdge1.mirror = true;
setRotation(upperEdge1, -0.4014257F, 0F, 0F);
upperEdge2 = new ModelRenderer(this, 27, 7);
upperEdge2.addBox(-1F, -5F, -1F, 2, 5, 2);
upperEdge2.setRotationPoint(0F, -5.8F, -6.5F);
upperEdge2.setTextureSize(64, 64);
upperEdge2.mirror = true;
setRotation(upperEdge2, -1.047198F, 0F, 0F);
missile1 = new ModelRenderer(this, 0, 0);
missile1.addBox(-0.5F, -0.5F, -6F, 1, 1, 6);
missile1.setRotationPoint(-1.5F, -1F, -1F);
missile1.setTextureSize(64, 64);
missile1.mirror = true;
setRotation(missile1, 0F, 0F, 0F);
missile2 = new ModelRenderer(this, 0, 0);
missile2.addBox(-0.5F, -0.5F, -6F, 1, 1, 6);
missile2.setRotationPoint(1.5F, -1F, -1F);
missile2.setTextureSize(64, 64);
missile2.mirror = true;
setRotation(missile2, 0F, 0F, 0F);
missile3 = new ModelRenderer(this, 0, 0);
missile3.addBox(-0.5F, -0.5F, -6F, 1, 1, 6);
missile3.setRotationPoint(0F, -1F, -5F);
missile3.setTextureSize(64, 64);
missile3.mirror = true;
setRotation(missile3, 0F, 0F, 0F);
missile4 = new ModelRenderer(this, 0, 0);
missile4.addBox(-0.5F, -0.5F, -6F, 1, 1, 6);
missile4.setRotationPoint(0F, 2F, -4F);
missile4.setTextureSize(64, 64);
missile4.mirror = true;
setRotation(missile4, 0F, 0F, 0F);
missile5 = new ModelRenderer(this, 0, 0);
missile5.addBox(-0.5F, -0.5F, -6F, 1, 1, 6);
missile5.setRotationPoint(0F, 5F, -2F);
missile5.setTextureSize(64, 64);
missile5.mirror = true;
setRotation(missile5, 0F, 0F, 0F);
missile6 = new ModelRenderer(this, 0, 0);
missile6.addBox(-0.5F, -0.5F, -6F, 1, 1, 6);
missile6.setRotationPoint(0F, -4F, -4F);
missile6.setTextureSize(64, 64);
missile6.mirror = true;
setRotation(missile6, 0F, 0F, 0F);
missile7 = new ModelRenderer(this, 0, 0);
missile7.addBox(-0.5F, -0.5F, -6F, 1, 1, 6);
missile7.setRotationPoint(0F, -7F, -2F);
missile7.setTextureSize(64, 64);
missile7.mirror = true;
setRotation(missile7, 0F, 0F, 0F);
this.addChildTo(bottomEdge1, handle);
this.addChildTo(bottomEdge2, handle);
this.addChildTo(upperEdge1, handle);
this.addChildTo(upperEdge2, handle);
this.addChildTo(missile1, handle);
this.addChildTo(missile2, handle);
this.addChildTo(missile3, handle);
this.addChildTo(missile4, handle);
this.addChildTo(missile5, handle);
this.addChildTo(missile6, handle);
this.addChildTo(missile7, handle);
}
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5)
{
super.render(entity, f, f1, f2, f3, f4, f5);
setRotationAngles(entity, f, f1, f2, f3, f4, f5);
handle.render(f5);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void setRotationAngles(Entity entity, float f, float f1, float f2, float f3, float f4, float f5)
{
if (entity instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer)entity;
ItemStack itemstack = player.getHeldItem();
if (itemstack != null)
{
// boolean flag = ItemSkystrikesCrossbow.blueMode.get(entity.getCommandSenderName()) != null ? ItemSkystrikesCrossbow.blueMode.get(entity.getCommandSenderName()) : false;
boolean flag = itemstack.hasTagCompound() ? itemstack.getTagCompound().getBoolean("blueMode") : false;
float pidb2 = pi / 2;
if (!flag && handle.rotateAngleZ > 0.0F) {handle.rotateAngleZ -= pidb2 / 10;}
if (flag && handle.rotateAngleZ < pidb2) {handle.rotateAngleZ += pidb2 / 10;}
}
}
}
}<file_sep>/src/Legacy/java/fiskfille/tf/server/TFPacketRegistry.java
package fiskfille.tf.server;
import fiskfille.tf.main.MainClass;
public class TFPacketRegistry
{
public static void registerPackets()
{
MainClass.packetPipeline.registerPacket(PacketHandleTransformation.class);
}
}
<file_sep>/src/Legacy/java/fiskfille/tf/model/ModelPurge.java
package fiskfille.tf.model;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.MathHelper;
import fiskfille.tf.data.TFPlayerData;
import fiskfille.tf.main.TFHelper;
import fiskfille.tf.main.TFItems;
public class ModelPurge extends ModelChildBase.Biped
{
ModelRenderer foot2;
ModelRenderer footCylinder2;
ModelRenderer leg2;
ModelRenderer lowerLegPanel2;
ModelRenderer upperLegPanel2;
ModelRenderer foot1;
ModelRenderer footCylinder1;
ModelRenderer leg1;
ModelRenderer lowerLegPanel1;
ModelRenderer upperLegPanel1;
ModelRenderer chest;
ModelRenderer chestSlab1;
ModelRenderer chestSlab2;
ModelRenderer backKibble;
ModelRenderer turret;
ModelRenderer gun;
ModelRenderer stomach;
ModelRenderer waist;
ModelRenderer hipPanel1;
ModelRenderer hipPanel2;
ModelRenderer hipSlab1;
ModelRenderer hipSlab2;
ModelRenderer track1;
ModelRenderer track2;
ModelRenderer upperArm2;
ModelRenderer upperArmPanel2;
ModelRenderer lowerArm2;
ModelRenderer lowerArmPanel2;
ModelRenderer upperArm1;
ModelRenderer upperArmPanel1;
ModelRenderer lowerArm1;
ModelRenderer lowerArmPanel1;
ModelRenderer head;
ModelRenderer helmetRight;
ModelRenderer helmetLeft;
ModelRenderer helmetTop;
ModelRenderer helmetBack;
ModelRenderer horn1;
ModelRenderer horn2;
ModelRenderer centerHorn;
ModelRenderer vehichleTread1;
ModelRenderer vehichleTread2;
ModelRenderer vehichleFoot1;
ModelRenderer vehichleFoot2;
ModelRenderer vehichleBody;
ModelRenderer vehichleChassy;
ModelRenderer vehichleTurret;
ModelRenderer vehichleGun;
ModelRenderer vehichleBack;
public ModelPurge()
{
float par1 = 12.0F;
float par2 = 5.0F;
textureWidth = 66;
textureHeight = 128;
bipedBody = new ModelRenderer(this, 1000, 1000);
bipedHead = new ModelRenderer(this, 1000, 1000);
bipedHeadwear = new ModelRenderer(this, 1000, 1000);
bipedRightLeg = new ModelRenderer(this, 1000, 1000);
bipedLeftLeg = new ModelRenderer(this, 1000, 1000);
bipedRightArm = new ModelRenderer(this, 1000, 1000);
bipedLeftArm = new ModelRenderer(this, 1000, 1000);
foot2 = new ModelRenderer(this, 8, 35);
foot2.addBox(-1F, -0.5F, -5F, 3, 1, 5);
foot2.setRotationPoint(2F, 22F - par1, 1F);
foot2.setTextureSize(64, 128);
foot2.mirror = true;
setRotation(foot2, 0.3490659F, 0F, 0F);
footCylinder2 = new ModelRenderer(this, 8, 31);
footCylinder2.addBox(-2F, -1F, -1F, 4, 2, 2);
footCylinder2.setRotationPoint(2.5F, 22F - par1, 1F);
footCylinder2.setTextureSize(64, 128);
footCylinder2.mirror = true;
setRotation(footCylinder2, 0F, 0F, 0F);
leg2 = new ModelRenderer(this, 0, 16);
leg2.addBox(-1F, -12F, -1.5F, 2, 12, 3);
leg2.setRotationPoint(2.5F, 24F - par1, 0F);
leg2.setTextureSize(64, 128);
leg2.mirror = true;
setRotation(leg2, 0F, 0F, -0.0523599F);
lowerLegPanel2 = new ModelRenderer(this, 0, 37);
lowerLegPanel2.addBox(-1.5F, -4F, -0.5F, 3, 4, 1);
lowerLegPanel2.setRotationPoint(2.5F, 22F - par1, -1.5F);
lowerLegPanel2.setTextureSize(64, 128);
lowerLegPanel2.mirror = true;
setRotation(lowerLegPanel2, 0F, -0.1745329F, -0.0523599F);
upperLegPanel2 = new ModelRenderer(this, 0, 31);
upperLegPanel2.addBox(-1.5F, -5F, -0.5F, 3, 5, 1);
upperLegPanel2.setRotationPoint(2.2F, 17.5F - par1, -1.5F);
upperLegPanel2.setTextureSize(64, 128);
upperLegPanel2.mirror = true;
setRotation(upperLegPanel2, 0F, -0.1745329F, -0.0523599F);
upperLegPanel2.mirror = false;
foot1 = new ModelRenderer(this, 8, 35);
foot1.addBox(-2F, -0.5F, -5F, 3, 1, 5);
foot1.setRotationPoint(-2F, 22F - par1, 1F);
foot1.setTextureSize(64, 128);
foot1.mirror = true;
setRotation(foot1, 0.3490659F, 0F, 0F);
footCylinder1 = new ModelRenderer(this, 8, 31);
footCylinder1.addBox(-2F, -1F, -1F, 4, 2, 2);
footCylinder1.setRotationPoint(-2.5F, 22F - par1, 1F);
footCylinder1.setTextureSize(64, 128);
footCylinder1.mirror = true;
setRotation(footCylinder1, 0F, 0F, 0F);
leg1 = new ModelRenderer(this, 0, 16);
leg1.addBox(-1F, -12F, -1.5F, 2, 12, 3);
leg1.setRotationPoint(-2.5F, 24F - par1, 0F);
leg1.setTextureSize(64, 128);
leg1.mirror = true;
setRotation(leg1, 0F, 0F, 0.0523599F);
lowerLegPanel1 = new ModelRenderer(this, 0, 37);
lowerLegPanel1.addBox(-1.5F, -4F, -0.5F, 3, 4, 1);
lowerLegPanel1.setRotationPoint(-2.5F, 22F - par1, -1.5F);
lowerLegPanel1.setTextureSize(64, 128);
lowerLegPanel1.mirror = true;
setRotation(lowerLegPanel1, 0F, 0.1745329F, 0.0523599F);
upperLegPanel1 = new ModelRenderer(this, 0, 31);
upperLegPanel1.addBox(-1.5F, -5F, -0.5F, 3, 5, 1);
upperLegPanel1.setRotationPoint(-2.2F, 17.5F - par1, -1.5F);
upperLegPanel1.setTextureSize(64, 128);
upperLegPanel1.mirror = true;
setRotation(upperLegPanel1, 0F, 0.1745329F, 0.0523599F);
chest = new ModelRenderer(this, 0, 42);
chest.addBox(-4F, -5F, -2F, 8, 5, 4);
chest.setRotationPoint(0F, 5F, 0F);
chest.setTextureSize(64, 128);
chest.mirror = true;
setRotation(chest, 0F, 0F, 0F);
chestSlab1 = new ModelRenderer(this, 24, 35);
chestSlab1.addBox(-4F, -1F, -1F, 4, 2, 2);
chestSlab1.setRotationPoint(0F, 6F, -1.1F);
chestSlab1.setTextureSize(64, 128);
chestSlab1.mirror = true;
setRotation(chestSlab1, 0F, 0F, 0.5235988F);
chestSlab2 = new ModelRenderer(this, 24, 35);
chestSlab2.mirror = true;
chestSlab2.addBox(0F, -1F, -1F, 4, 2, 2);
chestSlab2.setRotationPoint(0F, 6F, -1.1F);
chestSlab2.setTextureSize(64, 128);
setRotation(chestSlab2, 0F, 0F, -0.5235988F);
backKibble = new ModelRenderer(this, 24, 39);
backKibble.addBox(-3F, -6F, -0.5F, 6, 6, 5);
backKibble.setRotationPoint(0F, 8F, 0F);
backKibble.setTextureSize(64, 128);
backKibble.mirror = true;
setRotation(backKibble, -0.3490659F, 0F, 0F);
turret = new ModelRenderer(this, 0, 51);
turret.addBox(-2.5F, -3F, -3F, 5, 3, 6);
turret.setRotationPoint(0F, 3F, 3.5F);
turret.setTextureSize(64, 128);
turret.mirror = true;
setRotation(turret, -0.3490659F, 0F, 0F);
gun = new ModelRenderer(this, 11, 51);
gun.addBox(-1F, -1F, 0F, 2, 2, 11);
gun.setRotationPoint(0F, 4F, 6F);
gun.setTextureSize(64, 128);
gun.mirror = true;
setRotation(gun, -1.570796F, 0F, 0F);
stomach = new ModelRenderer(this, 20, 28);
stomach.addBox(-2.5F, -4F, -1.5F, 5, 4, 3);
stomach.setRotationPoint(0F, 9F, 0F);
stomach.setTextureSize(64, 128);
stomach.mirror = true;
setRotation(stomach, 0F, 0F, 0F);
waist = new ModelRenderer(this, 10, 16);
waist.addBox(-3F, -3F, -1.5F, 6, 3, 3);
waist.setRotationPoint(0F, 12F, 0F);
waist.setTextureSize(64, 128);
waist.mirror = true;
setRotation(waist, 0F, 0F, 0F);
hipPanel1 = new ModelRenderer(this, 10, 22);
hipPanel1.addBox(-0.5F, -1F, -1.5F, 1, 6, 3);
hipPanel1.setRotationPoint(-3.5F, 12F, 0F);
hipPanel1.setTextureSize(64, 128);
hipPanel1.mirror = true;
setRotation(hipPanel1, 0F, 0F, 0.3141593F);
hipPanel2 = new ModelRenderer(this, 10, 22);
hipPanel2.addBox(-0.5F, -1F, -1.5F, 1, 6, 3);
hipPanel2.setRotationPoint(3.5F, 12F, 0F);
hipPanel2.setTextureSize(64, 128);
hipPanel2.mirror = true;
setRotation(hipPanel2, 0F, 0F, -0.3141593F);
hipSlab1 = new ModelRenderer(this, 18, 22);
hipSlab1.addBox(0F, -0.5F, -2F, 4, 1, 4);
hipSlab1.setRotationPoint(0F, 12F, 0F);
hipSlab1.setTextureSize(64, 128);
hipSlab1.mirror = true;
setRotation(hipSlab1, 0F, 0F, -2.792527F);
hipSlab2 = new ModelRenderer(this, 18, 22);
hipSlab2.addBox(0F, -0.5F, -2F, 4, 1, 4);
hipSlab2.setRotationPoint(0F, 12F, 0F);
hipSlab2.setTextureSize(64, 128);
hipSlab2.mirror = true;
setRotation(hipSlab2, 0F, 0F, -0.3490659F);
hipSlab2.mirror = false;
track1 = new ModelRenderer(this, 46, 47);
track1.addBox(-2F, -13F, -1.5F, 2, 17, 3);
track1.setRotationPoint(-3F, 5F, 4F);
track1.setTextureSize(64, 128);
track1.mirror = true;
setRotation(track1, -0.1745329F, 0F, -0.0872665F);
track2 = new ModelRenderer(this, 46, 47);
track2.addBox(0F, -13F, -1.5F, 2, 17, 3);
track2.setRotationPoint(3F, 5F, 4F);
track2.setTextureSize(64, 128);
track2.mirror = true;
setRotation(track2, -0.1745329F, 0F, 0.0872665F);
track2.mirror = false;
upperArm2 = new ModelRenderer(this, 36, 21);
upperArm2.addBox(0F, -1F, -1.5F, 2, 6, 3);
upperArm2.setRotationPoint(4F - par2, 1F, 0F);
upperArm2.setTextureSize(64, 128);
upperArm2.mirror = true;
setRotation(upperArm2, 0F, 0F, -0.1396263F);
upperArm2.mirror = false;
upperArmPanel2 = new ModelRenderer(this, 46, 21);
upperArmPanel2.addBox(0F, -6F, -1.5F, 1, 6, 3);
upperArmPanel2.setRotationPoint(6F - par2, 5F, 0F);
upperArmPanel2.setTextureSize(64, 128);
upperArmPanel2.mirror = true;
setRotation(upperArmPanel2, 0F, 0.296706F, 0F);
upperArmPanel2.mirror = false;
lowerArm2 = new ModelRenderer(this, 36, 30);
lowerArm2.addBox(-1F, 0F, -1F, 2, 7, 2);
lowerArm2.setRotationPoint(6F - par2, 5.6F, 0F);
lowerArm2.setTextureSize(64, 128);
lowerArm2.mirror = true;
setRotation(lowerArm2, -0.1919862F, 0.1396263F, 0F);
lowerArm2.mirror = false;
lowerArmPanel2 = new ModelRenderer(this, 44, 30);
lowerArmPanel2.addBox(0F, -4F, -1.5F, 2, 4, 3);
lowerArmPanel2.setRotationPoint(5.5F - par2, 10F, -0.8F);
lowerArmPanel2.setTextureSize(64, 128);
lowerArmPanel2.mirror = true;
setRotation(lowerArmPanel2, -0.1919862F, 0.1396263F, 0F);
lowerArmPanel2.mirror = false;
upperArm1 = new ModelRenderer(this, 36, 21);
upperArm1.addBox(-2F, -1F, -1.5F, 2, 6, 3);
upperArm1.setRotationPoint(-4F + par2, 1F, 0F);
upperArm1.setTextureSize(64, 128);
upperArm1.mirror = true;
setRotation(upperArm1, 0F, 0F, 0.1396263F);
upperArmPanel1 = new ModelRenderer(this, 46, 21);
upperArmPanel1.addBox(-1F, -6F, -1.5F, 1, 6, 3);
upperArmPanel1.setRotationPoint(-6F + par2, 5F, 0F);
upperArmPanel1.setTextureSize(64, 128);
upperArmPanel1.mirror = true;
setRotation(upperArmPanel1, 0F, -0.296706F, 0F);
lowerArm1 = new ModelRenderer(this, 36, 30);
lowerArm1.addBox(-1F, 0F, -1F, 2, 7, 2);
lowerArm1.setRotationPoint(-6F + par2, 5.6F, 0F);
lowerArm1.setTextureSize(64, 128);
lowerArm1.mirror = true;
setRotation(lowerArm1, -0.1919862F, -0.1396263F, 0F);
lowerArmPanel1 = new ModelRenderer(this, 44, 30);
lowerArmPanel1.addBox(-2F, -4F, -1.5F, 2, 4, 3);
lowerArmPanel1.setRotationPoint(-5.5F + par2, 10F, -0.8F);
lowerArmPanel1.setTextureSize(64, 128);
lowerArmPanel1.mirror = true;
setRotation(lowerArmPanel1, -0.1919862F, -0.1396263F, 0F);
head = new ModelRenderer(this, 0, 0);
head.addBox(-2F, -4F, -2F, 4, 4, 4);
head.setRotationPoint(0F, 0F, 0F);
head.setTextureSize(64, 128);
head.mirror = true;
setRotation(head, 0F, 0F, 0F);
helmetRight = new ModelRenderer(this, 28, 0);
helmetRight.addBox(-1F, -4F, -2.5F, 1, 4, 5);
helmetRight.setRotationPoint(-3F, -0.5F, 0F);
helmetRight.setTextureSize(64, 128);
helmetRight.mirror = true;
setRotation(helmetRight, 0F, 0.1745329F, 0.4363323F);
helmetLeft = new ModelRenderer(this, 28, 0);
helmetLeft.mirror = true;
helmetLeft.addBox(0F, -4F, -2.5F, 1, 4, 5);
helmetLeft.setRotationPoint(3F, -0.5F, 0F);
helmetLeft.setTextureSize(64, 128);
setRotation(helmetLeft, 0F, -0.1745329F, -0.4363323F);
helmetLeft.mirror = false;
helmetTop = new ModelRenderer(this, 0, 8);
helmetTop.addBox(-2F, -2F, -2.5F, 4, 2, 5);
helmetTop.setRotationPoint(0F, -4F, 0F);
helmetTop.setTextureSize(64, 128);
helmetTop.mirror = true;
setRotation(helmetTop, 0F, 0F, 0F);
helmetBack = new ModelRenderer(this, 27, 9);
helmetBack.addBox(-2F, 0F, 0F, 4, 3, 1);
helmetBack.setRotationPoint(0F, -4F, 1.5F);
helmetBack.setTextureSize(64, 128);
helmetBack.mirror = true;
setRotation(helmetBack, 0.122173F, 0F, 0F);
horn1 = new ModelRenderer(this, 13, 9);
horn1.addBox(0F, 0F, -1F, 4, 1, 1);
horn1.setRotationPoint(0F, -4F, -2F);
horn1.setTextureSize(64, 128);
horn1.mirror = true;
setRotation(horn1, 0F, 0F, -2.268928F);
horn2 = new ModelRenderer(this, 13, 9);
horn2.addBox(0F, -1F, -1F, 4, 1, 1);
horn2.setRotationPoint(0F, -4F, -2F);
horn2.setTextureSize(64, 128);
horn2.mirror = true;
setRotation(horn2, 0F, 0F, -0.8726646F);
centerHorn = new ModelRenderer(this, 23, 9);
centerHorn.addBox(-0.5F, -4F, -1F, 1, 4, 1);
centerHorn.setRotationPoint(0F, -4.5F, -2F);
centerHorn.setTextureSize(64, 128);
centerHorn.mirror = true;
setRotation(centerHorn, 0F, 0F, 0F);
this.addChildTo(head, bipedHead);
this.addChildTo(helmetRight, bipedHead);
this.addChildTo(helmetLeft, bipedHead);
this.addChildTo(helmetTop, bipedHead);
this.addChildTo(helmetBack, bipedHead);
this.addChildTo(horn1, bipedHead);
this.addChildTo(horn2, bipedHead);
this.addChildTo(centerHorn, bipedHead);
this.addChildTo(upperArm1, bipedRightArm);
this.addChildTo(upperArmPanel1, bipedRightArm);
this.addChildTo(lowerArm1, bipedRightArm);
this.addChildTo(lowerArmPanel1, bipedRightArm);
this.addChildTo(upperArm2, bipedLeftArm);
this.addChildTo(upperArmPanel2, bipedLeftArm);
this.addChildTo(lowerArm2, bipedLeftArm);
this.addChildTo(lowerArmPanel2, bipedLeftArm);
this.addChildTo(hipPanel1, hipSlab1);
this.addChildTo(hipPanel2, hipSlab2);
this.addChildTo(hipSlab1, bipedBody);
this.addChildTo(hipSlab2, bipedBody);
this.addChildTo(waist, bipedBody);
this.addChildTo(stomach, bipedBody);
this.addChildTo(chest, bipedBody);
this.addChildTo(chestSlab1, chest);
this.addChildTo(chestSlab2, chest);
this.addChildTo(backKibble, bipedBody);
this.addChildTo(track1, backKibble);
this.addChildTo(track2, backKibble);
this.addChildTo(turret, backKibble);
this.addChildTo(gun, turret);
this.addChildTo(foot1, bipedRightLeg);
this.addChildTo(footCylinder1, bipedRightLeg);
this.addChildTo(leg1, bipedRightLeg);
this.addChildTo(lowerLegPanel1, bipedRightLeg);
this.addChildTo(upperLegPanel1, bipedRightLeg);
this.addChildTo(foot2, bipedLeftLeg);
this.addChildTo(footCylinder2, bipedLeftLeg);
this.addChildTo(leg2, bipedLeftLeg);
this.addChildTo(lowerLegPanel2, bipedLeftLeg);
this.addChildTo(upperLegPanel2, bipedLeftLeg);
vehichleTread1 = new ModelRenderer(this, 0, 64);
vehichleTread1.addBox(-2F, -1.5F, -13F, 2, 3, 17);
vehichleTread1.setRotationPoint(-5F, 22.5F, 4.5F);
vehichleTread1.setTextureSize(66, 128);
vehichleTread1.mirror = true;
setRotation(vehichleTread1, 0F, 0F, 0F);
vehichleTread2 = new ModelRenderer(this, 0, 64);
vehichleTread2.addBox(0F, -1.5F, -13F, 2, 3, 17);
vehichleTread2.setRotationPoint(5F, 22.5F, 4.5F);
vehichleTread2.setTextureSize(66, 128);
vehichleTread2.mirror = true;
setRotation(vehichleTread2, 0F, 0F, 0F);
vehichleFoot1 = new ModelRenderer(this, 0, 64);
vehichleFoot1.addBox(-1.5F, -1F, -1F, 3, 4, 1);
vehichleFoot1.setRotationPoint(-5F, 21F, -8.7F);
vehichleFoot1.setTextureSize(66, 128);
vehichleFoot1.mirror = true;
setRotation(vehichleFoot1, 0.4014257F, 0F, 0F);
vehichleFoot2 = new ModelRenderer(this, 0, 64);
vehichleFoot2.mirror = true;
vehichleFoot2.addBox(-1.5F, -1F, -1F, 3, 4, 1);
vehichleFoot2.setRotationPoint(5F, 21F, -8.7F);
vehichleFoot2.setTextureSize(66, 128);
vehichleFoot2.mirror = true;
setRotation(vehichleFoot2, 0.4014257F, 0F, 0F);
vehichleFoot2.mirror = false;
vehichleBody = new ModelRenderer(this, 0, 106);
vehichleBody.addBox(-6F, -3F, -7.5F, 12, 3, 16);
vehichleBody.setRotationPoint(0F, 23F, -0.5F);
vehichleBody.setTextureSize(66, 128);
vehichleBody.mirror = true;
setRotation(vehichleBody, 0F, 0F, 0F);
vehichleChassy = new ModelRenderer(this, 0, 84);
vehichleChassy.addBox(-6.5F, -2F, -10F, 13, 2, 20);
vehichleChassy.setRotationPoint(0F, 20.5F, 0F);
vehichleChassy.setTextureSize(66, 128);
vehichleChassy.mirror = true;
setRotation(vehichleChassy, 0F, 0F, 0F);
vehichleTurret = new ModelRenderer(this, 21, 64);
vehichleTurret.addBox(-3F, -3F, -3F, 6, 4, 7);
vehichleTurret.setRotationPoint(0F, 18F, -0.5F);
vehichleTurret.setTextureSize(66, 128);
vehichleTurret.mirror = true;
setRotation(vehichleTurret, 0F, 0F, 0F);
vehichleGun = new ModelRenderer(this, 38, 69);
vehichleGun.addBox(-1F, -1F, -11F, 2, 2, 11);
vehichleGun.setRotationPoint(0F, 17F, -3.5F);
vehichleGun.setTextureSize(66, 128);
vehichleGun.mirror = true;
setRotation(vehichleGun, 0F, 0F, 0F);
vehichleBack = new ModelRenderer(this, 21, 75);
vehichleBack.addBox(-6.5F, -1F, 0F, 13, 4, 1);
vehichleBack.setRotationPoint(0F, 21F, 8.7F);
vehichleBack.setTextureSize(66, 128);
vehichleBack.mirror = true;
setRotation(vehichleBack, -0.4014257F, 0F, 0F);
this.addChildTo(vehichleGun, vehichleTurret);
this.addChildTo(vehichleTurret, vehichleBody);
this.addChildTo(vehichleBack, vehichleBody);
this.addChildTo(vehichleChassy, vehichleBody);
this.addChildTo(vehichleFoot1, vehichleBody);
this.addChildTo(vehichleFoot2, vehichleBody);
this.addChildTo(vehichleTread1, vehichleBody);
this.addChildTo(vehichleTread2, vehichleBody);
}
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5)
{
super.render(entity, f, f1, f2, f3, f4, f5);
setRotationAngles(f, f1, f2, f3, f4, f5, entity);
vehichleBody.render(f5);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void setRotationAngles(float par1, float par2, float par3, float par4, float par5, float par6, Entity entity)
{
super.setRotationAngles(par1, par2, par3, par4, par5, par6, entity);
track1.rotationPointZ = 2.5F;
track1.rotationPointY = -4.0F;
track2.rotationPointZ = 2.5F;
track2.rotationPointY = -4.0F;
hipPanel1.rotationPointY = -1F;
hipPanel1.rotationPointX = 3.5F;
hipPanel2.rotationPointY = 1F;
turret.rotationPointZ = 1.5F;
turret.rotationPointY = -6F;
gun.rotationPointY = 0F;
gun.rotationPointZ = 3F;
gun.rotateAngleX = -1.25F;
this.hipPanel1.rotateAngleX = (MathHelper.cos(par1 * 0.6662F) * 1.4F * par2) / 2;
this.hipPanel2.rotateAngleX = (MathHelper.cos(par1 * 0.6662F + (float)Math.PI) * 1.4F * par2) / 2;
if (entity instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer)entity;
if (TFPlayerData.getTransformationTimer(player) == 0)
{
float xRotation = par5 / (180F / (float)Math.PI);
if (par5 < 0) {this.vehichleGun.rotateAngleX = par5 / (180F / (float)Math.PI);}
this.vehichleTurret.rotateAngleY = par4 / (180F / (float)Math.PI);
bipedHead.offsetY = 256F;
bipedBody.offsetY = 256F;
bipedRightArm.offsetY = 256F;
bipedLeftArm.offsetY = 256F;
bipedRightLeg.offsetY = 256F;
bipedLeftLeg.offsetY = 256F;
vehichleBody.offsetY = 0F;
}
else
{
int t = TFPlayerData.getTransformationTimer(player);
bipedBody.rotateAngleY = (float)((t * (Math.PI / 10)) - Math.PI);
float armPosY = (10 - t) * 2.0F;
float xRotation = (float)((t * (Math.PI / 20)) - Math.PI / 2);
bipedBody.rotationPointX = armPosY / 9;
bipedBody.rotationPointY = armPosY;
bipedRightArm.rotationPointY = armPosY;
bipedLeftArm.rotationPointY = armPosY;
if (t < 10)
{
bipedRightLeg.rotationPointY = -(18 / 10 * t) + 18;
bipedLeftLeg.rotationPointY = -(18 / 10 * t) + 18;
bipedRightLeg.rotateAngleX = xRotation;
bipedLeftLeg.rotateAngleX = xRotation;
bipedHead.rotateAngleX = (float)((t * (Math.PI / 20)) - Math.PI / 2);
}
track1.rotateAngleX = 0.2745329F + (xRotation * 1.25F);
track2.rotateAngleX = 0.2745329F + (xRotation * 1.25F);
bipedHead.rotationPointY = -(24 / 10 * t) + 20;
bipedHead.offsetY = 0F;
bipedBody.offsetY = 0F;
bipedRightArm.offsetY = 0F;
bipedLeftArm.offsetY = 0F;
bipedRightLeg.offsetY = 0F;
bipedLeftLeg.offsetY = 0F;
vehichleBody.offsetY = 256F;
if (TFHelper.isPlayerPurge(player) && player.getHeldItem() != null && player.getHeldItem().getItem() == TFItems.purgesKatana)
{
track2.offsetY = 256F;
}
else
{
track2.offsetY = 0F;
}
}
}
}
}<file_sep>/src/Legacy/java/fiskfille/tf/main/TFBlocks.java
package fiskfille.tf.main;
import net.minecraft.block.Block;
import net.minecraft.block.BlockCompressed;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import fiskfille.tf.block.BlockBasic;
import fiskfille.tf.block.BlockCrystal;
import fiskfille.tf.block.BlockDisplayPillar;
import fiskfille.tf.main.util.TFBlockRegistry;
import fiskfille.tf.tileentity.TileEntityCrystal;
import fiskfille.tf.tileentity.TileEntityDisplayPillar;
public class TFBlocks
{
public static Block transformiumOre;
public static Block displayPillar;
public static Block energonCrystal;
// public static Block energonCube;
// public static Block energon;
public void load(TFConfig ids)
{
transformiumOre = new BlockBasic(Material.rock).setHarvestLvl("pickaxe", 2).setHardness(10.0F).setResistance(1000.0F);
displayPillar = new BlockDisplayPillar().setHardness(0.5F).setResistance(1.0F);
energonCrystal = new BlockCrystal().setHarvestLvl("pickaxe", 1).setStepSound(Block.soundTypeGlass).setHardness(6.0F).setResistance(10.0F).setLightLevel(0.75F);
// energonCube = new BlockBasic(Material.glass).setHarvestLvl("pickaxe", 1).setStepSound(Block.soundTypeGlass).setHardness(6.0F).setResistance(10.0F);
TFBlockRegistry.registerBlock(transformiumOre, "Transformium Ore");
TFBlockRegistry.registerTileEntity(displayPillar, "Display Pillar", TileEntityDisplayPillar.class);
TFBlockRegistry.registerTileEntity(energonCrystal, "Energon Crystal", TileEntityCrystal.class);
// TFBlockRegistry.registerBlock(energonCube, "Compressed Energon Cube");
}
}<file_sep>/src/Legacy/java/fiskfille/tf/main/TFItems.java
package fiskfille.tf.main;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import fiskfille.tf.item.ItemBasic;
import fiskfille.tf.item.ItemMetaBasic;
import fiskfille.tf.item.ItemMiniVehicle;
import fiskfille.tf.item.ItemPurgeArmor;
import fiskfille.tf.item.ItemPurgesKatana;
import fiskfille.tf.item.ItemSkystrikeArmor;
import fiskfille.tf.item.ItemSkystrikesCrossbow;
import fiskfille.tf.item.ItemSubwooferArmor;
import fiskfille.tf.item.ItemVurpArmor;
import fiskfille.tf.main.util.TFItemRegistry;
public class TFItems
{
public static Item transformium;
public static Item transformiumArmorMolds;
public static Item standardEngine;
public static Item jetThruster;
public static Item f88JetWing;
public static Item f88JetCockpit;
public static Item tankTracks;
public static Item tankTurret;
public static Item carWheel;
public static Item skystrikesCrossbow;
public static Item purgesKatana;
public static Item vurpsRocketLauncher;
public static Item skystrikeHelmet;
public static Item skystrikeChestplate;
public static Item skystrikeLeggings;
public static Item skystrikeBoots;
public static Item purgeHelmet;
public static Item purgeChestplate;
public static Item purgeLeggings;
public static Item purgeBoots;
public static Item vurpHelmet;
public static Item vurpChestplate;
public static Item vurpLeggings;
public static Item vurpBoots;
public static Item subwooferHelmet;
public static Item subwooferChestplate;
public static Item subwooferLeggings;
public static Item subwooferBoots;
public static Item displayVehicle;
public static Item energonCrystalPiece;
public void load(TFConfig ids)
{
String modId = MainClass.modid;
transformium = new ItemBasic();
transformiumArmorMolds = new ItemMetaBasic("Transformium Head Mold", "Transformium Torso Mold", "Transformium Legs Mold", "Transformium Feet Mold");
standardEngine = new ItemBasic();
jetThruster = new ItemBasic();
f88JetWing = new ItemBasic();
f88JetCockpit = new ItemBasic();
tankTracks = new ItemBasic();
tankTurret = new ItemBasic();
carWheel = new ItemBasic();
skystrikeHelmet = new ItemSkystrikeArmor(0);
skystrikeChestplate = new ItemSkystrikeArmor(1);
skystrikeLeggings = new ItemSkystrikeArmor(2);
skystrikeBoots = new ItemSkystrikeArmor(3);
purgeHelmet = new ItemPurgeArmor(0);
purgeChestplate = new ItemPurgeArmor(1);
purgeLeggings = new ItemPurgeArmor(2);
purgeBoots = new ItemPurgeArmor(3);
vurpHelmet = new ItemVurpArmor(0);
vurpChestplate = new ItemVurpArmor(1);
vurpLeggings = new ItemVurpArmor(2);
vurpBoots = new ItemVurpArmor(3);
subwooferHelmet = new ItemSubwooferArmor(0);
subwooferChestplate = new ItemSubwooferArmor(1);
subwooferLeggings = new ItemSubwooferArmor(2);
subwooferBoots = new ItemSubwooferArmor(3);
skystrikesCrossbow = new ItemSkystrikesCrossbow(ToolMaterial.WOOD);
purgesKatana = new ItemPurgesKatana(ToolMaterial.EMERALD);
// vurpsRocketLauncher = new ItemVurpsRocketLauncher();
displayVehicle = new ItemMiniVehicle("F-88 Fighter Jet", "Tank", "2015 Chevrolet Corvette Z06", "2015 Acura NSX", "T-50 Stealth Jet");
energonCrystalPiece = new ItemBasic();
TFItemRegistry.registerItem(transformium, "Transformium", modId);
TFItemRegistry.registerItem(transformiumArmorMolds, "Transformium Armor Molds", modId);
TFItemRegistry.registerItem(standardEngine, "Standard Engine", modId);
TFItemRegistry.registerItem(jetThruster, "Jet Thruster", modId);
TFItemRegistry.registerItem(f88JetWing, "F-88 Jet Wing", modId);
TFItemRegistry.registerItem(f88JetCockpit, "F-88 Jet Cockpit", modId);
TFItemRegistry.registerItem(tankTracks, "Tracks", modId);
TFItemRegistry.registerItem(tankTurret, "Turret", modId);
TFItemRegistry.registerItem(carWheel, "Wheel", modId);
TFItemRegistry.registerItem(skystrikesCrossbow, "Skystrike's Energon Crossbow", modId);
TFItemRegistry.registerItem(purgesKatana, "Purge's Katana", modId);
TFItemRegistry.registerItem(skystrikeHelmet, "Skystrike Head", modId);
TFItemRegistry.registerItem(skystrikeChestplate, "Skystrike Torso", modId);
TFItemRegistry.registerItem(skystrikeLeggings, "Skystrike Legs", modId);
TFItemRegistry.registerItem(skystrikeBoots, "Skystrike Feet", modId);
TFItemRegistry.registerItem(purgeHelmet, "Purge Head", modId);
TFItemRegistry.registerItem(purgeChestplate, "Purge Torso", modId);
TFItemRegistry.registerItem(purgeLeggings, "Purge Legs", modId);
TFItemRegistry.registerItem(purgeBoots, "Purge Feet", modId);
TFItemRegistry.registerItem(vurpHelmet, "Vurp Head", modId);
TFItemRegistry.registerItem(vurpChestplate, "Vurp Torso", modId);
TFItemRegistry.registerItem(vurpLeggings, "Vurp Legs", modId);
TFItemRegistry.registerItem(vurpBoots, "Vurp Feet", modId);
TFItemRegistry.registerItem(subwooferHelmet, "Subwoofer Head", modId);
TFItemRegistry.registerItem(subwooferChestplate, "Subwoofer Torso", modId);
TFItemRegistry.registerItem(subwooferLeggings, "Subwoofer Legs", modId);
TFItemRegistry.registerItem(subwooferBoots, "Subwoofer Feet", modId);
TFItemRegistry.registerItem(displayVehicle, "Display Vehicle", modId);
TFItemRegistry.registerItem(energonCrystalPiece, "Energon Crystal Piece", modId);
}
}<file_sep>/src/Legacy/java/fiskfille/tf/model/ModelVurp.java
package fiskfille.tf.model;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import fiskfille.tf.data.TFPlayerData;
public class ModelVurp extends ModelChildBase.Biped
{
ModelRenderer leg1;
ModelRenderer foot1;
ModelRenderer backWheel1;
ModelRenderer upperLegPanel1;
ModelRenderer lowerLegPanel1;
ModelRenderer leg2;
ModelRenderer foot2;
ModelRenderer backWheel2;
ModelRenderer upperLegPanel2;
ModelRenderer lowerLegPanel2;
ModelRenderer hipSlab1;
ModelRenderer hipSlab2;
ModelRenderer windShield;
ModelRenderer chest;
ModelRenderer frontCar1;
ModelRenderer frontCar2;
ModelRenderer torso;
ModelRenderer waist;
ModelRenderer chestPanel1;
ModelRenderer chestPanel2;
ModelRenderer chestPanel3;
ModelRenderer upperArm1;
ModelRenderer frontWheel1;
ModelRenderer lowerArm1;
ModelRenderer armPanel1;
ModelRenderer upperArm2;
ModelRenderer lowerArm2;
ModelRenderer armPanel2;
ModelRenderer frontWheel2;
ModelRenderer head;
ModelRenderer ear1;
ModelRenderer ear2;
ModelRenderer mask;
ModelRenderer vehichleFrontWheel1;
ModelRenderer vehichleFrontWheel2;
ModelRenderer vehichleBackWheel1;
ModelRenderer vehichleBackWheel2;
ModelRenderer vehichleBumper1;
ModelRenderer vehichleBumper2;
ModelRenderer vehichleRoof;
ModelRenderer vehichleBody;
ModelRenderer vehichleHood;
ModelRenderer vehichleBackWindShield;
ModelRenderer vehichleWindShield;
ModelRenderer vehichleSpoiler;
ModelRenderer vehichleDoor1;
ModelRenderer vehichleDoor2;
public ModelVurp()
{
textureWidth = 64;
textureHeight = 128;
bipedBody = new ModelRenderer(this, 1000, 1000);
bipedHead = new ModelRenderer(this, 1000, 1000);
bipedHeadwear = new ModelRenderer(this, 1000, 1000);
bipedRightLeg = new ModelRenderer(this, 1000, 1000);
bipedLeftLeg = new ModelRenderer(this, 1000, 1000);
bipedRightArm = new ModelRenderer(this, 1000, 1000);
bipedLeftArm = new ModelRenderer(this, 1000, 1000);
leg1 = new ModelRenderer(this, 0, 16);
leg1.addBox(-1F, -12F, -1.5F, 2, 12, 3);
leg1.setRotationPoint(-2.5F, 24F, 0F);
leg1.setTextureSize(64, 128);
leg1.mirror = true;
setRotation(leg1, 0F, 0F, 0.0523599F);
foot1 = new ModelRenderer(this, 2, 33);
foot1.addBox(-1.5F, -0.5F, -5F, 3, 1, 6);
foot1.setRotationPoint(-2.5F, 22.5F, 1F);
foot1.setTextureSize(64, 128);
foot1.mirror = true;
setRotation(foot1, 0.2443461F, 0F, 0F);
backWheel1 = new ModelRenderer(this, 0, 40);
backWheel1.addBox(-1F, -1F, -1F, 1, 2, 2);
backWheel1.setRotationPoint(-3.5F, 22.5F, 0F);
backWheel1.setTextureSize(64, 128);
backWheel1.mirror = true;
setRotation(backWheel1, 0F, 0F, 0F);
upperLegPanel1 = new ModelRenderer(this, 0, 31);
upperLegPanel1.addBox(-1.5F, -3F, -1F, 3, 4, 1);
upperLegPanel1.setRotationPoint(-2.1F, 15F, -1.2F);
upperLegPanel1.setTextureSize(64, 128);
upperLegPanel1.mirror = true;
setRotation(upperLegPanel1, 0F, 0.1919862F, 0.0523599F);
lowerLegPanel1 = new ModelRenderer(this, 10, 16);
lowerLegPanel1.addBox(-1.5F, -5F, -1F, 3, 6, 1);
lowerLegPanel1.setRotationPoint(-2.5F, 21F, -1F);
lowerLegPanel1.setTextureSize(64, 128);
lowerLegPanel1.mirror = true;
setRotation(lowerLegPanel1, 0.2443461F, 0.0872665F, 0.0523599F);
leg2 = new ModelRenderer(this, 0, 16);
leg2.addBox(-1F, -12F, -1.5F, 2, 12, 3);
leg2.setRotationPoint(2.5F, 24F, 0F);
leg2.setTextureSize(64, 128);
leg2.mirror = true;
setRotation(leg2, 0F, 0F, -0.0523599F);
foot2 = new ModelRenderer(this, 2, 33);
foot2.addBox(-1.5F, -0.5F, -5F, 3, 1, 6);
foot2.setRotationPoint(2.5F, 22.5F, 1F);
foot2.setTextureSize(64, 128);
foot2.mirror = true;
setRotation(foot2, 0.2443461F, 0F, 0F);
backWheel2 = new ModelRenderer(this, 0, 40);
backWheel2.addBox(0F, -1F, -1F, 1, 2, 2);
backWheel2.setRotationPoint(3.5F, 22.5F, 0F);
backWheel2.setTextureSize(64, 128);
backWheel2.mirror = true;
setRotation(backWheel2, 0F, 0F, 0F);
upperLegPanel2 = new ModelRenderer(this, 0, 31);
upperLegPanel2.addBox(-1.5F, -3F, -1F, 3, 4, 1);
upperLegPanel2.setRotationPoint(2.1F, 15F, -1.2F);
upperLegPanel2.setTextureSize(64, 128);
upperLegPanel2.mirror = true;
setRotation(upperLegPanel2, 0F, -0.1919862F, -0.0523599F);
lowerLegPanel2 = new ModelRenderer(this, 10, 16);
lowerLegPanel2.addBox(-1.5F, -5F, -1F, 3, 6, 1);
lowerLegPanel2.setRotationPoint(2.5F, 21F, -1F);
lowerLegPanel2.setTextureSize(64, 128);
lowerLegPanel2.mirror = true;
setRotation(lowerLegPanel2, 0.2443461F, -0.0872665F, -0.0523599F);
hipSlab1 = new ModelRenderer(this, 18, 16);
hipSlab1.addBox(-0.5F, -4F, -2F, 1, 4, 4);
hipSlab1.setRotationPoint(0F, 12.7F, 0F);
hipSlab1.setTextureSize(64, 128);
hipSlab1.mirror = true;
setRotation(hipSlab1, 0F, 0F, -0.7853982F);
hipSlab2 = new ModelRenderer(this, 18, 16);
hipSlab2.addBox(-0.5F, -4F, -2F, 1, 4, 4);
hipSlab2.setRotationPoint(0F, 12.7F, 0F);
hipSlab2.setTextureSize(64, 128);
hipSlab2.mirror = true;
setRotation(hipSlab2, 0F, 0F, 0.7853982F);
windShield = new ModelRenderer(this, 36, 33);
windShield.addBox(-2.5F, 0F, 0F, 5, 3, 1);
windShield.setRotationPoint(0F, 0F, 2F);
windShield.setTextureSize(64, 128);
windShield.mirror = true;
setRotation(windShield, 0F, 0F, 0F);
chest = new ModelRenderer(this, 18, 24);
chest.addBox(-4F, -5F, -2F, 8, 5, 4);
chest.setRotationPoint(0F, 5F, 0F);
chest.setTextureSize(64, 128);
chest.mirror = true;
setRotation(chest, 0F, 0F, 0F);
frontCar1 = new ModelRenderer(this, 28, 18);
frontCar1.addBox(-3F, -2F, -3F, 3, 2, 2);
frontCar1.setRotationPoint(-0.5F, 2.5F, 0F);
frontCar1.setTextureSize(64, 128);
frontCar1.mirror = true;
setRotation(frontCar1, 0F, 0.2443461F, 0.0872665F);
frontCar2 = new ModelRenderer(this, 28, 18);
frontCar2.mirror = true;
frontCar2.addBox(0F, -2F, -3F, 3, 2, 2);
frontCar2.setRotationPoint(0.5F, 2.5F, 0F);
frontCar2.setTextureSize(64, 128);
setRotation(frontCar2, 0F, -0.2443461F, -0.0872665F);
frontCar2.mirror = true;
torso = new ModelRenderer(this, 28, 10);
torso.addBox(-2.5F, -5F, -1.5F, 5, 5, 3);
torso.setRotationPoint(0F, 9F, 0F);
torso.setTextureSize(64, 128);
torso.mirror = true;
setRotation(torso, 0F, 0F, 0F);
waist = new ModelRenderer(this, 18, 33);
waist.addBox(-3F, -3F, -1.5F, 6, 3, 3);
waist.setRotationPoint(0F, 12F, 0F);
waist.setTextureSize(64, 128);
waist.mirror = true;
setRotation(waist, 0F, 0F, 0F);
chestPanel1 = new ModelRenderer(this, 10, 23);
chestPanel1.addBox(-1F, -4F, -1.5F, 2, 4, 1);
chestPanel1.setRotationPoint(-1F, 7.5F, -0.5F);
chestPanel1.setTextureSize(64, 128);
chestPanel1.mirror = true;
setRotation(chestPanel1, 0.2443461F, 0.1396263F, -0.3141593F);
chestPanel2 = new ModelRenderer(this, 10, 23);
chestPanel2.addBox(-1F, -4F, -1.5F, 2, 4, 1);
chestPanel2.setRotationPoint(1F, 7.5F, -0.5F);
chestPanel2.setTextureSize(64, 128);
chestPanel2.mirror = true;
setRotation(chestPanel2, 0.2443461F, -0.1396263F, 0.3141593F);
chestPanel3 = new ModelRenderer(this, 20, 10);
chestPanel3.addBox(-1F, -1.5F, -2F, 2, 4, 2);
chestPanel3.setRotationPoint(0F, 2.1F, -0.9F);
chestPanel3.setTextureSize(64, 128);
chestPanel3.mirror = true;
setRotation(chestPanel3, 0.1047198F, 0F, 0F);
upperArm1 = new ModelRenderer(this, 52, 11);
upperArm1.addBox(-2.5F, -1F, -1.5F, 3, 5, 3);
upperArm1.setRotationPoint(-4F, 2F, 0F);
upperArm1.setTextureSize(64, 128);
upperArm1.mirror = true;
setRotation(upperArm1, 0.0872665F, 0F, 0.1745329F);
frontWheel1 = new ModelRenderer(this, 0, 40);
frontWheel1.addBox(-1F, -1F, -1F, 1, 2, 2);
frontWheel1.setRotationPoint(-4F, 0.5F, 0F);
frontWheel1.setTextureSize(64, 128);
frontWheel1.mirror = true;
setRotation(frontWheel1, 0.0872665F, 0F, 0.8901179F);
lowerArm1 = new ModelRenderer(this, 42, 18);
lowerArm1.addBox(-1F, -4F, -1F, 2, 11, 2);
lowerArm1.setRotationPoint(-5.7F, 5F, 0.5F);
lowerArm1.setTextureSize(64, 128);
lowerArm1.mirror = true;
setRotation(lowerArm1, -0.2443461F, 0F, 0.1396263F);
armPanel1 = new ModelRenderer(this, 44, 11);
armPanel1.addBox(-1F, -2F, -1.5F, 1, 4, 3);
armPanel1.setRotationPoint(-7F, 8.5F, -0.3F);
armPanel1.setTextureSize(64, 128);
armPanel1.mirror = true;
setRotation(armPanel1, -0.2617994F, 0F, 0.0872665F);
upperArm2 = new ModelRenderer(this, 52, 11);
upperArm2.addBox(-0.5F, -1F, -1.5F, 3, 5, 3);
upperArm2.setRotationPoint(4F, 2F, 0F);
upperArm2.setTextureSize(64, 128);
upperArm2.mirror = true;
setRotation(upperArm2, 0.0872665F, 0F, -0.1745329F);
lowerArm2 = new ModelRenderer(this, 42, 18);
lowerArm2.addBox(-1F, -4F, -1F, 2, 11, 2);
lowerArm2.setRotationPoint(5.7F, 5F, 0.5F);
lowerArm2.setTextureSize(64, 128);
lowerArm2.mirror = true;
setRotation(lowerArm2, -0.2443461F, 0F, -0.1396263F);
armPanel2 = new ModelRenderer(this, 44, 11);
armPanel2.addBox(0F, -2F, -1.5F, 1, 4, 3);
armPanel2.setRotationPoint(7F, 8.5F, -0.3F);
armPanel2.setTextureSize(64, 128);
armPanel2.mirror = true;
setRotation(armPanel2, -0.2617994F, 0F, -0.0872665F);
frontWheel2 = new ModelRenderer(this, 0, 40);
frontWheel2.addBox(0F, -1F, -1F, 1, 2, 2);
frontWheel2.setRotationPoint(4F, 0.5F, 0F);
frontWheel2.setTextureSize(64, 128);
frontWheel2.mirror = true;
setRotation(frontWheel2, 0.0872665F, 0F, -0.8901179F);
head = new ModelRenderer(this, 0, 0);
head.addBox(-2F, -4F, -1.5F, 4, 4, 3);
head.setRotationPoint(0F, 0F, 0F);
head.setTextureSize(64, 128);
head.mirror = true;
setRotation(head, 0F, 0F, 0F);
ear1 = new ModelRenderer(this, 8, 7);
ear1.addBox(-1F, -3F, -1F, 1, 4, 2);
ear1.setRotationPoint(-1.2F, -1F, -1F);
ear1.setTextureSize(64, 128);
ear1.mirror = true;
setRotation(ear1, -0.418879F, -0.1745329F, 0F);
ear2 = new ModelRenderer(this, 8, 7);
ear2.addBox(0F, -3F, -1F, 1, 4, 2);
ear2.setRotationPoint(1.2F, -1F, -1F);
ear2.setTextureSize(64, 128);
ear2.mirror = true;
setRotation(ear2, -0.418879F, 0.1745329F, 0F);
mask = new ModelRenderer(this, 0, 7);
mask.addBox(-1.5F, -2F, -1F, 3, 4, 1);
mask.setRotationPoint(0F, -2F, -1.5F);
mask.setTextureSize(64, 128);
mask.mirror = true;
setRotation(mask, -0.1745329F, 0F, 0F);
this.addChildTo(waist, bipedBody);
this.addChildTo(hipSlab1, waist);
this.addChildTo(hipSlab2, waist);
this.addChildTo(torso, waist);
this.addChildTo(chestPanel1, torso);
this.addChildTo(chestPanel2, torso);
this.addChildTo(chest, torso);
this.addChildTo(chestPanel3, chest);
this.addChildTo(frontCar1, chest);
this.addChildTo(frontCar2, chest);
this.addChildTo(windShield, chest);
this.addChildTo(frontWheel1, chest);
this.addChildTo(frontWheel2, chest);
this.addChildTo(head, bipedHead);
this.addChildTo(mask, head);
this.addChildTo(ear1, mask);
this.addChildTo(ear2, mask);
this.addChildTo(upperArm1, bipedRightArm);
this.addChildTo(lowerArm1, upperArm1);
this.addChildTo(armPanel1, lowerArm1);
this.addChildTo(upperArm2, bipedLeftArm);
this.addChildTo(lowerArm2, upperArm2);
this.addChildTo(armPanel2, lowerArm2);
this.addChildTo(leg1, bipedRightLeg);
this.addChildTo(upperLegPanel1, leg1);
this.addChildTo(lowerLegPanel1, leg1);
this.addChildTo(foot1, leg1);
this.addChildTo(backWheel1, leg1);
this.addChildTo(leg2, bipedLeftLeg);
this.addChildTo(upperLegPanel2, leg2);
this.addChildTo(lowerLegPanel2, leg2);
this.addChildTo(foot2, leg2);
this.addChildTo(backWheel2, leg2);
vehichleFrontWheel1 = new ModelRenderer(this, 0, 64);
vehichleFrontWheel1.addBox(-1F, -1F, -1F, 1, 2, 2);
vehichleFrontWheel1.setRotationPoint(-2.3F, 23F, -4.5F);
vehichleFrontWheel1.setTextureSize(64, 128);
vehichleFrontWheel1.mirror = true;
setRotation(vehichleFrontWheel1, 0F, 0F, 0F);
vehichleFrontWheel2 = new ModelRenderer(this, 0, 64);
vehichleFrontWheel2.addBox(0F, -1F, -1F, 1, 2, 2);
vehichleFrontWheel2.setRotationPoint(2.3F, 23F, -4.5F);
vehichleFrontWheel2.setTextureSize(64, 128);
vehichleFrontWheel2.mirror = true;
setRotation(vehichleFrontWheel2, 0F, 0F, 0F);
vehichleBackWheel1 = new ModelRenderer(this, 0, 64);
vehichleBackWheel1.addBox(-1F, -1F, -1F, 1, 2, 2);
vehichleBackWheel1.setRotationPoint(-2.3F, 23F, 4F);
vehichleBackWheel1.setTextureSize(64, 128);
vehichleBackWheel1.mirror = true;
setRotation(vehichleBackWheel1, 0F, 0F, 0F);
vehichleBackWheel2 = new ModelRenderer(this, 0, 64);
vehichleBackWheel2.addBox(0F, -1F, -1F, 1, 2, 2);
vehichleBackWheel2.setRotationPoint(2.3F, 23F, 4F);
vehichleBackWheel2.setTextureSize(64, 128);
vehichleBackWheel2.mirror = true;
setRotation(vehichleBackWheel2, 0F, 0F, 0F);
vehichleBumper1 = new ModelRenderer(this, 0, 68);
vehichleBumper1.addBox(-2.5F, -1.5F, -2F, 3, 2, 2);
vehichleBumper1.setRotationPoint(0F, 23F, -5F);
vehichleBumper1.setTextureSize(64, 128);
vehichleBumper1.mirror = true;
setRotation(vehichleBumper1, 0F, 0.2443461F, 0F);
vehichleBumper2 = new ModelRenderer(this, 0, 68);
vehichleBumper2.mirror = true;
vehichleBumper2.addBox(-0.5F, -1.5F, -2F, 3, 2, 2);
vehichleBumper2.setRotationPoint(0F, 23F, -5F);
vehichleBumper2.setTextureSize(64, 128);
setRotation(vehichleBumper2, 0F, -0.2443461F, 0F);
vehichleBumper2.mirror = true;
vehichleRoof = new ModelRenderer(this, 0, 78);
vehichleRoof.addBox(-2.5F, -0.5F, 0F, 5, 1, 2);
vehichleRoof.setRotationPoint(0F, 20.7F, -0.5F);
vehichleRoof.setTextureSize(64, 128);
vehichleRoof.mirror = true;
setRotation(vehichleRoof, 0F, 0F, 0F);
vehichleBody = new ModelRenderer(this, 0, 64);
vehichleBody.addBox(-3F, -1F, 0F, 6, 2, 12);
vehichleBody.setRotationPoint(0F, 22.5F, -6.2F);
vehichleBody.setTextureSize(64, 128);
vehichleBody.mirror = true;
setRotation(vehichleBody, 0F, 0F, 0F);
vehichleHood = new ModelRenderer(this, 0, 81);
vehichleHood.addBox(-2F, -1F, -2F, 4, 1, 3);
vehichleHood.setRotationPoint(0F, 22.3F, -3.7F);
vehichleHood.setTextureSize(64, 128);
vehichleHood.mirror = true;
setRotation(vehichleHood, 0F, 0F, 0F);
vehichleBackWindShield = new ModelRenderer(this, 14, 78);
vehichleBackWindShield.addBox(-2.5F, -0.5F, 0F, 5, 1, 3);
vehichleBackWindShield.setRotationPoint(0F, 20.7F, 1.3F);
vehichleBackWindShield.setTextureSize(64, 128);
vehichleBackWindShield.mirror = true;
setRotation(vehichleBackWindShield, -0.3839724F, 0F, 0F);
vehichleWindShield = new ModelRenderer(this, 14, 82);
vehichleWindShield.addBox(-2.5F, -1F, 0F, 5, 1, 3);
vehichleWindShield.setRotationPoint(0F, 22.4F, -2.7F);
vehichleWindShield.setTextureSize(64, 128);
vehichleWindShield.mirror = true;
setRotation(vehichleWindShield, 0.4537856F, 0F, 0F);
vehichleSpoiler = new ModelRenderer(this, 24, 64);
vehichleSpoiler.addBox(-2.5F, -1F, -1.5F, 5, 1, 3);
vehichleSpoiler.setRotationPoint(0F, 22F, 4.8F);
vehichleSpoiler.setTextureSize(64, 128);
vehichleSpoiler.mirror = true;
setRotation(vehichleSpoiler, 0.1919862F, 0F, 0F);
vehichleDoor1 = new ModelRenderer(this, 24, 68);
vehichleDoor1.addBox(-1F, -1F, -1.5F, 1, 1, 3);
vehichleDoor1.setRotationPoint(-1.8F, 21.7F, 0.5F);
vehichleDoor1.setTextureSize(64, 128);
vehichleDoor1.mirror = true;
setRotation(vehichleDoor1, 0F, 0F, 0.2268928F);
vehichleDoor2 = new ModelRenderer(this, 24, 68);
vehichleDoor2.addBox(0F, -1F, -1.5F, 1, 1, 3);
vehichleDoor2.setRotationPoint(1.8F, 21.7F, 0.5F);
vehichleDoor2.setTextureSize(64, 128);
vehichleDoor2.mirror = true;
setRotation(vehichleDoor2, 0F, 0F, -0.2268928F);
this.addChildTo(vehichleFrontWheel1, vehichleBody);
this.addChildTo(vehichleFrontWheel2, vehichleBody);
this.addChildTo(vehichleBackWheel1, vehichleBody);
this.addChildTo(vehichleBackWheel2, vehichleBody);
this.addChildTo(vehichleBumper1, vehichleBody);
this.addChildTo(vehichleBumper2, vehichleBody);
this.addChildTo(vehichleRoof, vehichleBody);
this.addChildTo(vehichleHood, vehichleBody);
this.addChildTo(vehichleBackWindShield, vehichleBody);
this.addChildTo(vehichleWindShield, vehichleBody);
this.addChildTo(vehichleSpoiler, vehichleBody);
this.addChildTo(vehichleDoor1, vehichleBody);
this.addChildTo(vehichleDoor2, vehichleBody);
adjustPos();
}
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5)
{
super.render(entity, f, f1, f2, f3, f4, f5);
setRotationAngles(f, f1, f2, f3, f4, f5, entity);
vehichleBody.render(f5);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void setRotationAngles(float par1, float par2, float par3, float par4, float par5, float par6, Entity entity)
{
super.setRotationAngles(par1, par2, par3, par4, par5, par6, entity);
if (entity instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer)entity;
if (TFPlayerData.getTransformationTimer(player) == 0)
{
float f = this.bipedHead.rotateAngleY - (this.bipedBody.rotateAngleY - this.bipedHead.rotateAngleY) / 3;
if (vehichleBody.rotateAngleY < f) {vehichleBody.rotateAngleY += 0.05F;}
if (vehichleBody.rotateAngleY > f) {vehichleBody.rotateAngleY -= 0.05F;}
vehichleBody.rotateAngleY = f;
vehichleBody.rotateAngleX = -(float)player.motionY - 0.0784000015258789F;
vehichleFrontWheel1.rotateAngleX = -par1;
vehichleFrontWheel2.rotateAngleX = -par1;
vehichleBackWheel1.rotateAngleX = -par1;
vehichleBackWheel2.rotateAngleX = -par1;
bipedHead.offsetY = 256F;
bipedBody.offsetY = 256F;
bipedRightArm.offsetY = 256F;
bipedLeftArm.offsetY = 256F;
bipedRightLeg.offsetY = 256F;
bipedLeftLeg.offsetY = 256F;
vehichleBody.offsetY = 0F;
}
else
{
int t = TFPlayerData.getTransformationTimer(player);
float f = (10 - t);
vehichleBody.rotateAngleX = 0;
bipedBody.rotationPointY = f * 2.5F;
bipedBody.rotationPointZ = f / 10 * -7.5F;
bipedRightArm.rotationPointZ = f / 10 * -5F;
bipedLeftArm.rotationPointZ = f / 10 * -5F;
chest.rotationPointZ = -3.0F / 10 * f;
chest.rotateAngleX = -pi / 2 / 10 * f;
bipedRightArm.rotationPointY = f * 2;
bipedLeftArm.rotationPointY = f * 2;
bipedRightArm.rotationPointX = f / 3.5F - 5;
bipedLeftArm.rotationPointX = -f / 3.5F + 5;
bipedRightLeg.rotateAngleZ = f * pi / 10;
bipedLeftLeg.rotateAngleZ = f * pi / 10;
bipedRightLeg.rotationPointX = -f / 7.5F;
bipedLeftLeg.rotationPointX = -f / 7.5F;
if (t < 10)
{
bipedRightLeg.rotateAngleX = f * pi / 2 / 10;
bipedLeftLeg.rotateAngleX = f * pi / 2 / 10;
bipedRightLeg.rotationPointY = f * 1.3F + 12;
bipedLeftLeg.rotationPointY = f * 1.3F + 12;
bipedRightLeg.rotationPointZ = -f / 2;
bipedLeftLeg.rotationPointZ = -f / 2;
bipedBody.rotateAngleX = pi / 2 / 10 * f;
bipedHead.rotationPointY = f * 2.5F;
bipedRightArm.rotateAngleX = f / 10 * 1.5F;
bipedLeftArm.rotateAngleX = f / 10 * 1.5F;
}
bipedHead.offsetY = 0F;
bipedBody.offsetY = 0F;
bipedRightArm.offsetY = 0F;
bipedLeftArm.offsetY = 0F;
bipedRightLeg.offsetY = 0F;
bipedLeftLeg.offsetY = 0F;
vehichleBody.offsetY = 256F;
}
}
}
public void adjustPos()
{
// Body
chest.rotationPointY = -4F;
frontCar1.rotationPointY = -2.5F;
frontCar2.rotationPointY = -2.5F;
chestPanel1.rotationPointY = -1.5F;
chestPanel2.rotationPointY = -1.5F;
chestPanel3.rotationPointY = -3F;
windShield.rotationPointY = -5F;
frontWheel1.rotationPointY = -4.5F;
frontWheel2.rotationPointY = -4.5F;
// Arms
upperArm1.rotationPointX = 1F;
lowerArm1.setRotationPoint(-1F, 3.5F, 0);
armPanel1.setRotationPoint(-1F, 3.75F, 0F);
setRotation(armPanel1, 0F, 0F, -0.0872665F);
upperArm2.rotationPointX = -1F;
lowerArm2.setRotationPoint(1F, 3.5F, 0);
armPanel2.setRotationPoint(1F, 3.75F, 0F);
setRotation(armPanel2, 0F, 0F, 0.0872665F);
// Legs
leg1.rotationPointY = 12F;
leg2.rotationPointY = 12F;
upperLegPanel1.rotationPointX = 0F;
upperLegPanel2.rotationPointX = 0F;
}
}<file_sep>/src/main/java/fiskfille/tf/common/packet/base/TFPacketManager.java
package fiskfille.tf.common.packet.base;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import cpw.mods.fml.relauncher.Side;
import fiskfille.tf.common.packet.PacketBroadcastState;
import fiskfille.tf.common.packet.PacketCloudtrapJetpack;
import fiskfille.tf.common.packet.PacketHandleStealthTransformation;
import fiskfille.tf.common.packet.PacketHandleTransformation;
import fiskfille.tf.common.packet.PacketSendFlying;
import fiskfille.tf.common.packet.PacketTransformersAction;
import fiskfille.tf.common.packet.PacketSyncStates;
import fiskfille.tf.common.packet.PacketVehicleNitro;
import fiskfille.tf.common.packet.PacketVurpSniperShoot;
public class TFPacketManager
{
public static SimpleNetworkWrapper networkWrapper;
private static int packetId = 0;
public static void registerPackets()
{
networkWrapper = NetworkRegistry.INSTANCE.newSimpleChannel("transformersMod");
registerPacket(PacketHandleTransformation.Handler.class, PacketHandleTransformation.class);
registerPacket(PacketHandleStealthTransformation.Handler.class, PacketHandleStealthTransformation.class);
registerPacket(PacketSyncStates.Handler.class, PacketSyncStates.class);
registerPacket(PacketTransformersAction.Handler.class, PacketTransformersAction.class);
registerPacket(PacketCloudtrapJetpack.Handler.class, PacketCloudtrapJetpack.class);
registerPacket(PacketBroadcastState.Handler.class, PacketBroadcastState.class);
registerPacket(PacketVehicleNitro.Handler.class, PacketVehicleNitro.class);
registerPacket(PacketVurpSniperShoot.Handler.class, PacketVurpSniperShoot.class);
registerPacket(PacketSendFlying.Handler.class, PacketSendFlying.class);
}
private static <REQ extends IMessage, REPLY extends IMessage> void registerPacket(Class<? extends IMessageHandler<REQ, REPLY>> messageHandler, Class<REQ> requestMessageType)
{
networkWrapper.registerMessage(messageHandler, requestMessageType, packetId++, Side.CLIENT);
networkWrapper.registerMessage(messageHandler, requestMessageType, packetId++, Side.SERVER);
}
}
<file_sep>/src/Legacy/java/fiskfille/tf/main/TFHelper.java
package fiskfille.tf.main;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fiskfille.tf.item.ITransformerArmor;
import fiskfille.tf.main.misc.ClientProxy;
import fiskfille.tf.model.ModelCustomPlayer;
public class TFHelper
{
private static TFHelper instance = new TFHelper();
public static TFHelper getInstance()
{
return instance;
}
private static boolean hasPlayerFullArmor(EntityPlayer player)
{
return player != null ? player.getCurrentArmor(0) != null && player.getCurrentArmor(1) != null && player.getCurrentArmor(2) != null && player.getCurrentArmor(3) != null : false;
}
public static boolean isPlayerSkystrike(EntityPlayer player)
{
return hasPlayerFullArmor(player) ? player.getCurrentArmor(3).getItem() == TFItems.skystrikeHelmet && player.getCurrentArmor(2).getItem() == TFItems.skystrikeChestplate && player.getCurrentArmor(1).getItem() == TFItems.skystrikeLeggings && player.getCurrentArmor(0).getItem() == TFItems.skystrikeBoots : false;
}
public static boolean isPlayerPurge(EntityPlayer player)
{
return hasPlayerFullArmor(player) ? player.getCurrentArmor(3).getItem() == TFItems.purgeHelmet && player.getCurrentArmor(2).getItem() == TFItems.purgeChestplate && player.getCurrentArmor(1).getItem() == TFItems.purgeLeggings && player.getCurrentArmor(0).getItem() == TFItems.purgeBoots : false;
}
public static boolean isPlayerVurp(EntityPlayer player)
{
return hasPlayerFullArmor(player) ? player.getCurrentArmor(3).getItem() == TFItems.vurpHelmet && player.getCurrentArmor(2).getItem() == TFItems.vurpChestplate && player.getCurrentArmor(1).getItem() == TFItems.vurpLeggings && player.getCurrentArmor(0).getItem() == TFItems.vurpBoots : false;
}
public static boolean isPlayerSubwoofer(EntityPlayer player)
{
return hasPlayerFullArmor(player) ? player.getCurrentArmor(3).getItem() == TFItems.subwooferHelmet && player.getCurrentArmor(2).getItem() == TFItems.subwooferChestplate && player.getCurrentArmor(1).getItem() == TFItems.subwooferLeggings && player.getCurrentArmor(0).getItem() == TFItems.subwooferBoots : false;
}
public static ResourceLocation getPlayerHandTexture(EntityPlayer player)
{
if (player.getCurrentArmor(2) != null)
{
if (player.getCurrentArmor(2).getItem() == TFItems.skystrikeChestplate) {return new ResourceLocation(MainClass.modid, "textures/models/skystrike/skystrike1.png");}
if (player.getCurrentArmor(2).getItem() == TFItems.purgeChestplate) {return new ResourceLocation(MainClass.modid, "textures/models/purge/purge1.png");}
if (player.getCurrentArmor(2).getItem() == TFItems.vurpChestplate) {return new ResourceLocation(MainClass.modid, "textures/models/vurp/vurp1.png");}
if (player.getCurrentArmor(2).getItem() == TFItems.vurpChestplate) {return new ResourceLocation(MainClass.modid, "textures/models/subwoofer/subwoofer.png");}
}
return null;
}
@SideOnly(Side.CLIENT)
public static ModelBiped getPlayerModel(EntityPlayer player, int piece)
{
if (player.getCurrentArmor(piece) != null)
{
if (player.getCurrentArmor(piece).getItem() == TFItems.skystrikeChestplate) {return ClientProxy.modelSkystrike;}
if (player.getCurrentArmor(piece).getItem() == TFItems.purgeChestplate) {return ClientProxy.modelPurge;}
if (player.getCurrentArmor(piece).getItem() == TFItems.vurpChestplate) {return ClientProxy.modelVurp;}
if (player.getCurrentArmor(piece).getItem() == TFItems.subwooferChestplate) {return ClientProxy.modelSubwoofer;}
}
return null;
}
public static boolean isTransformerArmor(EntityPlayer player, Item item)
{
return item instanceof ITransformerArmor;
}
public void adjustPlayerVisibility(EntityPlayer player, ModelBiped model)
{
boolean flag = Minecraft.getMinecraft().gameSettings.thirdPersonView == 0;
if (player.getCurrentArmor(3) != null)
{
int i = isTransformerArmor(player, player.getCurrentArmor(3).getItem()) ? 256 : 0;
model.bipedHead.offsetY = i;
model.bipedHeadwear.offsetY = i;
}
else
{
model.bipedHead.offsetY = 0;
model.bipedHeadwear.offsetY = 0;
}
if (player.getCurrentArmor(2) != null)
{
int i = isTransformerArmor(player, player.getCurrentArmor(2).getItem()) ? 256 : 0;
model.bipedBody.offsetY = i;
model.bipedRightArm.offsetY = i;
model.bipedLeftArm.offsetY = i;
}
else
{
model.bipedBody.offsetY = 0;
model.bipedRightArm.offsetY = 0;
model.bipedLeftArm.offsetY = 0;
}
if (player.getCurrentArmor(1) != null)
{
int i = isTransformerArmor(player, player.getCurrentArmor(1).getItem()) ? 256 : 0;
model.bipedRightLeg.offsetY = i;
model.bipedLeftLeg.offsetY = i;
}
else
{
model.bipedRightLeg.offsetY = 0;
model.bipedLeftLeg.offsetY = 0;
}
model.bipedRightArm.rotateAngleX = 1;
ClientProxy.modelBipedMain.bipedRightArm.rotateAngleX = 1;
}
}<file_sep>/src/main/java/fiskfille/tf/client/particle/EntityTFFlameFX.java
package fiskfille.tf.client.particle;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class EntityTFFlameFX extends EntityFX
{
/** the scale of the flame FX */
private float flameScale;
public EntityTFFlameFX(World world, double x, double y, double z, double motionX, double motionY, double motionZ)
{
super(world, x, y, z, motionX, motionY, motionZ);
this.motionX = this.motionX * 0.009999999776482582D + motionX;
this.motionY = this.motionY * 0.009999999776482582D + motionY;
this.motionZ = this.motionZ * 0.009999999776482582D + motionZ;
double d6 = x + (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.05F);
d6 = y + (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.05F);
d6 = z + (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.05F);
this.flameScale = this.particleScale;
this.particleRed = this.particleGreen = this.particleBlue = 1.0F;
this.particleMaxAge = (int)(8.0D / (Math.random() * 0.8D + 0.2D)) + 4;
this.noClip = true;
this.setParticleTextureIndex(48);
}
public void renderParticle(Tessellator tesselator, float x, float y, float z, float r, float g, float b)
{
float f6 = ((float)this.particleAge + x) / (float)this.particleMaxAge;
this.particleScale = this.flameScale * (1.0F - f6 * f6 * 0.5F);
super.renderParticle(tesselator, x, y, z, r, g, b);
}
public int getBrightnessForRender(float p_70070_1_)
{
float f1 = ((float)this.particleAge + p_70070_1_) / (float)this.particleMaxAge;
if (f1 < 0.0F)
{
f1 = 0.0F;
}
if (f1 > 1.0F)
{
f1 = 1.0F;
}
int i = super.getBrightnessForRender(p_70070_1_);
int j = i & 255;
int k = i >> 16 & 255;
j += (int)(f1 * 15.0F * 16.0F);
if (j > 240)
{
j = 240;
}
return j | k << 16;
}
/**
* Gets how bright this entity is.
*/
public float getBrightness(float p_70013_1_)
{
float f1 = ((float)this.particleAge + p_70013_1_) / (float)this.particleMaxAge;
if (f1 < 0.0F)
{
f1 = 0.0F;
}
if (f1 > 1.0F)
{
f1 = 1.0F;
}
float f2 = super.getBrightness(p_70013_1_);
return f2 * f1 + (1.0F - f1);
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate()
{
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
if (this.particleAge++ >= this.particleMaxAge)
{
this.setDead();
}
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.9599999785423279D;
this.motionY *= 0.9599999785423279D;
this.motionZ *= 0.9599999785423279D;
if (this.onGround)
{
this.motionX *= 0.699999988079071D;
this.motionZ *= 0.699999988079071D;
}
if(!worldObj.isAirBlock((int) posX, (int) posY, (int) posZ))
{
this.setDead();
// this.motionX = -this.motionX;
// this.motionY = -this.motionY;
// this.motionZ = -this.motionZ;
}
}
}<file_sep>/src/main/java/fiskfille/tf/common/entity/EntityFlamethrowerFire.java
package fiskfille.tf.common.entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.Blocks;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import fiskfille.tf.client.particle.TFParticleType;
import fiskfille.tf.client.particle.TFParticles;
import fiskfille.tf.common.motion.TFMotionManager;
public class EntityFlamethrowerFire extends EntityThrowable
{
public EntityFlamethrowerFire(World world)
{
super(world);
}
public EntityFlamethrowerFire(World world, EntityLivingBase entity)
{
super(world, entity);
}
public EntityFlamethrowerFire(World world, double x, double y, double z)
{
super(world, x, y, z);
}
protected float getGravityVelocity()
{
return 0.0F;
}
protected float func_70182_d()
{
return 1.0F;
}
public void onUpdate()
{
super.onUpdate();
if (this.isEntityAlive())
{
if(worldObj.isRemote)
{
for (int i = 0; i < 5; ++i)
{
float f = (rand.nextFloat() / 5);
TFParticles.spawnParticle(TFParticleType.FLAMETHROWER_FLAME, posX + f, posY + 0.15F + f, posZ + f, 0, 0, 0);
}
}
if (ticksExisted > 7)
{
this.setDead();
}
}
}
protected void onImpact(MovingObjectPosition mop)
{
if (mop.entityHit != null)
{
mop.entityHit.setFire(20);
if (getThrower() instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer)getThrower();
mop.entityHit.attackEntityFrom(DamageSource.causePlayerDamage(player), 10.0F);
}
}
setFire(worldObj, mop.blockX, mop.blockY, mop.blockZ, mop.sideHit);
this.setDead();
}
public boolean setFire(World world, int x, int y, int z, int sideHit)
{
if (sideHit == 0)
{
--y;
}
if (sideHit == 1)
{
++y;
}
if (sideHit == 2)
{
--z;
}
if (sideHit == 3)
{
++z;
}
if (sideHit == 4)
{
--x;
}
if (sideHit == 5)
{
++x;
}
if (world.isAirBlock(x, y, z))
{
world.setBlock(x, y, z, Blocks.fire);
}
return true;
}
}<file_sep>/src/main/java/fiskfille/tf/client/render/entity/RenderMiniMissile.java
package fiskfille.tf.client.render.entity;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.entity.Entity;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fiskfille.tf.TransformersMod;
import fiskfille.tf.client.model.ModelMissile;
import fiskfille.tf.common.entity.EntityMiniMissile;
@SideOnly(Side.CLIENT)
public class RenderMiniMissile extends Render
{
private ModelMissile model = new ModelMissile();
private ResourceLocation texture = new ResourceLocation(TransformersMod.modid, "textures/models/weapons/missile.png");
/**
* Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
* handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic
* (Render<T extends Entity) and this method has signature public void func_76986_a(T entity, double d, double d1,
* double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
*/
public void doRender(EntityMiniMissile miniMissile, double x, double y, double z, float rotationYaw, float p_76986_9_)
{
this.bindEntityTexture(miniMissile);
GL11.glPushMatrix();
GL11.glTranslatef((float)x, (float)y, (float)z);
GL11.glRotatef(miniMissile.prevRotationYaw + (miniMissile.rotationYaw - miniMissile.prevRotationYaw) * p_76986_9_ - 90.0F, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(miniMissile.prevRotationPitch + (miniMissile.rotationPitch - miniMissile.prevRotationPitch) * p_76986_9_, 0.0F, 0.0F, 1.0F);
GL11.glRotatef(90, 0, -1, 0);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
float f11 = (float)miniMissile.missileShake - p_76986_9_;
if (f11 > 0.0F)
{
float f12 = -MathHelper.sin(f11 * 3.0F) * f11;
GL11.glRotatef(f12, 0.0F, 0.0F, 1.0F);
}
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
float f = 0.7F;
GL11.glScalef(f, f, f);
model.render(miniMissile, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0625F);
GL11.glRotatef(90, 0.0F, 0.0F, -1.0F);
GL11.glPopMatrix();
}
/**
* Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture.
*/
protected ResourceLocation getEntityTexture(EntityMiniMissile tankShell)
{
return texture;
}
/**
* Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture.
*/
protected ResourceLocation getEntityTexture(Entity p_110775_1_)
{
return this.getEntityTexture((EntityMiniMissile)p_110775_1_);
}
/**
* Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
* handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic
* (Render<T extends Entity) and this method has signature public void func_76986_a(T entity, double d, double d1,
* double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
*/
public void doRender(Entity entity, double x, double y, double z, float rotationYaw, float partialTicks)
{
this.doRender((EntityMiniMissile)entity, x, y, z, rotationYaw, partialTicks);
}
}<file_sep>/src/main/java/fiskfille/tf/client/event/ClientEventHandler.java
package fiskfille.tf.client.event;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraftforge.client.event.FOVUpdateEvent;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.event.entity.PlaySoundAtEntityEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import fiskfille.tf.client.keybinds.TFKeyBinds;
import fiskfille.tf.client.render.entity.CustomEntityRenderer;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.motion.TFMotionManager;
import fiskfille.tf.common.motion.VehicleMotion;
import fiskfille.tf.common.playerdata.TFDataManager;
import fiskfille.tf.common.transformer.base.Transformer;
import fiskfille.tf.helper.TFHelper;
public class ClientEventHandler
{
private final Minecraft mc = Minecraft.getMinecraft();
private EntityRenderer renderer, prevRenderer;
@SubscribeEvent
public void onPlaySound(PlaySoundAtEntityEvent event)
{
if (event.entity instanceof EntityPlayer)
{
if (event.name.startsWith("step.") && TFDataManager.isInVehicleMode((EntityPlayer) event.entity))
{
event.setCanceled(true);
}
}
}
@SubscribeEvent
public void onRenderPlayerSpecialsPre(RenderPlayerEvent.Specials.Pre event)
{
if (TFDataManager.getTransformationTimer(event.entityPlayer) < 10)
{
event.setCanceled(true);
}
}
@SubscribeEvent
public void onRenderPlayerPre(RenderPlayerEvent.Pre event)
{
EntityPlayer player = event.entityPlayer;
Transformer transformer = TFHelper.getTransformer(player);
boolean isClientPlayer = mc.thePlayer == player;
boolean isTransformer = TFHelper.isPlayerTransformer(player);
boolean inVehicleMode = TFDataManager.isInVehicleMode(player);
int transformationTimer = TFDataManager.getTransformationTimer(player);
boolean isTransformerAndInVehicleMode = isTransformer && inVehicleMode;
float cameraYOffset = 0;
if (transformer != null)
{
cameraYOffset = transformer.getCameraYOffset(player);
}
if (isClientPlayer && cameraYOffset != 0)
{
GL11.glPushMatrix();
GL11.glTranslatef(0, -CustomEntityRenderer.getOffsetY(player), 0);
}
// This prevents the player from sinking into the ground when sneaking in vehicle mode
if (player.isSneaking() && TFDataManager.getTransformationTimer(player) < 20)
{
GL11.glTranslatef(0, 0.08F, 0);
}
}
@SubscribeEvent
public void onRenderPlayer(RenderPlayerEvent.Post event)
{
EntityPlayer player = event.entityPlayer;
Transformer transformer = TFHelper.getTransformer(player);
boolean isClientPlayer = mc.thePlayer == player;
if (transformer != null)
{
if (isClientPlayer && transformer.getCameraYOffset(player) != 0.0F)
{
GL11.glPopMatrix();
}
}
// ModelBiped modelBipedMain = ObfuscationReflectionHelper.getPrivateValue(RenderPlayer.class, event.renderer, new String[]{"f", "modelBipedMain"});
// TFModelHelper.modelBipedMain = modelBipedMain;
//
// ObfuscationReflectionHelper.setPrivateValue(RenderPlayer.class, event.renderer, modelBipedMain, new String[]{"f", "modelBipedMain"});
}
@SubscribeEvent
public void renderTick(TickEvent.RenderTickEvent event)
{
Minecraft mc = Minecraft.getMinecraft();
if (mc.theWorld != null)
{
if (event.phase == TickEvent.Phase.START)
{
EntityClientPlayerMP player = mc.thePlayer;
Transformer transformer = TFHelper.getTransformer(player);
if (transformer != null)
{
if (transformer.getCameraYOffset(player) != 0.0F)
{
if (renderer == null)
{
renderer = new CustomEntityRenderer(mc);
}
if (mc.entityRenderer != renderer)
{
prevRenderer = mc.entityRenderer;
mc.entityRenderer = renderer;
}
}
else if (prevRenderer != null && mc.entityRenderer != prevRenderer)
{
mc.entityRenderer = prevRenderer;
}
}
else if (prevRenderer != null && mc.entityRenderer != prevRenderer)
{
mc.entityRenderer = prevRenderer;
}
}
}
}
@SubscribeEvent
public void onFOVUpdate(FOVUpdateEvent event)
{
EntityPlayerSP player = event.entity;
VehicleMotion transformedPlayer = TFMotionManager.getTransformerPlayer(player);
int nitro = transformedPlayer == null ? 0 : transformedPlayer.getNitro();
boolean moveForward = Minecraft.getMinecraft().gameSettings.keyBindForward.getIsKeyPressed();
boolean nitroPressed = TFKeyBinds.keyBindingNitro.getIsKeyPressed() || Minecraft.getMinecraft().gameSettings.keyBindSprint.getIsKeyPressed();
if (TFDataManager.isInVehicleMode(player))
{
if (nitro > 0 && moveForward && nitroPressed && !TFDataManager.isInStealthMode(player))
{
event.newfov = 1.3F;
}
}
else
{
ItemStack itemstack = player.getHeldItem();
if (TFDataManager.getZoomTimer(player) > 0 && TFHelper.isPlayerVurp(player) && itemstack != null && itemstack.getItem() == TFItems.vurpsSniper && this.mc.gameSettings.thirdPersonView == 0)
{
event.newfov = 1.0F - (float)TFDataManager.getZoomTimer(player) / 10;
}
}
if (TFDataManager.getTransformationTimer(player) < 20 && !(nitro > 0 && moveForward && nitroPressed && !TFDataManager.isInStealthMode(player)))
{
event.newfov = 1.0F;
}
}
@SubscribeEvent
public void onItemToolTip(ItemTooltipEvent event)
{
String s = "tooltip." + event.itemStack.getUnlocalizedName();
if (!s.equals(StatCollector.translateToLocal(s)))
{
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT))
{
event.toolTip.add(StatCollector.translateToLocal(s));
}
else
{
event.toolTip.add(EnumChatFormatting.BLUE + "Hold SHIFT for info.");
}
}
}
}<file_sep>/src/main/java/fiskfille/tf/helper/TFShootManager.java
package fiskfille.tf.helper;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.packet.PacketTransformersAction;
import fiskfille.tf.common.packet.base.TFPacketManager;
import fiskfille.tf.common.playerdata.TFDataManager;
import fiskfille.tf.common.transformer.base.Transformer;
public class TFShootManager
{
public static int shootCooldown = 0;
public static int shotsLeft = 4;
public static boolean reloading;
@SubscribeEvent
public void onLivingUpdate(LivingUpdateEvent event)
{
if (event.entity instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) event.entity;
if (event.entity.worldObj.isRemote)
{
if (player == Minecraft.getMinecraft().thePlayer)
{
Transformer transformer = TFHelper.getTransformer(player);
if (transformer != null)
{
if (shootCooldown > 0)
{
shootCooldown--;
}
if(TFHelper.isPlayerVurp(player) && !TFDataManager.isInVehicleMode(player)) //TODO
{
if (reloading && shootCooldown <= 0)
{
shotsLeft = getShotsLeft(player, transformer, TFItems.miniMissile);
reloading = false;
}
}
else
{
Item ammo = transformer.getShootItem();
if (ammo != null)
{
int ammoCount = getShotsLeft(player, transformer, ammo);
if (TFDataManager.isInVehicleMode(player))
{
if (reloading && shootCooldown <= 0)
{
shotsLeft = ammoCount;
reloading = false;
}
}
else
{
int shots = ammoCount;
if (shotsLeft > shots)
{
shotsLeft = shots;
}
}
}
}
}
}
}
}
}
private int getShotsLeft(EntityPlayer player, Transformer transformer, Item shootItem)
{
int maxAmmo = transformer.getShots();
if(!TFDataManager.isInVehicleMode(player))
{
maxAmmo = 4;
}
int ammoCount;
if (player.capabilities.isCreativeMode)
{
ammoCount = maxAmmo;
}
else
{
ammoCount = getAmountOf(shootItem, player);
}
if (ammoCount > maxAmmo)
{
ammoCount = maxAmmo;
}
if (shotsLeft > ammoCount)
{
shotsLeft = ammoCount;
}
return ammoCount;
}
private int getAmountOf(Item item, EntityPlayer player)
{
int amount = 0;
InventoryPlayer inventory = player.inventory;
for(ItemStack stack : inventory.mainInventory)
{
if (stack != null)
{
if (stack.getItem() == item)
{
amount += stack.stackSize;
}
}
}
return amount;
}
@SubscribeEvent
public void onPlayerInteract(PlayerInteractEvent event)
{
EntityPlayer player = event.entityPlayer;
Transformer transformer = TFHelper.getTransformer(player);
if(transformer != null && TFDataManager.isInVehicleMode(player))
{
if (transformer.canShoot(player))
{
Action action = event.action;
if (action == PlayerInteractEvent.Action.RIGHT_CLICK_AIR || action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK)
{
if (shotsLeft > 0)
{
if (shootCooldown <= 0)
{
if (transformer.canShoot(player))
{
Item shootItem = transformer.getShootItem();
boolean isCreative = player.capabilities.isCreativeMode;
boolean hasAmmo = isCreative || player.inventory.hasItem(shootItem);
if (hasAmmo)
{
TFPacketManager.networkWrapper.sendToServer(new PacketTransformersAction(player, action));
if (!isCreative)
{
player.inventory.consumeInventoryItem(shootItem);
}
}
}
shotsLeft--;
if (shotsLeft <= 0)
{
shootCooldown = 20;
reloading = true;
}
}
}
else
{
if (!reloading)
{
shootCooldown = 20;
reloading = true;
}
}
}
event.setCanceled(true);
}
}
}
}
<file_sep>/src/main/java/fiskfille/tf/common/block/BlockTransformiumStone.java
package fiskfille.tf.common.block;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fiskfille.tf.TransformersMod;
public class BlockTransformiumStone extends BlockBasic
{
public BlockTransformiumStone()
{
super(Material.rock);
this.setCreativeTab(TransformersMod.tabTransformers);
}
@SideOnly(Side.CLIENT)
public void randomDisplayTick(World world, int x, int y, int z, Random rand)
{
// world.spawnParticle("smoke", x + 0.5F + (rand.nextFloat() - 0.5F), y + 1.0F, z + 0.5F + (rand.nextFloat() - 0.5F), 0.0D, 0.0D, 0.0D);
}
}<file_sep>/src/main/java/fiskfille/tf/common/transformer/TransformerCloudtrap.java
package fiskfille.tf.common.transformer;
import net.minecraft.item.Item;
import fiskfille.tf.client.model.transformer.ModelChildBase.Biped;
import fiskfille.tf.client.model.transformer.TFModelRegistry;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.transformer.base.TransformerJet;
public class TransformerCloudtrap extends TransformerJet
{
public TransformerCloudtrap()
{
super("Cloudtrap");
}
@Override
public Item getHelmet()
{
return TFItems.cloudtrapHelmet;
}
@Override
public Item getChestplate()
{
return TFItems.cloudtrapChestplate;
}
@Override
public Item getLeggings()
{
return TFItems.cloudtrapLeggings;
}
@Override
public Item getBoots()
{
return TFItems.cloudtrapBoots;
}
@Override
public boolean hasJetpack()
{
return true;
}
}<file_sep>/src/main/java/fiskfille/tf/common/transformer/base/TransformerTruck.java
package fiskfille.tf.common.transformer.base;
import java.util.Random;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.entity.Entity;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.util.Vec3;
import fiskfille.tf.client.keybinds.TFKeyBinds;
import fiskfille.tf.client.particle.NitroParticleHandler;
import fiskfille.tf.common.entity.EntityMissile;
import fiskfille.tf.common.event.CommonEventHandler;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.motion.TFMotionManager;
import fiskfille.tf.common.motion.VehicleMotion;
import fiskfille.tf.common.packet.PacketVehicleNitro;
import fiskfille.tf.common.packet.base.TFPacketManager;
import fiskfille.tf.common.playerdata.TFDataManager;
import fiskfille.tf.common.playerdata.TFPlayerData;
import fiskfille.tf.config.TFConfig;
import fiskfille.tf.helper.TFHelper;
import fiskfille.tf.helper.TFModelHelper;
public abstract class TransformerTruck extends Transformer
{
public TransformerTruck(String name)
{
super(name);
}
@Override
public float fall(EntityPlayer player, float distance)
{
return TFDataManager.isInVehicleMode(player) ? distance / 4 : super.fall(player, distance);
}
@Override
public boolean hasStealthForce(EntityPlayer player)
{
return true;
}
@Override
public boolean canJumpAsVehicle(EntityPlayer player)
{
return TFDataManager.isInStealthMode(player);
}
@Override
public float getCameraYOffset(EntityPlayer player)
{
return -1F;
}
@Override
public void updateMovement(EntityPlayer player)
{
Minecraft mc = Minecraft.getMinecraft();
boolean inStealthMode = TFDataManager.isInStealthMode(player);
boolean moveForward = mc.gameSettings.keyBindForward.getIsKeyPressed();
boolean moveSide = player.moveStrafing != 0;
boolean nitroPressed = TFKeyBinds.keyBindingNitro.getIsKeyPressed() || mc.gameSettings.keyBindSprint.getIsKeyPressed();
int nitro = 0;
double forwardVelocity = 0;
double horizontalVelocity = 0;
player.stepHeight = 1.0F;
VehicleMotion transformedPlayer = TFMotionManager.getTransformerPlayer(player);
if (transformedPlayer != null)
{
nitro = transformedPlayer.getNitro();
forwardVelocity = transformedPlayer.getForwardVelocity();
horizontalVelocity = transformedPlayer.getHorizontalVelocity();
double increment;
if (inStealthMode)
{
increment = (0.2D - forwardVelocity) / 10;
}
else
{
if(nitroPressed && nitro > 0)
{
increment = 0.68D;
}
else
{
increment = 0.45D;
}
increment -= forwardVelocity;
increment = increment / 10;
if(forwardVelocity < 0.5D)
{
increment += 0.05D;
}
}
if (moveForward && forwardVelocity <= 1.0D)
{
forwardVelocity += increment * 0.5F;
}
else if (forwardVelocity > 0.02D)
{
forwardVelocity -= 0.02D;
}
else if (forwardVelocity <= 0.02D)
{
forwardVelocity = 0;
}
if (moveSide && horizontalVelocity <= 1.0D && inStealthMode)
{
horizontalVelocity += increment * 0.5F;
}
else if (horizontalVelocity > 0.02D)
{
horizontalVelocity-= 0.02D;
}
else if (horizontalVelocity <= 0.02D)
{
horizontalVelocity = 0;
}
Vec3 forwardVec = TFMotionManager.getFrontCoords(player, 0, forwardVelocity);
player.motionX = (forwardVec.xCoord - player.posX);
player.motionZ = (forwardVec.zCoord - player.posZ);
if (forwardVelocity <= 0) {forwardVelocity = 0;}
if (forwardVelocity > 1) {forwardVelocity = 1;}
boolean prevNitro = TFMotionManager.prevNitro;
if (nitro > 0 && nitroPressed && moveForward && player == mc.thePlayer && !inStealthMode)
{
if (!player.capabilities.isCreativeMode) --nitro;
if (!prevNitro)
{
TFPacketManager.networkWrapper.sendToServer(new PacketVehicleNitro(player, true));
TFMotionManager.prevNitro = true;
}
for (int i = 0; i < 4; ++i)
{
Vec3 side = TFMotionManager.getBackSideCoords(player, 0.15F, i < 2, -0.9, false);
Random rand = new Random();
player.worldObj.spawnParticle("smoke", side.xCoord, player.posY - 1.6F, side.zCoord, rand.nextFloat() / 20, rand.nextFloat() / 20, rand.nextFloat() / 20);
}
for (int i = 0; i < 10; ++i)
{
Vec3 side = TFMotionManager.getBackSideCoords(player, 0.15F, i < 2, -0.9, false);
Random rand = new Random();
player.worldObj.spawnParticle("smoke", side.xCoord, player.posY - 1.6F, side.zCoord, rand.nextFloat() / 10, rand.nextFloat() / 10 + 0.05F, rand.nextFloat() / 10);
}
}
else
{
if (prevNitro)
{
TFPacketManager.networkWrapper.sendToServer(new PacketVehicleNitro(player, false));
TFMotionManager.prevNitro = false;
}
}
transformedPlayer.setNitro(nitro);
transformedPlayer.setForwardVelocity(forwardVelocity);
transformedPlayer.setHorizontalVelocity(horizontalVelocity);
if (player.isInWater())
{
player.motionY = -0.1F;
}
}
}
@Override
public boolean canShoot(EntityPlayer player)
{
return TFDataManager.getStealthModeTimer(player) < 5;
}
@Override
public Item getShootItem()
{
return TFItems.missile;
}
@Override
public Entity getShootEntity(EntityPlayer player)
{
EntityMissile entityMissile = new EntityMissile(player.worldObj, player, 3, TFConfig.allowMissileExplosions, TFDataManager.isInStealthMode(player));
entityMissile.posY--;
return entityMissile;
}
@Override
public int getShots()
{
return 8;
}
@Override
public void doNitroParticles(EntityPlayer player)
{
for (int i = 0; i < 4; ++i)
{
Vec3 side = NitroParticleHandler.getBackSideCoords(player, 0.15F, i < 2, -1.3, false);
Random rand = new Random();
player.worldObj.spawnParticle("smoke", side.xCoord, player.posY, side.zCoord, rand.nextFloat() / 20, rand.nextFloat() / 20, rand.nextFloat() / 20);
}
for (int i = 0; i < 10; ++i)
{
Vec3 side = NitroParticleHandler.getBackSideCoords(player, 0.15F, i < 2, -1.3, false);
Random rand = new Random();
player.worldObj.spawnParticle("smoke", side.xCoord, player.posY, side.zCoord, rand.nextFloat() / 10, rand.nextFloat() / 10 + 0.05F, rand.nextFloat() / 10);
}
}
@Override
public void transformationTick(EntityPlayer player, int timer)
{
if(TFDataManager.isInVehicleMode(player) && timer == 0)
{
IAttributeInstance entityAttribute = player.getEntityAttribute(SharedMonsterAttributes.movementSpeed);
Transformer transformer = TFHelper.getTransformer(player);
if (!TFPlayerData.getData(player).stealthForce)
{
CommonEventHandler.prevMove = entityAttribute.getAttributeValue();
entityAttribute.setBaseValue(0.0D);
}
else
{
if(CommonEventHandler.prevMove != 0)
{
entityAttribute.setBaseValue(CommonEventHandler.prevMove);
}
}
}
}
}
<file_sep>/src/main/java/fiskfille/tf/common/block/BlockEnergonCrystal.java
package fiskfille.tf.common.block;
import static net.minecraftforge.common.util.ForgeDirection.EAST;
import static net.minecraftforge.common.util.ForgeDirection.NORTH;
import static net.minecraftforge.common.util.ForgeDirection.SOUTH;
import static net.minecraftforge.common.util.ForgeDirection.WEST;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import fiskfille.tf.TransformersMod;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.tileentity.TileEntityCrystal;
public class BlockEnergonCrystal extends BlockBasic implements ITileEntityProvider
{
private Random rand = new Random();
public BlockEnergonCrystal()
{
super(Material.glass);
this.setCreativeTab(TransformersMod.tabTransformers);
}
protected boolean canSilkHarvest()
{
return true;
}
public int quantityDropped(Random random)
{
return random.nextInt(3) + 2;
}
public Item getItemDropped(int p_149650_1_, Random random, int p_149650_3_)
{
return TFItems.energonCrystalPiece;
}
@Override
public int getExpDrop(IBlockAccess world, int p_149690_5_, int p_149690_7_)
{
return MathHelper.getRandomIntegerInRange(rand, 0, 2);
}
public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z)
{
return null;
}
public boolean renderAsNormalBlock()
{
return false;
}
public int getRenderType()
{
return -1;
}
public boolean isOpaqueCube()
{
return false;
}
public boolean hasTileEntity()
{
return true;
}
private boolean isSolid(World world, int x, int y, int z)
{
if (World.doesBlockHaveSolidTopSurface(world, x, y, z))
{
return true;
}
else
{
Block block = world.getBlock(x, y, z);
return block.canPlaceTorchOnTop(world, x, y, z);
}
}
/**
* Checks to see if its valid to put this block at the specified coordinates. Args: world, x, y, z
*/
public boolean canPlaceBlockAt(World world, int x, int y, int z)
{
return world.isSideSolid(x - 1, y, z, EAST, true) ||
world.isSideSolid(x + 1, y, z, WEST, true) ||
world.isSideSolid(x, y, z - 1, SOUTH, true) ||
world.isSideSolid(x, y, z + 1, NORTH, true) ||
isSolid(world, x, y - 1, z) ||
isSolid(world, x, y + 1, z);
}
/**
* Called when a block is placed using its ItemBlock. Args: World, X, Y, Z, side, hitX, hitY, hitZ, block metadata
*/
public int onBlockPlaced(World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata)
{
int rotation = metadata;
if (side == 0 && this.isSolid(world, x, y + 1, z))
{
rotation = 6;
}
if (side == 1 && this.isSolid(world, x, y - 1, z))
{
rotation = 5;
}
if (side == 2 && world.isSideSolid(x, y, z + 1, NORTH, true))
{
rotation = 4;
}
if (side == 3 && world.isSideSolid(x, y, z - 1, SOUTH, true))
{
rotation = 3;
}
if (side == 4 && world.isSideSolid(x + 1, y, z, WEST, true))
{
rotation = 2;
}
if (side == 5 && world.isSideSolid(x - 1, y, z, EAST, true))
{
rotation = 1;
}
return rotation;
}
/**
* Ticks the block if it's been scheduled
*/
public void updateTick(World world, int x, int y, int z, Random rand)
{
super.updateTick(world, x, y, z, rand);
if (world.getBlockMetadata(x, y, z) == 0)
{
this.onBlockAdded(world, x, y, z);
}
}
/**
* Called whenever the block is added into the world. Args: world, x, y, z
*/
public void onBlockAdded(World world, int x, int y, int z)
{
if (world.getBlockMetadata(x, y, z) == 0)
{
if (world.isSideSolid(x - 1, y, z, EAST, true))
{
world.setBlockMetadataWithNotify(x, y, z, 1, 2);
}
else if (world.isSideSolid(x + 1, y, z, WEST, true))
{
world.setBlockMetadataWithNotify(x, y, z, 2, 2);
}
else if (world.isSideSolid(x, y, z - 1, SOUTH, true))
{
world.setBlockMetadataWithNotify(x, y, z, 3, 2);
}
else if (world.isSideSolid(x, y, z + 1, NORTH, true))
{
world.setBlockMetadataWithNotify(x, y, z, 4, 2);
}
else if (this.isSolid(world, x, y - 1, z))
{
world.setBlockMetadataWithNotify(x, y, z, 5, 2);
}
else if (this.isSolid(world, x, y + 1, z))
{
world.setBlockMetadataWithNotify(x, y, z, 6, 2);
}
}
this.canPlaceAt(world, x, y, z);
}
/**
* Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are
* their own) Args: x, y, z, neighbor Block
*/
public void onNeighborBlockChange(World world, int x, int y, int z, Block block)
{
this.neighbourChanged(world, x, y, z, block);
}
protected boolean neighbourChanged(World world, int x, int y, int z, Block block)
{
if (this.canPlaceAt(world, x, y, z))
{
int metadata = world.getBlockMetadata(x, y, z);
boolean canSupport = true;
if (!world.isSideSolid(x - 1, y, z, EAST, true) && metadata == 1)
{
canSupport = false;
}
else if (!world.isSideSolid(x + 1, y, z, WEST, true) && metadata == 2)
{
canSupport = false;
}
else if (!world.isSideSolid(x, y, z - 1, SOUTH, true) && metadata == 3)
{
canSupport = false;
}
else if (!world.isSideSolid(x, y, z + 1, NORTH, true) && metadata == 4)
{
canSupport = false;
}
else if (!this.isSolid(world, x, y - 1, z) && metadata == 5)
{
canSupport = false;
}
else if (!this.isSolid(world, x, y + 1, z) && metadata == 6)
{
canSupport = false;
}
if (!canSupport)
{
if (new Random().nextInt(9) == 0)
{
if (!world.isRemote && world.getGameRules().getGameRuleBooleanValue("doTileDrops") && !world.restoringBlockSnapshots) // do not drop items while restoring blockstates, prevents item dupe
{
float f = 0.7F;
double motionX = (double)(world.rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D;
double motionY = (double)(world.rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D;
double motionZ = (double)(world.rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D;
EntityItem entityitem = new EntityItem(world, (double)x + motionX, (double)y + motionY, (double)z + motionZ, new ItemStack(TFBlocks.energonCrystal));
entityitem.delayBeforeCanPickup = 10;
world.spawnEntityInWorld(entityitem);
}
}
else
{
this.dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0);
}
world.setBlockToAir(x, y, z);
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
protected boolean canPlaceAt(World world, int x, int y, int z)
{
if (!this.canPlaceBlockAt(world, x, y, z))
{
if (world.getBlock(x, y, z) == this)
{
this.dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0);
world.setBlockToAir(x, y, z);
}
return false;
}
else
{
return true;
}
}
/**
* Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. Args: world,
* x, y, z, startVec, endVec
*/
public MovingObjectPosition collisionRayTrace(World p_149731_1_, int p_149731_2_, int p_149731_3_, int p_149731_4_, Vec3 p_149731_5_, Vec3 p_149731_6_)
{
int l = p_149731_1_.getBlockMetadata(p_149731_2_, p_149731_3_, p_149731_4_) & 7;
float f = 0.21F;
if (l == 1)
{
this.setBlockBounds(0.0F, 0.2F, 0.5F - f, f * 2.0F, 0.8F, 0.5F + f);
}
else if (l == 2)
{
this.setBlockBounds(1.0F - f * 2.0F, 0.2F, 0.5F - f, 1.0F, 0.8F, 0.5F + f);
}
else if (l == 3)
{
this.setBlockBounds(0.5F - f, 0.2F, 0.0F, 0.5F + f, 0.8F, f * 2.0F);
}
else if (l == 4)
{
this.setBlockBounds(0.5F - f, 0.2F, 1.0F - f * 2.0F, 0.5F + f, 0.8F, 1.0F);
}
else if (l == 6)
{
f = 0.2F;
this.setBlockBounds(0.5F - f, 0.0F + f * 2, 0.5F - f, 0.5F + f, 1.0F, 0.5F + f);
}
else
{
f = 0.2F;
this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.6F, 0.5F + f);
}
return super.collisionRayTrace(p_149731_1_, p_149731_2_, p_149731_3_, p_149731_4_, p_149731_5_, p_149731_6_);
}
public TileEntity createNewTileEntity(World world, int metadata)
{
return new TileEntityCrystal();
}
public void registerBlockIcons(IIconRegister par1IconRegister)
{
blockIcon = par1IconRegister.registerIcon(TransformersMod.modid + ":energon_crystal");
}
}<file_sep>/src/Legacy/java/fiskfille/tf/block/BlockDisplayPillar.java
package fiskfille.tf.block;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import fiskfille.tf.item.IDisplayPillarItem;
import fiskfille.tf.main.MainClass;
import fiskfille.tf.main.TFItems;
import fiskfille.tf.render.tileentity.RenderDisplayPillar;
import fiskfille.tf.tileentity.TileEntityDisplayPillar;
public class BlockDisplayPillar extends BlockBasic implements ITileEntityProvider
{
private Random rand = new Random();
public BlockDisplayPillar()
{
super(Material.rock);
this.setCreativeTab(MainClass.tabTransformers);
}
public void breakBlock(World world, int x, int y, int z, Block block, int metadata)
{
ItemStack itemstack = metadata != 0 ? new ItemStack(TFItems.displayVehicle, 1, metadata - 1) : null;
if (itemstack != null)
{
float f = this.rand.nextFloat() * 0.8F + 0.1F;
float f1 = this.rand.nextFloat() * 0.8F + 0.1F;
float f2 = this.rand.nextFloat() * 0.8F + 0.1F;
while (itemstack.stackSize > 0)
{
int j1 = this.rand.nextInt(21) + 10;
if (j1 > itemstack.stackSize)
{
j1 = itemstack.stackSize;
}
itemstack.stackSize -= j1;
EntityItem entityitem = new EntityItem(world, (double)((float)x + f), (double)((float)y + f1), (double)((float)z + f2), new ItemStack(itemstack.getItem(), j1, itemstack.getItemDamage()));
if (itemstack.hasTagCompound())
{
entityitem.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy());
}
float f3 = 0.05F;
entityitem.motionX = (double)((float)this.rand.nextGaussian() * f3);
entityitem.motionY = (double)((float)this.rand.nextGaussian() * f3 + 0.2F);
entityitem.motionZ = (double)((float)this.rand.nextGaussian() * f3);
world.spawnEntityInWorld(entityitem);
}
}
super.breakBlock(world, x, y, z, block, metadata);
}
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int p_149727_6_, float p_149727_7_, float p_149727_8_, float p_149727_9_)
{
if (world.isRemote)
{
return false;
}
else
{
TileEntityDisplayPillar tileentitydisplaypillar = (TileEntityDisplayPillar)world.getTileEntity(x, y, z);
if (tileentitydisplaypillar != null)
{
int meta = world.getBlockMetadata(x, y, z);
for (int i = 0; i < 5; ++i)
{
if (meta == i + 1 && player.getHeldItem() == null)
{
world.setBlockMetadataWithNotify(x, y, z, 0, 2);
player.setCurrentItemOrArmor(0, new ItemStack(TFItems.displayVehicle, 1, i));
}
else if (meta == 0 && player.getHeldItem() != null && player.getHeldItem().getItem() == TFItems.displayVehicle && player.getHeldItem().getItemDamage() == i)
{
world.setBlockMetadataWithNotify(x, y, z, i + 1, 2);
player.setCurrentItemOrArmor(0, null);
}
}
}
return false;
}
}
public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 p_149731_5_, Vec3 p_149731_6_)
{
int l = world.getBlockMetadata(x, y, z);
float f = 0.21F;
if (l == 0)
{
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.55F, 1.0F);
}
else if (l == 1 || l == 2)
{
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
}
else if (l == 3 || l == 4)
{
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F);
}
return super.collisionRayTrace(world, x, y, z, p_149731_5_, p_149731_6_);
}
public boolean renderAsNormalBlock()
{
return false;
}
public int getRenderType()
{
return -1;
}
public boolean isOpaqueCube()
{
return false;
}
public boolean hasTileEntity()
{
return true;
}
public TileEntity createNewTileEntity(World world, int metadata)
{
return new TileEntityDisplayPillar();
}
@Override
public void registerBlockIcons(IIconRegister par1IconRegister)
{
blockIcon = par1IconRegister.registerIcon(MainClass.modid + ":" + getUnlocalizedName().substring(5));
}
}<file_sep>/src/Legacy/java/fiskfille/tf/main/misc/ClientTickHandler.java
package fiskfille.tf.main.misc;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.potion.Potion;
import net.minecraft.util.Vec3;
import org.lwjgl.input.Keyboard;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import fiskfille.tf.data.TFPlayerData;
import fiskfille.tf.main.TFConfig;
import fiskfille.tf.main.TFHelper;
import fiskfille.tf.render.entity.EntityRendererAlt;
public class ClientTickHandler
{
private Minecraft mc = Minecraft.getMinecraft();
public void onPlayerTick(EntityPlayer player)
{
float offsetY = 1.0F - (float)TFPlayerData.getTransformationTimer(player) / 10;
EntityRendererAlt.offsetY = -offsetY;
if (!TFHelper.getInstance().isPlayerSkystrike(player) && !TFHelper.isPlayerPurge(player) && !TFHelper.isPlayerVurp(player) && !TFHelper.isPlayerSubwoofer(player))
{
TFPlayerData.setInVehichleMode(player, false);
}
if (TFPlayerData.getTransformationTimer(player) < 10 && !TFPlayerData.isInVehicleMode(player))
{
TFPlayerData.setTransformationTimer(player, TFPlayerData.getTransformationTimer(player) + 1);
TFVehichleModeMotionManager.velocityMap.put(player.getCommandSenderName(), 0.0D);
if (TFPlayerData.getTransformationTimer(player) == 9)
{
Minecraft.getMinecraft().gameSettings.thirdPersonView = TFConfig.firstPersonAfterTransformation ? 0 : Minecraft.getMinecraft().gameSettings.thirdPersonView;
}
}
if (TFPlayerData.getTransformationTimer(player) > 0 && TFPlayerData.isInVehicleMode(player))
{
TFPlayerData.setTransformationTimer(player, TFPlayerData.getTransformationTimer(player) - 1);
if (TFHelper.isPlayerVurp(player) || TFHelper.isPlayerSubwoofer(player))
{
double vel = TFVehichleModeMotionManager.velocityMap.get(player.getCommandSenderName()) == null ? 0 : TFVehichleModeMotionManager.velocityMap.get(player.getCommandSenderName());
Vec3 vec3 = TFVehichleModeMotionManager.getFrontCoords(player, 0, vel);
vel += 0.05D;
player.motionX = (vec3.xCoord - player.posX);
player.motionZ = (vec3.zCoord - player.posZ);
if (TFPlayerData.getTransformationTimer(player) >= 7)
{
player.motionY += 0.2D;
}
TFVehichleModeMotionManager.velocityMap.put(player.getCommandSenderName(), vel);
}
}
if (player != null)
{
if (TFPlayerData.isInVehicleMode(player) && TFPlayerData.getTransformationTimer(player) < 5)
{
player.setSprinting(false);
Minecraft.getMinecraft().gameSettings.viewBobbing = false;
Minecraft.getMinecraft().gameSettings.thirdPersonView = Keyboard.isKeyDown(Keyboard.KEY_R) && Minecraft.getMinecraft().currentScreen == null ? 2 : 3;
if (TFHelper.isPlayerSkystrike(player))
{
TFVehichleModeMotionManager.motionJet(player);
}
if (TFHelper.isPlayerPurge(player))
{
TFVehichleModeMotionManager.motionTank(player);
}
if (TFHelper.isPlayerVurp(player))
{
TFVehichleModeMotionManager.motionCar(player);
}
if (TFHelper.isPlayerSubwoofer(player))
{
TFVehichleModeMotionManager.motionCar(player);
}
}
else
{
if (TFHelper.isPlayerSkystrike(player) && !player.capabilities.isFlying)
{
if (player.motionY < 0.0D)
{
player.motionY *= 0.85F;
}
else
{
player.motionY += 0.02D;
}
}
player.stepHeight = 0.5F;
Minecraft.getMinecraft().gameSettings.viewBobbing = true;
if (player.isPotionActive(Potion.resistance) && player.getActivePotionEffect(Potion.resistance).getDuration() < 1)
{
player.removePotionEffect(Potion.resistance.id);
}
}
}
int nitro = TFVehichleModeMotionManager.nitroMap.get(player.getCommandSenderName()) == null ? 0 : TFVehichleModeMotionManager.nitroMap.get(player.getCommandSenderName());
boolean moveForward = Minecraft.getMinecraft().gameSettings.keyBindForward.getIsKeyPressed();
boolean nitroPressed = ClientProxy.keyBindingNitro.getIsKeyPressed() || Minecraft.getMinecraft().gameSettings.keyBindSprint.getIsKeyPressed();
if (nitro < 160 && !(nitroPressed && moveForward && TFPlayerData.isInVehicleMode(player) && TFPlayerData.getTransformationTimer(player) < 5))
{
++nitro;
}
TFVehichleModeMotionManager.nitroMap.put(player.getCommandSenderName(), nitro);
}
public void onClientTickEnd()
{
EntityPlayer player = mc.thePlayer;
try
{
// ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, mc.entityRenderer, 0, new String[] { "camRoll", "R", "field_78495_O" });
float thirdPersonDistance = 4.0F - (2.0F - (float)TFPlayerData.getTransformationTimer(player) / 5);
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, mc.entityRenderer, TFHelper.isPlayerSkystrike(player) ? 4.0F : thirdPersonDistance, new String[] { "thirdPersonDistance", "E", "field_78490_B" });
}
catch (Exception e) {}
}
public void onClientTickStart()
{
}
}<file_sep>/src/main/java/fiskfille/tf/common/item/TFItems.java
package fiskfille.tf.common.item;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import net.minecraftforge.common.util.EnumHelper;
import fiskfille.tf.TransformersMod;
import fiskfille.tf.common.item.armor.ItemCloudtrapArmor;
import fiskfille.tf.common.item.armor.ItemPurgeArmor;
import fiskfille.tf.common.item.armor.ItemSkystrikeArmor;
import fiskfille.tf.common.item.armor.ItemSubwooferArmor;
import fiskfille.tf.common.item.armor.ItemVurpArmor;
import fiskfille.tf.common.registry.TFItemRegistry;
public class TFItems
{
public static ArmorMaterial TRANSFORMERMATERIAL = EnumHelper.addArmorMaterial("Transformer", 1250 / 16, new int[]{3, 9, 6, 3}, 2);
public static ArmorMaterial TANKMATERIAL = EnumHelper.addArmorMaterial("Transformer", 1550 / 16, new int[]{4, 9, 7, 3}, 2);
public static ArmorMaterial SUBWOOFERMATERIAL = EnumHelper.addArmorMaterial("Transformer", 1250 / 16, new int[]{3, 9, 7, 3}, 2);
public static Item transformium;
public static Item transformiumArmorMolds;
public static Item standardEngine;
public static Item jetTurbine;
public static Item jetThruster;
public static Item ahd2JetWing;
public static Item ahd2JetCockpit;
public static Item t50JetWing;
public static Item t50JetCockpit;
public static Item tankTracks;
public static Item tankTurret;
public static Item carWheel;
public static Item skystrikesCrossbow;
public static Item purgesKatana;
public static Item vurpsSniper;
public static Item cloudtrapsFlamethrower;
public static Item subwoofersBassBlaster;
public static Item skystrikeHelmet;
public static Item skystrikeChestplate;
public static Item skystrikeLeggings;
public static Item skystrikeBoots;
public static Item purgeHelmet;
public static Item purgeChestplate;
public static Item purgeLeggings;
public static Item purgeBoots;
public static Item vurpHelmet;
public static Item vurpChestplate;
public static Item vurpLeggings;
public static Item vurpBoots;
public static Item subwooferHelmet;
public static Item subwooferChestplate;
public static Item subwooferLeggings;
public static Item subwooferBoots;
public static Item cloudtrapHelmet;
public static Item cloudtrapChestplate;
public static Item cloudtrapLeggings;
public static Item cloudtrapBoots;
public static Item displayVehicle;
public static Item energonCrystalPiece;
public static Item tankShell;
public static Item miniMissile;
public static Item missile;
public static Item smallThruster;
public static Item transformiumDetector;
public void register()
{
String modId = TransformersMod.modid;
transformium = new ItemBasic();
transformiumArmorMolds = new ItemMetaBasic("Transformium Head Mold", "Transformium Torso Mold", "Transformium Legs Mold", "Transformium Feet Mold");
standardEngine = new ItemBasic();
jetTurbine = new ItemBasic();
ahd2JetWing = new ItemBasic();
ahd2JetCockpit = new ItemBasic();
tankTracks = new ItemBasic();
tankTurret = new ItemBasic();
carWheel = new ItemBasic();
t50JetCockpit = new ItemBasic();
t50JetWing = new ItemBasic();
jetThruster = new ItemBasic();
smallThruster = new ItemBasic();
skystrikesCrossbow = new ItemSkystrikesCrossbow(ToolMaterial.WOOD);
purgesKatana = new ItemPurgesKatana(ToolMaterial.EMERALD);
vurpsSniper = new ItemVurpsSniper(ToolMaterial.WOOD);
cloudtrapsFlamethrower = new ItemFlamethrower(ToolMaterial.WOOD);
subwoofersBassBlaster = new ItemBassBlaster(ToolMaterial.WOOD);
skystrikeHelmet = new ItemSkystrikeArmor(0);
skystrikeChestplate = new ItemSkystrikeArmor(1);
skystrikeLeggings = new ItemSkystrikeArmor(2);
skystrikeBoots = new ItemSkystrikeArmor(3);
purgeHelmet = new ItemPurgeArmor(0);
purgeChestplate = new ItemPurgeArmor(1);
purgeLeggings = new ItemPurgeArmor(2);
purgeBoots = new ItemPurgeArmor(3);
vurpHelmet = new ItemVurpArmor(0);
vurpChestplate = new ItemVurpArmor(1);
vurpLeggings = new ItemVurpArmor(2);
vurpBoots = new ItemVurpArmor(3);
subwooferHelmet = new ItemSubwooferArmor(0);
subwooferChestplate = new ItemSubwooferArmor(1);
subwooferLeggings = new ItemSubwooferArmor(2);
subwooferBoots = new ItemSubwooferArmor(3);
cloudtrapHelmet = new ItemCloudtrapArmor(0);
cloudtrapChestplate = new ItemCloudtrapArmor(1);
cloudtrapLeggings = new ItemCloudtrapArmor(2);
cloudtrapBoots = new ItemCloudtrapArmor(3);
transformiumDetector = new ItemTransformiumDetector();
displayVehicle = new ItemMiniVehicle();
energonCrystalPiece = new ItemBasic();
tankShell = new ItemBasic();
missile = new ItemBasic().setFull3D();
miniMissile = new ItemBasic().setFull3D();
smallThruster = new ItemBasic();
TRANSFORMERMATERIAL.customCraftingMaterial = transformium;
TANKMATERIAL.customCraftingMaterial = transformium;
SUBWOOFERMATERIAL.customCraftingMaterial = transformium;
TFItemRegistry.registerItem(transformium, "Transformium", modId);
TFItemRegistry.registerItem(transformiumArmorMolds, "Transformium Armor Molds", modId);
TFItemRegistry.registerItem(standardEngine, "Standard Engine", modId);
TFItemRegistry.registerItem(jetTurbine, "Jet Turbine", modId);
TFItemRegistry.registerItem(ahd2JetWing, "AHD-2 Jet Wing", modId);
TFItemRegistry.registerItem(ahd2JetCockpit, "AHD-2 Jet Cockpit", modId);
TFItemRegistry.registerItem(t50JetWing, "T-50 Jet Wing", modId);
TFItemRegistry.registerItem(t50JetCockpit, "T-50 Jet Cockpit", modId);
TFItemRegistry.registerItem(tankTracks, "Tracks", modId);
TFItemRegistry.registerItem(tankTurret, "Turret", modId);
TFItemRegistry.registerItem(carWheel, "Wheel", modId);
TFItemRegistry.registerItem(jetThruster, "Jet Thruster", modId);
TFItemRegistry.registerItem(smallThruster, "Small Thruster", modId);
TFItemRegistry.registerItem(transformiumDetector, "Transformium Detector", modId);
TFItemRegistry.registerItem(skystrikesCrossbow, "Skystrike's Energon Crossbow", modId);
TFItemRegistry.registerItem(purgesKatana, "Purge's Katana", modId);
TFItemRegistry.registerItem(vurpsSniper, "Vurp's Sniper", modId);
TFItemRegistry.registerItem(subwoofersBassBlaster, "Subwoofer's Bass Blaster", modId);
TFItemRegistry.registerItem(cloudtrapsFlamethrower, "Flame Thrower", modId);
TFItemRegistry.registerItem(skystrikeHelmet, "Skystrike Head", modId);
TFItemRegistry.registerItem(skystrikeChestplate, "Skystrike Torso", modId);
TFItemRegistry.registerItem(skystrikeLeggings, "Skystrike Legs", modId);
TFItemRegistry.registerItem(skystrikeBoots, "Skystrike Feet", modId);
TFItemRegistry.registerItem(purgeHelmet, "Purge Head", modId);
TFItemRegistry.registerItem(purgeChestplate, "Purge Torso", modId);
TFItemRegistry.registerItem(purgeLeggings, "Purge Legs", modId);
TFItemRegistry.registerItem(purgeBoots, "Purge Feet", modId);
TFItemRegistry.registerItem(vurpHelmet, "Vurp Head", modId);
TFItemRegistry.registerItem(vurpChestplate, "Vurp Torso", modId);
TFItemRegistry.registerItem(vurpLeggings, "Vurp Legs", modId);
TFItemRegistry.registerItem(vurpBoots, "Vurp Feet", modId);
TFItemRegistry.registerItem(subwooferHelmet, "Subwoofer Head", modId);
TFItemRegistry.registerItem(subwooferChestplate, "Subwoofer Torso", modId);
TFItemRegistry.registerItem(subwooferLeggings, "Subwoofer Legs", modId);
TFItemRegistry.registerItem(subwooferBoots, "Subwoofer Feet", modId);
TFItemRegistry.registerItem(cloudtrapHelmet, "Cloudtrap Head", modId);
TFItemRegistry.registerItem(cloudtrapChestplate, "Cloudtrap Torso", modId);
TFItemRegistry.registerItem(cloudtrapLeggings, "Cloudtrap Legs", modId);
TFItemRegistry.registerItem(cloudtrapBoots, "Cloudtrap Feet", modId);
TFItemRegistry.registerItem(displayVehicle, "Display Vehicle", modId);
TFItemRegistry.registerItem(energonCrystalPiece, "Energon Crystal Piece", modId);
TFItemRegistry.registerItem(tankShell, "Tank Shell", modId);
TFItemRegistry.registerItem(missile, "Missile", modId);
TFItemRegistry.registerItem(miniMissile, "Mini Missile", modId);
}
}<file_sep>/src/main/java/fiskfille/tf/common/tab/CreativeTabTransformers.java
package fiskfille.tf.common.tab;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import fiskfille.tf.common.block.TFBlocks;
public class CreativeTabTransformers extends CreativeTabs
{
public CreativeTabTransformers()
{
super("Transformers");
}
@Override
public Item getTabIconItem()
{
return Item.getItemFromBlock(TFBlocks.energonCrystal);
}
}<file_sep>/src/main/java/fiskfille/tf/common/playerdata/TFPlayerData.java
package fiskfille.tf.common.playerdata;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
public class TFPlayerData implements IExtendedEntityProperties
{
public boolean vehicle;
public boolean stealthForce;
public static final String IDENTIFIER = "TFPLAYERDATA";
public static TFPlayerData getData(EntityPlayer player)
{
return (TFPlayerData) player.getExtendedProperties(IDENTIFIER);
}
@Override
public void saveNBTData(NBTTagCompound compound)
{
compound.setBoolean("mode", vehicle);
compound.setBoolean("stealth", stealthForce);
}
@Override
public void loadNBTData(NBTTagCompound compound)
{
vehicle = compound.getBoolean("mode");
stealthForce = compound.getBoolean("stealth");
}
@Override
public void init(Entity entity, World world)
{
}
}
<file_sep>/src/main/java/fiskfille/tf/common/block/BlockDisplayPillar.java
package fiskfille.tf.common.block;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import fiskfille.tf.TransformersMod;
import fiskfille.tf.common.item.ItemMiniVehicle;
import fiskfille.tf.common.tileentity.TileEntityDisplayPillar;
public class BlockDisplayPillar extends BlockBasic implements ITileEntityProvider
{
private Random rand = new Random();
public BlockDisplayPillar()
{
super(Material.rock);
this.setCreativeTab(TransformersMod.tabTransformers);
}
public void breakBlock(World world, int x, int y, int z, Block block, int metadata)
{
TileEntityDisplayPillar tileEntityDisplayPillar = (TileEntityDisplayPillar) world.getTileEntity(x, y, z);
ItemStack itemstack = tileEntityDisplayPillar.getDisplayItem();
if (itemstack != null)
{
float f = this.rand.nextFloat() * 0.8F + 0.1F;
float f1 = this.rand.nextFloat() * 0.8F + 0.1F;
float f2 = this.rand.nextFloat() * 0.8F + 0.1F;
while (itemstack.stackSize > 0)
{
int j1 = this.rand.nextInt(21) + 10;
if (j1 > itemstack.stackSize)
{
j1 = itemstack.stackSize;
}
itemstack.stackSize -= j1;
EntityItem entityitem = new EntityItem(world, (double)((float)x + f), (double)((float)y + f1), (double)((float)z + f2), new ItemStack(itemstack.getItem(), j1, itemstack.getItemDamage()));
if (itemstack.hasTagCompound())
{
entityitem.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy());
}
float f3 = 0.05F;
entityitem.motionX = (double)((float)this.rand.nextGaussian() * f3);
entityitem.motionY = (double)((float)this.rand.nextGaussian() * f3 + 0.2F);
entityitem.motionZ = (double)((float)this.rand.nextGaussian() * f3);
world.spawnEntityInWorld(entityitem);
}
}
super.breakBlock(world, x, y, z, block, metadata);
}
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ)
{
TileEntityDisplayPillar tileEntityDisplayPillar = (TileEntityDisplayPillar) world.getTileEntity(x, y, z);
if (tileEntityDisplayPillar != null)
{
ItemStack heldItem = player.getHeldItem();
ItemStack displayItem = tileEntityDisplayPillar.getDisplayItem();
if (heldItem == null && displayItem != null)
{
player.setCurrentItemOrArmor(0, displayItem);
tileEntityDisplayPillar.setDisplayItem(null, true);
}
else if (heldItem != null && heldItem.getItem() instanceof ItemMiniVehicle)
{
if(displayItem == null)
{
tileEntityDisplayPillar.setDisplayItem(heldItem, true);
//if (!player.capabilities.isCreativeMode)
{
player.setCurrentItemOrArmor(0, null);
}
}
}
}
return false;
}
public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 p_149731_5_, Vec3 p_149731_6_)
{
TileEntityDisplayPillar tileEntityDisplayPillar = (TileEntityDisplayPillar)world.getTileEntity(x, y, z);
if (tileEntityDisplayPillar != null)
{
ItemStack displayItem = tileEntityDisplayPillar.getDisplayItem();
if (displayItem != null)
{
float f = 0.21F;
int metadata = displayItem.getItemDamage();
if (metadata == 0 || metadata == 1 || metadata == 4) {this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);}
else if (metadata == 2 || metadata == 3) {this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F);}
}
else
{
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.55F, 1.0F);
}
}
return super.collisionRayTrace(world, x, y, z, p_149731_5_, p_149731_6_);
}
public boolean renderAsNormalBlock()
{
return false;
}
public int getRenderType()
{
return -1;
}
public boolean isOpaqueCube()
{
return false;
}
public boolean hasTileEntity()
{
return true;
}
public TileEntity createNewTileEntity(World world, int metadata)
{
return new TileEntityDisplayPillar();
}
@Override
public void registerBlockIcons(IIconRegister iconRegister)
{
blockIcon = iconRegister.registerIcon(TransformersMod.modid + ":" + getUnlocalizedName().substring(5));
}
}<file_sep>/src/main/java/fiskfille/tf/common/entity/EntityTransformiumSeed.java
package fiskfille.tf.common.entity;
import java.util.List;
import net.minecraft.command.IEntitySelector;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fiskfille.tf.common.block.TFBlocks;
public class EntityTransformiumSeed extends Entity
{
public int fuse;
public int maxFuse;
private EntityLivingBase placedBye;
public EntityTransformiumSeed(World world)
{
super(world);
this.preventEntitySpawning = true;
this.setSize(0.98F, 0.98F);
this.yOffset = this.height / 2.0F;
}
public EntityTransformiumSeed(World world, double x, double y, double z, EntityLivingBase entity)
{
this(world);
this.setPosition(x, y, z);
float f = (float)(Math.random() * Math.PI * 2.0D);
this.motionX = (double)(-((float)Math.sin((double)f)) * 0.02F);
this.motionY = 0.05D;
this.motionZ = (double)(-((float)Math.cos((double)f)) * 0.02F);
this.prevPosX = x;
this.prevPosY = y;
this.prevPosZ = z;
this.placedBye = entity;
}
protected void entityInit() {}
protected boolean canTriggerWalking()
{
return false;
}
public boolean canBeCollidedWith()
{
return !this.isDead;
}
public void onUpdate()
{
this.motionX = 0;
this.motionZ = 0;
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
this.moveEntity(this.motionX, this.motionY, this.motionZ);
if (this.motionY > 0)
{
this.motionY -= 0.0005D;
}
else
{
this.motionY = 0D;
}
this.worldObj.playSoundAtEntity(this, "note.pling", 1, 0.0F + (float)ticksExisted / 50);
this.worldObj.playSoundAtEntity(this, "note.bassattack", 1, 0.0F + (float)ticksExisted / 50);
for (int j = 0; j < 5; ++j)
{
worldObj.spawnParticle("flame", posX, posY, posZ, 0.0D, -0.5D, 0.0D);
}
if (this.ticksExisted > 100)
{
if (this.fuse++ >= 40)
{
this.setDead();
this.explode();
}
else
{
for (int i = 0; i < 360; ++i)
{
float f = 1.0F;
float f1 = 0.0F;
float f2 = i;
double d0 = prevPosX + (posX - prevPosX) * (double)f;
double d1 = prevPosY + (posY - prevPosY) * (double)f;
double d2 = prevPosZ + (posZ - prevPosZ) * (double)f;
Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2);
float f3 = MathHelper.cos(-f2 * 0.017453292F - (float)Math.PI);
float f4 = MathHelper.sin(-f2 * 0.017453292F - (float)Math.PI);
float f5 = -MathHelper.cos(-f1 * 0.017453292F);
float f6 = MathHelper.sin(-f1 * 0.017453292F);
float f7 = f4 * f5;
float f8 = f3 * f5;
double d3 = fuse;
Vec3 vec31 = vec3.addVector(f7 * d3, f6 * d3, f8 * d3);
double x = (int)vec31.xCoord;
int y = 256;
double z = (int)vec31.zCoord;
while (worldObj.getBlock((int)x, y, (int)z) == Blocks.air)
{
--y;
}
for (int j = 0; j < 5; ++j)
{
worldObj.spawnParticle("smoke", x + rand.nextFloat() - 0.5F / 2, y + 1.2F, z + rand.nextFloat() - 0.5F / 2, 0.0D, 0.0D, 0.0D);
worldObj.spawnParticle("flame", x + rand.nextFloat() - 0.5F / 2, y + 1.2F, z + rand.nextFloat() - 0.5F / 2, 0.0D, 0.0D, 0.0D);
if (worldObj.getBlock((int)x, y - j, (int)z) != TFBlocks.transformiumStone && !worldObj.isAirBlock((int)x, y - j, (int)z) && worldObj.getBlock((int)x, y - j, (int)z) != Blocks.bedrock)
{
worldObj.setBlock((int)x, y - j, (int)z, TFBlocks.transformiumStone);
}
List<Entity> list = getEntitiesNear(worldObj, x, y, z, 5.0F);
for (Entity entity : list)
{
if (!entity.getUniqueID().equals(getUniqueID()))
{
if (entity instanceof EntityLivingBase)
{
((EntityLivingBase)entity).attackEntityFrom(DamageSource.onFire, 99999999999999999999.0F);
((EntityLivingBase)entity).attackEntityFrom(DamageSource.generic, 99999999999999999999.0F);
}
}
}
}
}
}
}
}
public static List<Entity> getEntitiesNear(World world, double x, double y, double z, float radius)
{
List list = world.selectEntitiesWithinAABB(EntityLivingBase.class, AxisAlignedBB.getBoundingBox(x - radius, y - radius, z - radius, x + radius, y + radius, z + radius), IEntitySelector.selectAnything);
return list;
}
private void explode()
{
if (!this.worldObj.isRemote)
{
float f = 10.0F;
this.worldObj.createExplosion(this, this.posX, this.posY, this.posZ, f, true);
}
}
protected void writeEntityToNBT(NBTTagCompound nbt)
{
nbt.setByte("Fuse", (byte)this.fuse);
nbt.setByte("MaxFuse", (byte)this.maxFuse);
}
protected void readEntityFromNBT(NBTTagCompound nbt)
{
this.fuse = nbt.getByte("Fuse");
this.maxFuse = nbt.getByte("MaxFuse");
}
@SideOnly(Side.CLIENT)
public float getShadowSize()
{
return 0.0F;
}
public EntityLivingBase getSeedPlacedBy()
{
return this.placedBye;
}
}<file_sep>/src/Legacy/java/fiskfille/tf/main/misc/TickHandler.java
package fiskfille.tf.main.misc;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent.KeyInputEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent;
import fiskfille.tf.data.TFPlayerData;
import fiskfille.tf.main.MainClass;
import fiskfille.tf.main.TFHelper;
public class TickHandler
{
public static int time = 0;
public static boolean hasDisplayedEasterEggMessage = false;
@SubscribeEvent
public void onKeyInput(KeyInputEvent event)
{
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
if (ClientProxy.keyBindingTransform.getIsKeyPressed() && Minecraft.getMinecraft().currentScreen == null && (TFHelper.isPlayerSkystrike(player) || TFHelper.isPlayerPurge(player) || TFHelper.isPlayerVurp(player) || TFHelper.isPlayerSubwoofer(player)))
{
if (TFPlayerData.isInVehicleMode(player) && TFPlayerData.getTransformationTimer(player) == 0)
{
TFPlayerData.setInVehichleMode(player, false);
TFPlayerData.sync(player);
player.playSound(MainClass.modid + ":transform_robot", 1.0F, 1.0F);
}
else if (!TFPlayerData.isInVehicleMode(player) && TFPlayerData.getTransformationTimer(player) == 10)
{
TFPlayerData.setInVehichleMode(player, true);
TFPlayerData.sync(player);
player.playSound(MainClass.modid + ":transform_vehicle", 1.0F, 1.0F);
}
}
}
@SubscribeEvent
public void onPlayerTick(PlayerTickEvent event)
{
++time;
EntityPlayer player = event.player;
if (player.worldObj.isRemote && time % 2 == 0)
{
MainClass.proxy.tickHandler.onPlayerTick(player);
}
}
@SubscribeEvent
public void onClientTick(ClientTickEvent event)
{
switch (event.phase)
{
case START:
{
MainClass.proxy.tickHandler.onClientTickStart();
break;
}
case END:
{
MainClass.proxy.tickHandler.onClientTickEnd();
break;
}
}
}
}<file_sep>/src/Legacy/java/fiskfille/tf/item/ItemMiniVehicle.java
package fiskfille.tf.item;
import net.minecraft.client.renderer.texture.IIconRegister;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemMiniVehicle extends ItemMetaBasic implements IDisplayPillarItem
{
public ItemMiniVehicle(String... itemNames)
{
super(itemNames);
this.setMaxStackSize(1);
}
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister par1IconRegister)
{
}
}<file_sep>/src/main/java/fiskfille/tf/common/item/IDisplayPillarItem.java
package fiskfille.tf.common.item;
public interface IDisplayPillarItem
{
}<file_sep>/src/main/java/fiskfille/tf/common/playerdata/TFDataManager.java
package fiskfille.tf.common.playerdata;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.common.MinecraftForge;
import fiskfille.tf.common.achievement.TFAchievements;
import fiskfille.tf.common.event.PlayerTransformEvent;
import fiskfille.tf.common.packet.PacketHandleStealthTransformation;
import fiskfille.tf.common.packet.PacketHandleTransformation;
import fiskfille.tf.common.packet.PacketSyncStates;
import fiskfille.tf.common.packet.base.TFPacketManager;
import fiskfille.tf.common.transformer.base.Transformer;
import fiskfille.tf.helper.TFHelper;
public class TFDataManager
{
public static Map<UUID, Integer> transformationTimerClient = new HashMap<UUID, Integer>();
public static Map<UUID, Integer> stealthModeTimerClient = new HashMap<UUID, Integer>();
public static Map<UUID, Integer> zoomTimerClient = new HashMap<UUID, Integer>();
public static void setInVehicleMode(EntityPlayer player, boolean vehicleMode)
{
TFPlayerData data = TFPlayerData.getData(player);
if (vehicleMode != data.vehicle)
{
player.triggerAchievement(TFAchievements.transform);
if (!vehicleMode)
{
data.stealthForce = false;
}
if (player.worldObj.isRemote)
{
TFPacketManager.networkWrapper.sendToServer(new PacketHandleTransformation(player, vehicleMode));
}
else
{
TFPacketManager.networkWrapper.sendToAllAround(new PacketHandleTransformation(player, vehicleMode), new TargetPoint(player.dimension, player.posX, player.posY, player.posZ, 256));
}
data.vehicle = vehicleMode;
MinecraftForge.EVENT_BUS.post(new PlayerTransformEvent(player, vehicleMode, data.stealthForce));
}
}
public static void setInStealthMode(EntityPlayer player, boolean stealthMode)
{
if (stealthMode != TFPlayerData.getData(player).stealthForce)
{
if (isInVehicleMode(player))
{
if (player.worldObj.isRemote)
{
TFPacketManager.networkWrapper.sendToServer(new PacketHandleStealthTransformation(player, stealthMode));
}
else
{
TFPacketManager.networkWrapper.sendToAllAround(new PacketHandleStealthTransformation(player, stealthMode), new TargetPoint(player.dimension, player.posX, player.posY, player.posZ, 256));
}
TFPlayerData.getData(player).stealthForce = stealthMode;
}
}
}
public static void setTransformationTimer(EntityPlayer player, int timer)
{
transformationTimerClient.put(player.getUniqueID(), timer);
}
public static void setStealthModeTimer(EntityPlayer player, int timer)
{
stealthModeTimerClient.put(player.getUniqueID(), timer);
}
public static void setZoomTimer(EntityPlayer player, int timer)
{
zoomTimerClient.put(player.getUniqueID(), timer);
}
public static boolean isInVehicleMode(EntityPlayer player)
{
return TFPlayerData.getData(player).vehicle && TFHelper.isPlayerTransformer(player);
}
public static boolean isInStealthMode(EntityPlayer player)
{
Transformer transformer = TFHelper.getTransformer(player);
if (transformer != null)
{
return transformer.hasStealthForce(player) && isInVehicleMode(player) && TFPlayerData.getData(player).stealthForce;
}
return false;
}
public static int getTransformationTimer(EntityPlayer player)
{
Integer timer = transformationTimerClient.get(player.getUniqueID());
return timer != null ? timer : 0;
}
public static int getStealthModeTimer(EntityPlayer player)
{
Integer timer = stealthModeTimerClient.get(player.getUniqueID());
return timer != null ? timer : 0;
}
public static int getZoomTimer(EntityPlayer player)
{
Integer timer = zoomTimerClient.get(player.getUniqueID());
return timer != null ? timer : 0;
}
public static void toggleVehicleMode(EntityPlayer player)
{
setInVehicleMode(player, !TFPlayerData.getData(player).vehicle);
}
public static void toggleStealthMode(EntityPlayer player)
{
setInStealthMode(player, !TFPlayerData.getData(player).stealthForce);
}
public static void updateTransformationStatesFor(EntityPlayer player)
{
Map<UUID, Boolean[]> states = new HashMap<UUID, Boolean[]>();
for (Object obj : player.worldObj.playerEntities)
{
if (obj instanceof EntityPlayer)
{
EntityPlayer cPlayer = (EntityPlayer) obj;
TFPlayerData data = TFPlayerData.getData(cPlayer);
if (data != null)
{
states.put(cPlayer.getUniqueID(), new Boolean[]{data.vehicle, data.stealthForce});
}
}
}
TFPacketManager.networkWrapper.sendTo(new PacketSyncStates(states), (EntityPlayerMP) player);
}
}<file_sep>/src/Legacy/java/fiskfille/tf/model/vehicle/ModelPurgeVehicle.java
package fiskfille.tf.model.vehicle;
import net.minecraft.client.model.ModelRenderer;
import fiskfille.tf.model.ModelChildBase;
public class ModelPurgeVehicle extends ModelVehicleBase
{
ModelRenderer vehichleTread1;
ModelRenderer vehichleTread2;
ModelRenderer vehichleFoot1;
ModelRenderer vehichleFoot2;
ModelRenderer vehichleBody;
ModelRenderer vehichleChassy;
ModelRenderer vehichleTurret;
ModelRenderer vehichleGun;
ModelRenderer vehichleBack;
public ModelPurgeVehicle()
{
textureWidth = 66;
textureHeight = 128;
vehichleTread1 = new ModelRenderer(this, 0, 64);
vehichleTread1.addBox(-2F, -1.5F, -13F, 2, 3, 17);
vehichleTread1.setRotationPoint(-5F, 22.5F, 4.5F);
vehichleTread1.setTextureSize(66, 128);
vehichleTread1.mirror = true;
setRotation(vehichleTread1, 0F, 0F, 0F);
vehichleTread2 = new ModelRenderer(this, 0, 64);
vehichleTread2.addBox(0F, -1.5F, -13F, 2, 3, 17);
vehichleTread2.setRotationPoint(5F, 22.5F, 4.5F);
vehichleTread2.setTextureSize(66, 128);
vehichleTread2.mirror = true;
setRotation(vehichleTread2, 0F, 0F, 0F);
vehichleFoot1 = new ModelRenderer(this, 0, 64);
vehichleFoot1.addBox(-1.5F, -1F, -1F, 3, 4, 1);
vehichleFoot1.setRotationPoint(-5F, 21F, -8.7F);
vehichleFoot1.setTextureSize(66, 128);
vehichleFoot1.mirror = true;
setRotation(vehichleFoot1, 0.4014257F, 0F, 0F);
vehichleFoot2 = new ModelRenderer(this, 0, 64);
vehichleFoot2.mirror = true;
vehichleFoot2.addBox(-1.5F, -1F, -1F, 3, 4, 1);
vehichleFoot2.setRotationPoint(5F, 21F, -8.7F);
vehichleFoot2.setTextureSize(66, 128);
vehichleFoot2.mirror = true;
setRotation(vehichleFoot2, 0.4014257F, 0F, 0F);
vehichleFoot2.mirror = false;
vehichleBody = new ModelRenderer(this, 0, 106);
vehichleBody.addBox(-6F, -3F, -7.5F, 12, 3, 16);
vehichleBody.setRotationPoint(0F, 23F, -0.5F);
vehichleBody.setTextureSize(66, 128);
vehichleBody.mirror = true;
setRotation(vehichleBody, 0F, 0F, 0F);
vehichleChassy = new ModelRenderer(this, 0, 84);
vehichleChassy.addBox(-6.5F, -2F, -10F, 13, 2, 20);
vehichleChassy.setRotationPoint(0F, 20.5F, 0F);
vehichleChassy.setTextureSize(66, 128);
vehichleChassy.mirror = true;
setRotation(vehichleChassy, 0F, 0F, 0F);
vehichleTurret = new ModelRenderer(this, 21, 64);
vehichleTurret.addBox(-3F, -3F, -3F, 6, 4, 7);
vehichleTurret.setRotationPoint(0F, 18F, -0.5F);
vehichleTurret.setTextureSize(66, 128);
vehichleTurret.mirror = true;
setRotation(vehichleTurret, 0F, 0F, 0F);
vehichleGun = new ModelRenderer(this, 38, 69);
vehichleGun.addBox(-1F, -1F, -11F, 2, 2, 11);
vehichleGun.setRotationPoint(0F, 17F, -3.5F);
vehichleGun.setTextureSize(66, 128);
vehichleGun.mirror = true;
setRotation(vehichleGun, 0F, 0F, 0F);
vehichleBack = new ModelRenderer(this, 21, 75);
vehichleBack.addBox(-6.5F, -1F, 0F, 13, 4, 1);
vehichleBack.setRotationPoint(0F, 21F, 8.7F);
vehichleBack.setTextureSize(66, 128);
vehichleBack.mirror = true;
setRotation(vehichleBack, -0.4014257F, 0F, 0F);
this.addChildTo(vehichleGun, vehichleTurret);
this.addChildTo(vehichleTurret, vehichleBody);
this.addChildTo(vehichleBack, vehichleBody);
this.addChildTo(vehichleChassy, vehichleBody);
this.addChildTo(vehichleFoot1, vehichleBody);
this.addChildTo(vehichleFoot2, vehichleBody);
this.addChildTo(vehichleTread1, vehichleBody);
this.addChildTo(vehichleTread2, vehichleBody);
}
public void render()
{
vehichleBody.render(0.0625F);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
}<file_sep>/src/Legacy/java/fiskfille/tf/gui/GuiTFModConfig.java
package fiskfille.tf.gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import cpw.mods.fml.client.config.GuiConfig;
import fiskfille.tf.main.MainClass;
public class GuiTFModConfig extends GuiConfig
{
public GuiTFModConfig(GuiScreen parent)
{
super(
parent,
new ConfigElement(MainClass.configFile.getCategory("Options")).getChildElements(),
MainClass.modid,
false,
false,
GuiConfig.getAbridgedConfigPath(MainClass.configFile.toString()));
}
}<file_sep>/src/main/java/fiskfille/tf/common/transformer/base/TransformerJet.java
package fiskfille.tf.common.transformer.base;
import java.util.Random;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.util.Vec3;
import fiskfille.tf.client.keybinds.TFKeyBinds;
import fiskfille.tf.client.particle.NitroParticleHandler;
import fiskfille.tf.common.entity.EntityMissile;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.motion.TFMotionManager;
import fiskfille.tf.common.motion.VehicleMotion;
import fiskfille.tf.common.packet.PacketVehicleNitro;
import fiskfille.tf.common.packet.base.TFPacketManager;
import fiskfille.tf.common.playerdata.TFDataManager;
import fiskfille.tf.common.proxy.ClientProxy;
import fiskfille.tf.config.TFConfig;
import fiskfille.tf.helper.TFModelHelper;
public abstract class TransformerJet extends Transformer
{
public TransformerJet(String name)
{
super(name);
}
@Override
public float fall(EntityPlayer player, float distance)
{
return 0;
}
@Override
public float getCameraYOffset(EntityPlayer player)
{
return 0;
}
@Override
public float getVehicleCameraYOffset(EntityPlayer player)
{
return 0;
}
@Override
public float getThirdPersonDistance(EntityPlayer player)
{
return 4.0F;
}
@Override
public void updateMovement(EntityPlayer player)
{
Minecraft minecraft = Minecraft.getMinecraft();
boolean moveForward = minecraft.gameSettings.keyBindForward.getIsKeyPressed();
boolean nitroPressed = TFKeyBinds.keyBindingNitro.getIsKeyPressed() || minecraft.gameSettings.keyBindSprint.getIsKeyPressed();
VehicleMotion motion = TFMotionManager.getTransformerPlayer(player);
int nitro = 0;
double vel = 0;
if (motion != null)
{
nitro = motion.getNitro();
vel = motion.getForwardVelocity();
boolean prevNitro = TFMotionManager.prevNitro;
double increment = ((nitroPressed && nitro > 0 ? 6.84D : 1.36D) - vel) / 10 + 0.001D;
if (moveForward && vel <= 1.41D)
{
vel += increment;
}
if (vel > 0.14D && !moveForward)
{
vel -= 0.14D;
}
if (vel <= 0.14D)
{
vel = 0.14D;
}
if ((player.worldObj.getBlock((int)player.posX, (int)player.posY - 1, (int)player.posZ) != Blocks.air || player.worldObj.getBlock((int)player.posX, (int)player.posY - 2, (int)player.posZ) != Blocks.air || player.worldObj.getBlock((int)player.posX, (int)player.posY - 3, (int)player.posZ) != Blocks.air))
{
player.setPosition(player.posX, player.posY + 0.8, player.posZ);
}
Vec3 vec3 = TFMotionManager.getFrontCoords(player, vel, true);
player.motionX = (vec3.xCoord - player.posX);
player.motionY = (vec3.yCoord - player.posY) + getMotionYOffset();
player.motionZ = (vec3.zCoord - player.posZ);
if (vel <= 0.09F) {vel = 0.09F;}
if (vel > 1.41F) {vel = 1.41F;}
if (player == Minecraft.getMinecraft().thePlayer)
{
if (nitro > 0 && nitroPressed && moveForward)
{
if (!player.capabilities.isCreativeMode) --nitro;
if (!prevNitro)
{
TFPacketManager.networkWrapper.sendToServer(new PacketVehicleNitro(player, true));
TFMotionManager.prevNitro = true;
}
for (int i = 0; i < 4; ++i)
{
Vec3 side = TFMotionManager.getBackSideCoords(player, 0.15F, i < 2, -1.5, true);
Random rand = new Random();
player.worldObj.spawnParticle("flame", side.xCoord, side.yCoord - 0.2F, side.zCoord, rand.nextFloat() / 20, -0.2F + rand.nextFloat() / 20, rand.nextFloat() / 20);
}
}
else
{
if (prevNitro)
{
TFPacketManager.networkWrapper.sendToServer(new PacketVehicleNitro(player, false));
TFMotionManager.prevNitro = false;
}
}
try
{
if (TFConfig.rollWithJet)
{
EntityRenderer entityRenderer = Minecraft.getMinecraft().entityRenderer;
ModelBiped modelBipedMain = TFModelHelper.modelBipedMain;
float yaw = (modelBipedMain.bipedHead.rotateAngleY - modelBipedMain.bipedBody.rotateAngleY) * 100;
ClientProxy.camRollField.set(entityRenderer, yaw);
}
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
motion.setNitro(nitro);
motion.setForwardVelocity(vel);
}
}
@Override
public boolean canShoot(EntityPlayer player)
{
return true;
}
@Override
public Item getShootItem()
{
return TFItems.missile;
}
@Override
public Entity getShootEntity(EntityPlayer player)
{
return new EntityMissile(player.worldObj, player, 3, TFConfig.allowMissileExplosions, TFDataManager.isInStealthMode(player));
}
@Override
public void doNitroParticles(EntityPlayer player)
{
for (int i = 0; i < 4; ++i)
{
Vec3 side = NitroParticleHandler.getBackSideCoords(player, 0.15F, i < 2, -1, true);
Random rand = new Random();
player.worldObj.spawnParticle("flame", side.xCoord, side.yCoord + 1.5F, side.zCoord, rand.nextFloat() / 20, -0.2F + rand.nextFloat() / 20, rand.nextFloat() / 20);
}
}
public float getMotionYOffset()
{
return -0.1f;
}
}
<file_sep>/src/main/java/fiskfille/tf/common/transformer/TransformerSkystrike.java
package fiskfille.tf.common.transformer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import fiskfille.tf.client.model.transformer.ModelChildBase.Biped;
import fiskfille.tf.client.model.transformer.TFModelRegistry;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.playerdata.TFDataManager;
import fiskfille.tf.common.transformer.base.TransformerJet;
public class TransformerSkystrike extends TransformerJet
{
public TransformerSkystrike()
{
super("Skystrike");
}
@Override
public Item getHelmet()
{
return TFItems.skystrikeHelmet;
}
@Override
public Item getChestplate()
{
return TFItems.skystrikeChestplate;
}
@Override
public Item getLeggings()
{
return TFItems.skystrikeLeggings;
}
@Override
public Item getBoots()
{
return TFItems.skystrikeBoots;
}
@Override
public void onJump(EntityPlayer player)
{
player.motionY += 0.205D;
}
@Override
public void robotTick(EntityPlayer player)
{
if (!player.capabilities.isFlying && !(TFDataManager.getTransformationTimer(player) < 10))
{
if (player.motionY < 0.0D)
{
player.motionY *= 0.85F;
}
else
{
player.motionY += 0.02D;
}
}
}
}<file_sep>/src/main/java/fiskfille/tf/client/render/item/RenderItemVurpsSniper.java
package fiskfille.tf.client.render.item;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.IItemRenderer;
import org.lwjgl.opengl.GL11;
import fiskfille.tf.TransformersMod;
import fiskfille.tf.client.model.item.ModelVurpsSniper;
import fiskfille.tf.common.playerdata.TFDataManager;
public class RenderItemVurpsSniper implements IItemRenderer
{
private ModelVurpsSniper model = new ModelVurpsSniper();
public boolean handleRenderType(ItemStack item, ItemRenderType type)
{
return type == type.EQUIPPED || type == type.EQUIPPED_FIRST_PERSON;
}
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper)
{
return false;
}
public void renderItem(ItemRenderType type, ItemStack item, Object... data)
{
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(TransformersMod.modid, "textures/models/weapons/sniper.png"));
if (type == ItemRenderType.EQUIPPED_FIRST_PERSON)
{
GL11.glPushMatrix();
if ((Entity)data[1] instanceof EntityPlayer)
{
int i = TFDataManager.getZoomTimer((EntityPlayer)data[1]);
if (i == 7)
{
GL11.glTranslatef(0.1F, 0.45F, -1.0F);
GL11.glRotatef(0, 1, 0, 0);
GL11.glRotatef(210, 0, 0, 1);
GL11.glRotatef(95, 0, 1, 0);
}
else if (i == 6)
{
GL11.glTranslatef(0.6F, 0.7F, -0.95F);
GL11.glRotatef(0, 1, 0, 0);
GL11.glRotatef(210, 0, 0, 1);
GL11.glRotatef(95, 0, 1, 0);
}
else if (i == 5)
{
GL11.glTranslatef(1.0F, 0.9F, -0.9F);
GL11.glRotatef(0, 1, 0, 0);
GL11.glRotatef(210, 0, 0, 1);
GL11.glRotatef(95, 0, 1, 0);
}
else if (i == 4)
{
GL11.glTranslatef(1.1F, 0.9F, -0.6F);
GL11.glRotatef(0, 1, 0, 0);
GL11.glRotatef(200, 0, 0, 1);
GL11.glRotatef(105, 0, 1, 0);
}
else if (i == 3)
{
GL11.glTranslatef(1.2F, 0.8F, -0.45F);
GL11.glRotatef(-5, 1, 0, 0);
GL11.glRotatef(200, 0, 0, 1);
GL11.glRotatef(105, 0, 1, 0);
}
else if (i == 2)
{
GL11.glTranslatef(1.2F, 0.7F, -0.3F);
GL11.glRotatef(-10, 1, 0, 0);
GL11.glRotatef(200, 0, 0, 1);
GL11.glRotatef(100, 0, 1, 0);
}
else if (i == 1)
{
GL11.glTranslatef(1.2F, 0.6F, -0.15F);
GL11.glRotatef(-10, 1, 0, 0);
GL11.glRotatef(200, 0, 0, 1);
GL11.glRotatef(95, 0, 1, 0);
}
else if (i == 0)
{
GL11.glTranslatef(1.2F, 0.6F, 0);
GL11.glRotatef(-10, 1, 0, 0);
GL11.glRotatef(200, 0, 0, 1);
GL11.glRotatef(90, 0, 1, 0);
// GL11.glTranslatef(0.6F, 0.7F, -0.95F);
// GL11.glRotatef(0, 1, 0, 0);
// GL11.glRotatef(210, 0, 0, 1);
// GL11.glRotatef(95, 0, 1, 0);
}
float f = 2.0F;
GL11.glScalef(f, f, f);
model.render();
}
GL11.glPopMatrix();
}
else if (type == ItemRenderType.EQUIPPED)
{
GL11.glPushMatrix();
GL11.glTranslatef(0.83F, 0.5F, 0F);
GL11.glRotatef(-135, 0, 0, 1);
GL11.glRotatef(0, 0, 0, 1);
GL11.glRotatef(75, 0, 1, 0);
float f = 0.9F;
GL11.glScalef(f, f, f);
model.render();
GL11.glPopMatrix();
}
}
}<file_sep>/src/main/java/fiskfille/tf/client/model/transformer/CopyOfModelVurp.java
package fiskfille.tf.client.model.transformer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import fiskfille.tf.client.model.tools.MowzieModelRenderer;
import fiskfille.tf.common.playerdata.TFDataManager;
import fiskfille.tf.helper.ModelOffset;
import fiskfille.tf.helper.TFModelHelper;
public class CopyOfModelVurp extends ModelChildBase.Biped
{
MowzieModelRenderer leg1;
MowzieModelRenderer foot1;
MowzieModelRenderer backWheel1;
MowzieModelRenderer upperLegPanel1;
MowzieModelRenderer lowerLegPanel1;
MowzieModelRenderer leg2;
MowzieModelRenderer foot2;
MowzieModelRenderer backWheel2;
MowzieModelRenderer upperLegPanel2;
MowzieModelRenderer lowerLegPanel2;
MowzieModelRenderer hipSlab1;
MowzieModelRenderer hipSlab2;
MowzieModelRenderer windShield;
MowzieModelRenderer chest;
MowzieModelRenderer frontCar1;
MowzieModelRenderer frontCar2;
MowzieModelRenderer torso;
MowzieModelRenderer waist;
MowzieModelRenderer chestPanel1;
MowzieModelRenderer chestPanel2;
MowzieModelRenderer chestPanel3;
public MowzieModelRenderer upperArm1;
MowzieModelRenderer frontWheel1;
public MowzieModelRenderer lowerArm1;
MowzieModelRenderer armPanel1;
MowzieModelRenderer upperArm2;
MowzieModelRenderer lowerArm2;
MowzieModelRenderer armPanel2;
MowzieModelRenderer frontWheel2;
MowzieModelRenderer head;
MowzieModelRenderer ear1;
MowzieModelRenderer ear2;
MowzieModelRenderer mask;
MowzieModelRenderer vehicleFrontWheel1;
MowzieModelRenderer vehicleFrontWheel2;
MowzieModelRenderer vehicleBackWheel1;
MowzieModelRenderer vehicleBackWheel2;
MowzieModelRenderer vehicleBumper1;
MowzieModelRenderer vehicleBumper2;
MowzieModelRenderer vehicleRoof;
MowzieModelRenderer vehicleBody;
MowzieModelRenderer vehicleHood;
MowzieModelRenderer vehicleBackWindShield;
MowzieModelRenderer vehicleWindShield;
MowzieModelRenderer vehicleSpoiler;
MowzieModelRenderer vehicleDoor1;
MowzieModelRenderer vehicleDoor2;
public MowzieModelRenderer stealthForceBase;
public MowzieModelRenderer stealthForceBackWheelCover1;
public MowzieModelRenderer stealthForceBackWheelCover2;
public MowzieModelRenderer stealthForceBackWindShield;
public MowzieModelRenderer stealthForceRoof;
public MowzieModelRenderer stealthForceBumper1;
public MowzieModelRenderer stealthForceBumper2;
public MowzieModelRenderer stealthForceWindShield;
public MowzieModelRenderer stealthForceSpoiler;
public MowzieModelRenderer stealthForceDoor1;
public MowzieModelRenderer stealthForceDoor2;
public MowzieModelRenderer stealthForceFrontWheelCover1;
public MowzieModelRenderer stealthForceFrontWheelCover2;
public MowzieModelRenderer stealthForceFrontGun;
public MowzieModelRenderer stealthForceHood;
public MowzieModelRenderer stealthForceGun1;
public MowzieModelRenderer stealthForceGun2;
public MowzieModelRenderer stealthForceBackWheel1;
public MowzieModelRenderer stealthForceBackWheel2;
public MowzieModelRenderer stealthForceFrontWheel1;
public MowzieModelRenderer stealthForceFrontWheel2;
public MowzieModelRenderer stealthForceHoodGun2;
public MowzieModelRenderer stealthForceHoodGun1;
public CopyOfModelVurp()
{
textureWidth = 64;
textureHeight = 128;
bipedBody = new MowzieModelRenderer(this, 1000, 1000);
bipedHead = new MowzieModelRenderer(this, 1000, 1000);
bipedHeadwear = new MowzieModelRenderer(this, 1000, 1000);
bipedRightLeg = new MowzieModelRenderer(this, 1000, 1000);
bipedLeftLeg = new MowzieModelRenderer(this, 1000, 1000);
bipedRightArm = new MowzieModelRenderer(this, 1000, 1000);
bipedLeftArm = new MowzieModelRenderer(this, 1000, 1000);
leg1 = new MowzieModelRenderer(this, 0, 16);
leg1.addBox(-1F, -12F, -1.5F, 2, 12, 3);
leg1.setRotationPoint(-2.5F, 24F, 0F);
leg1.setTextureSize(64, 128);
leg1.mirror = true;
setRotation(leg1, 0F, 0F, 0.0523599F);
foot1 = new MowzieModelRenderer(this, 2, 33);
foot1.addBox(-1.5F, -0.5F, -5F, 3, 1, 6);
foot1.setRotationPoint(-2.5F, 22.5F, 1F);
foot1.setTextureSize(64, 128);
foot1.mirror = true;
setRotation(foot1, 0.2443461F, 0F, 0F);
backWheel1 = new MowzieModelRenderer(this, 0, 40);
backWheel1.addBox(-1F, -1F, -1F, 1, 2, 2);
backWheel1.setRotationPoint(-3.5F, 22.5F, 0F);
backWheel1.setTextureSize(64, 128);
backWheel1.mirror = true;
setRotation(backWheel1, 0F, 0F, 0F);
upperLegPanel1 = new MowzieModelRenderer(this, 0, 31);
upperLegPanel1.addBox(-1.5F, -3F, -1F, 3, 4, 1);
upperLegPanel1.setRotationPoint(-2.1F, 15F, -1.2F);
upperLegPanel1.setTextureSize(64, 128);
upperLegPanel1.mirror = true;
setRotation(upperLegPanel1, 0F, 0.1919862F, 0.0523599F);
lowerLegPanel1 = new MowzieModelRenderer(this, 10, 16);
lowerLegPanel1.addBox(-1.5F, -5F, -1F, 3, 6, 1);
lowerLegPanel1.setRotationPoint(-2.5F, 21F, -1F);
lowerLegPanel1.setTextureSize(64, 128);
lowerLegPanel1.mirror = true;
setRotation(lowerLegPanel1, 0.2443461F, 0.0872665F, 0.0523599F);
leg2 = new MowzieModelRenderer(this, 0, 16);
leg2.addBox(-1F, -12F, -1.5F, 2, 12, 3);
leg2.setRotationPoint(2.5F, 24F, 0F);
leg2.setTextureSize(64, 128);
leg2.mirror = true;
setRotation(leg2, 0F, 0F, -0.0523599F);
foot2 = new MowzieModelRenderer(this, 2, 33);
foot2.addBox(-1.5F, -0.5F, -5F, 3, 1, 6);
foot2.setRotationPoint(2.5F, 22.5F, 1F);
foot2.setTextureSize(64, 128);
foot2.mirror = true;
setRotation(foot2, 0.2443461F, 0F, 0F);
backWheel2 = new MowzieModelRenderer(this, 0, 40);
backWheel2.addBox(0F, -1F, -1F, 1, 2, 2);
backWheel2.setRotationPoint(3.5F, 22.5F, 0F);
backWheel2.setTextureSize(64, 128);
backWheel2.mirror = true;
setRotation(backWheel2, 0F, 0F, 0F);
upperLegPanel2 = new MowzieModelRenderer(this, 0, 31);
upperLegPanel2.addBox(-1.5F, -3F, -1F, 3, 4, 1);
upperLegPanel2.setRotationPoint(2.1F, 15F, -1.2F);
upperLegPanel2.setTextureSize(64, 128);
upperLegPanel2.mirror = true;
setRotation(upperLegPanel2, 0F, -0.1919862F, -0.0523599F);
lowerLegPanel2 = new MowzieModelRenderer(this, 10, 16);
lowerLegPanel2.addBox(-1.5F, -5F, -1F, 3, 6, 1);
lowerLegPanel2.setRotationPoint(2.5F, 21F, -1F);
lowerLegPanel2.setTextureSize(64, 128);
lowerLegPanel2.mirror = true;
setRotation(lowerLegPanel2, 0.2443461F, -0.0872665F, -0.0523599F);
hipSlab1 = new MowzieModelRenderer(this, 18, 16);
hipSlab1.addBox(-0.5F, -4F, -2F, 1, 4, 4);
hipSlab1.setRotationPoint(0F, 12.7F, 0F);
hipSlab1.setTextureSize(64, 128);
hipSlab1.mirror = true;
setRotation(hipSlab1, 0F, 0F, -0.7853982F);
hipSlab2 = new MowzieModelRenderer(this, 18, 16);
hipSlab2.addBox(-0.5F, -4F, -2F, 1, 4, 4);
hipSlab2.setRotationPoint(0F, 12.7F, 0F);
hipSlab2.setTextureSize(64, 128);
hipSlab2.mirror = true;
setRotation(hipSlab2, 0F, 0F, 0.7853982F);
windShield = new MowzieModelRenderer(this, 36, 33);
windShield.addBox(-2.5F, 0F, 0F, 5, 3, 1);
windShield.setRotationPoint(0F, 0F, 2F);
windShield.setTextureSize(64, 128);
windShield.mirror = true;
setRotation(windShield, 0F, 0F, 0F);
chest = new MowzieModelRenderer(this, 18, 24);
chest.addBox(-4F, -5F, -2F, 8, 5, 4);
chest.setRotationPoint(0F, 5F, 0F);
chest.setTextureSize(64, 128);
chest.mirror = true;
setRotation(chest, 0F, 0F, 0F);
frontCar1 = new MowzieModelRenderer(this, 28, 18);
frontCar1.addBox(-3F, -2F, -3F, 3, 2, 2);
frontCar1.setRotationPoint(-0.5F, 2.5F, 0F);
frontCar1.setTextureSize(64, 128);
frontCar1.mirror = true;
setRotation(frontCar1, 0F, 0.2443461F, 0.0872665F);
frontCar2 = new MowzieModelRenderer(this, 28, 18);
frontCar2.mirror = true;
frontCar2.addBox(0F, -2F, -3F, 3, 2, 2);
frontCar2.setRotationPoint(0.5F, 2.5F, 0F);
frontCar2.setTextureSize(64, 128);
setRotation(frontCar2, 0F, -0.2443461F, -0.0872665F);
frontCar2.mirror = true;
torso = new MowzieModelRenderer(this, 28, 10);
torso.addBox(-2.5F, -5F, -1.5F, 5, 5, 3);
torso.setRotationPoint(0F, 9F, 0F);
torso.setTextureSize(64, 128);
torso.mirror = true;
setRotation(torso, 0F, 0F, 0F);
waist = new MowzieModelRenderer(this, 18, 33);
waist.addBox(-3F, -3F, -1.5F, 6, 3, 3);
waist.setRotationPoint(0F, 12F, 0F);
waist.setTextureSize(64, 128);
waist.mirror = true;
setRotation(waist, 0F, 0F, 0F);
chestPanel1 = new MowzieModelRenderer(this, 10, 23);
chestPanel1.addBox(-1F, -4F, -1.5F, 2, 4, 1);
chestPanel1.setRotationPoint(-1F, 7.5F, -0.5F);
chestPanel1.setTextureSize(64, 128);
chestPanel1.mirror = true;
setRotation(chestPanel1, 0.2443461F, 0.1396263F, -0.3141593F);
chestPanel2 = new MowzieModelRenderer(this, 10, 23);
chestPanel2.addBox(-1F, -4F, -1.5F, 2, 4, 1);
chestPanel2.setRotationPoint(1F, 7.5F, -0.5F);
chestPanel2.setTextureSize(64, 128);
chestPanel2.mirror = true;
setRotation(chestPanel2, 0.2443461F, -0.1396263F, 0.3141593F);
chestPanel3 = new MowzieModelRenderer(this, 20, 10);
chestPanel3.addBox(-1F, -1.5F, -2F, 2, 4, 2);
chestPanel3.setRotationPoint(0F, 2.1F, -0.9F);
chestPanel3.setTextureSize(64, 128);
chestPanel3.mirror = true;
setRotation(chestPanel3, 0.1047198F, 0F, 0F);
upperArm1 = new MowzieModelRenderer(this, 52, 11);
upperArm1.addBox(-2.5F, -1F, -1.5F, 3, 5, 3);
upperArm1.setRotationPoint(-4F, 2F, 0F);
upperArm1.setTextureSize(64, 128);
upperArm1.mirror = true;
setRotation(upperArm1, 0.0872665F, 0F, 0.1745329F);
frontWheel1 = new MowzieModelRenderer(this, 0, 40);
frontWheel1.addBox(-1F, -1F, -1F, 1, 2, 2);
frontWheel1.setRotationPoint(-4F, 0.5F, 0F);
frontWheel1.setTextureSize(64, 128);
frontWheel1.mirror = true;
setRotation(frontWheel1, 0.0872665F, 0F, 0.8901179F);
lowerArm1 = new MowzieModelRenderer(this, 42, 18);
lowerArm1.addBox(-1F, -4F, -1F, 2, 11, 2);
lowerArm1.setRotationPoint(-5.7F, 5F, 0.5F);
lowerArm1.setTextureSize(64, 128);
lowerArm1.mirror = true;
setRotation(lowerArm1, -0.2443461F, 0F, 0.1396263F);
armPanel1 = new MowzieModelRenderer(this, 44, 11);
armPanel1.addBox(-1F, -2F, -1.5F, 1, 4, 3);
armPanel1.setRotationPoint(-7F, 8.5F, -0.3F);
armPanel1.setTextureSize(64, 128);
armPanel1.mirror = true;
setRotation(armPanel1, -0.2617994F, 0F, 0.0872665F);
upperArm2 = new MowzieModelRenderer(this, 52, 11);
upperArm2.addBox(-0.5F, -1F, -1.5F, 3, 5, 3);
upperArm2.setRotationPoint(4F, 2F, 0F);
upperArm2.setTextureSize(64, 128);
upperArm2.mirror = true;
setRotation(upperArm2, 0.0872665F, 0F, -0.1745329F);
lowerArm2 = new MowzieModelRenderer(this, 42, 18);
lowerArm2.addBox(-1F, -4F, -1F, 2, 11, 2);
lowerArm2.setRotationPoint(5.7F, 5F, 0.5F);
lowerArm2.setTextureSize(64, 128);
lowerArm2.mirror = true;
setRotation(lowerArm2, -0.2443461F, 0F, -0.1396263F);
armPanel2 = new MowzieModelRenderer(this, 44, 11);
armPanel2.addBox(0F, -2F, -1.5F, 1, 4, 3);
armPanel2.setRotationPoint(7F, 8.5F, -0.3F);
armPanel2.setTextureSize(64, 128);
armPanel2.mirror = true;
setRotation(armPanel2, -0.2617994F, 0F, -0.0872665F);
frontWheel2 = new MowzieModelRenderer(this, 0, 40);
frontWheel2.addBox(0F, -1F, -1F, 1, 2, 2);
frontWheel2.setRotationPoint(4F, 0.5F, 0F);
frontWheel2.setTextureSize(64, 128);
frontWheel2.mirror = true;
setRotation(frontWheel2, 0.0872665F, 0F, -0.8901179F);
head = new MowzieModelRenderer(this, 0, 0);
head.addBox(-2F, -4F, -1.5F, 4, 4, 3);
head.setRotationPoint(0F, 0F, 0F);
head.setTextureSize(64, 128);
head.mirror = true;
setRotation(head, 0F, 0F, 0F);
ear1 = new MowzieModelRenderer(this, 8, 7);
ear1.addBox(-1F, -3F, -1F, 1, 4, 2);
ear1.setRotationPoint(-1.2F, -1F, -1F);
ear1.setTextureSize(64, 128);
ear1.mirror = true;
setRotation(ear1, -0.418879F, -0.1745329F, 0F);
ear2 = new MowzieModelRenderer(this, 8, 7);
ear2.addBox(0F, -3F, -1F, 1, 4, 2);
ear2.setRotationPoint(1.2F, -1F, -1F);
ear2.setTextureSize(64, 128);
ear2.mirror = true;
setRotation(ear2, -0.418879F, 0.1745329F, 0F);
mask = new MowzieModelRenderer(this, 0, 7);
mask.addBox(-1.5F, -2F, -1F, 3, 4, 1);
mask.setRotationPoint(0F, -2F, -1.5F);
mask.setTextureSize(64, 128);
mask.mirror = true;
setRotation(mask, -0.1745329F, 0F, 0F);
this.addChildTo(waist, bipedBody);
this.addChildTo(hipSlab1, waist);
this.addChildTo(hipSlab2, waist);
this.addChildTo(torso, waist);
this.addChildTo(chestPanel1, torso);
this.addChildTo(chestPanel2, torso);
this.addChildTo(chest, torso);
this.addChildTo(chestPanel3, chest);
this.addChildTo(frontCar1, chest);
this.addChildTo(frontCar2, chest);
this.addChildTo(windShield, chest);
this.addChildTo(frontWheel1, chest);
this.addChildTo(frontWheel2, chest);
this.addChildTo(head, bipedHead);
this.addChildTo(mask, head);
this.addChildTo(ear1, mask);
this.addChildTo(ear2, mask);
this.addChildTo(upperArm1, bipedRightArm);
this.addChildTo(lowerArm1, upperArm1);
this.addChildTo(armPanel1, lowerArm1);
this.addChildTo(upperArm2, bipedLeftArm);
this.addChildTo(lowerArm2, upperArm2);
this.addChildTo(armPanel2, lowerArm2);
this.addChildTo(leg1, bipedRightLeg);
this.addChildTo(upperLegPanel1, leg1);
this.addChildTo(lowerLegPanel1, leg1);
this.addChildTo(foot1, leg1);
this.addChildTo(backWheel1, leg1);
this.addChildTo(leg2, bipedLeftLeg);
this.addChildTo(upperLegPanel2, leg2);
this.addChildTo(lowerLegPanel2, leg2);
this.addChildTo(foot2, leg2);
this.addChildTo(backWheel2, leg2);
vehicleFrontWheel1 = new MowzieModelRenderer(this, 0, 64);
vehicleFrontWheel1.addBox(-1F, -1F, -1F, 1, 2, 2);
vehicleFrontWheel1.setRotationPoint(-2.3F, 23F, -4.5F);
vehicleFrontWheel1.setTextureSize(64, 128);
vehicleFrontWheel1.mirror = true;
setRotation(vehicleFrontWheel1, 0F, 0F, 0F);
vehicleFrontWheel2 = new MowzieModelRenderer(this, 0, 64);
vehicleFrontWheel2.addBox(0F, -1F, -1F, 1, 2, 2);
vehicleFrontWheel2.setRotationPoint(2.3F, 23F, -4.5F);
vehicleFrontWheel2.setTextureSize(64, 128);
vehicleFrontWheel2.mirror = true;
setRotation(vehicleFrontWheel2, 0F, 0F, 0F);
vehicleBackWheel1 = new MowzieModelRenderer(this, 0, 64);
vehicleBackWheel1.addBox(-1F, -1F, -1F, 1, 2, 2);
vehicleBackWheel1.setRotationPoint(-2.3F, 23F, 4F);
vehicleBackWheel1.setTextureSize(64, 128);
vehicleBackWheel1.mirror = true;
setRotation(vehicleBackWheel1, 0F, 0F, 0F);
vehicleBackWheel2 = new MowzieModelRenderer(this, 0, 64);
vehicleBackWheel2.addBox(0F, -1F, -1F, 1, 2, 2);
vehicleBackWheel2.setRotationPoint(2.3F, 23F, 4F);
vehicleBackWheel2.setTextureSize(64, 128);
vehicleBackWheel2.mirror = true;
setRotation(vehicleBackWheel2, 0F, 0F, 0F);
vehicleBumper1 = new MowzieModelRenderer(this, 0, 68);
vehicleBumper1.addBox(-2.5F, -1.5F, -2F, 3, 2, 2);
vehicleBumper1.setRotationPoint(0F, 23F, -5F);
vehicleBumper1.setTextureSize(64, 128);
vehicleBumper1.mirror = true;
setRotation(vehicleBumper1, 0F, 0.2443461F, 0F);
vehicleBumper2 = new MowzieModelRenderer(this, 0, 68);
vehicleBumper2.mirror = true;
vehicleBumper2.addBox(-0.5F, -1.5F, -2F, 3, 2, 2);
vehicleBumper2.setRotationPoint(0F, 23F, -5F);
vehicleBumper2.setTextureSize(64, 128);
setRotation(vehicleBumper2, 0F, -0.2443461F, 0F);
vehicleBumper2.mirror = true;
vehicleRoof = new MowzieModelRenderer(this, 0, 78);
vehicleRoof.addBox(-2.5F, -0.5F, 0F, 5, 1, 2);
vehicleRoof.setRotationPoint(0F, 20.7F, -0.5F);
vehicleRoof.setTextureSize(64, 128);
vehicleRoof.mirror = true;
setRotation(vehicleRoof, 0F, 0F, 0F);
vehicleBody = new MowzieModelRenderer(this, 0, 64);
vehicleBody.addBox(-3F, -1F, 0F, 6, 2, 12);
vehicleBody.setRotationPoint(0F, 22.5F, -6.2F);
vehicleBody.setTextureSize(64, 128);
vehicleBody.mirror = true;
setRotation(vehicleBody, 0F, 0F, 0F);
vehicleHood = new MowzieModelRenderer(this, 0, 81);
vehicleHood.addBox(-2F, -1F, -2F, 4, 1, 3);
vehicleHood.setRotationPoint(0F, 22.3F, -3.7F);
vehicleHood.setTextureSize(64, 128);
vehicleHood.mirror = true;
setRotation(vehicleHood, 0F, 0F, 0F);
vehicleBackWindShield = new MowzieModelRenderer(this, 14, 78);
vehicleBackWindShield.addBox(-2.5F, -0.5F, 0F, 5, 1, 3);
vehicleBackWindShield.setRotationPoint(0F, 20.7F, 1.3F);
vehicleBackWindShield.setTextureSize(64, 128);
vehicleBackWindShield.mirror = true;
setRotation(vehicleBackWindShield, -0.3839724F, 0F, 0F);
vehicleWindShield = new MowzieModelRenderer(this, 14, 82);
vehicleWindShield.addBox(-2.5F, -1F, 0F, 5, 1, 3);
vehicleWindShield.setRotationPoint(0F, 22.4F, -2.7F);
vehicleWindShield.setTextureSize(64, 128);
vehicleWindShield.mirror = true;
setRotation(vehicleWindShield, 0.4537856F, 0F, 0F);
vehicleSpoiler = new MowzieModelRenderer(this, 24, 64);
vehicleSpoiler.addBox(-2.5F, -1F, -1.5F, 5, 1, 3);
vehicleSpoiler.setRotationPoint(0F, 22F, 4.8F);
vehicleSpoiler.setTextureSize(64, 128);
vehicleSpoiler.mirror = true;
setRotation(vehicleSpoiler, 0.1919862F, 0F, 0F);
vehicleDoor1 = new MowzieModelRenderer(this, 24, 68);
vehicleDoor1.addBox(-1F, -1F, -1.5F, 1, 1, 3);
vehicleDoor1.setRotationPoint(-1.8F, 21.7F, 0.5F);
vehicleDoor1.setTextureSize(64, 128);
vehicleDoor1.mirror = true;
setRotation(vehicleDoor1, 0F, 0F, 0.2268928F);
vehicleDoor2 = new MowzieModelRenderer(this, 24, 68);
vehicleDoor2.addBox(0F, -1F, -1.5F, 1, 1, 3);
vehicleDoor2.setRotationPoint(1.8F, 21.7F, 0.5F);
vehicleDoor2.setTextureSize(64, 128);
vehicleDoor2.mirror = true;
setRotation(vehicleDoor2, 0F, 0F, -0.2268928F);
this.addChildTo(vehicleFrontWheel1, vehicleBody);
this.addChildTo(vehicleFrontWheel2, vehicleBody);
this.addChildTo(vehicleBackWheel1, vehicleBody);
this.addChildTo(vehicleBackWheel2, vehicleBody);
this.addChildTo(vehicleBumper1, vehicleBody);
this.addChildTo(vehicleBumper2, vehicleBody);
this.addChildTo(vehicleRoof, vehicleBody);
this.addChildTo(vehicleHood, vehicleBody);
this.addChildTo(vehicleBackWindShield, vehicleBody);
this.addChildTo(vehicleWindShield, vehicleBody);
this.addChildTo(vehicleSpoiler, vehicleBody);
this.addChildTo(vehicleDoor1, vehicleBody);
this.addChildTo(vehicleDoor2, vehicleBody);
this.stealthForceHoodGun1 = new MowzieModelRenderer(this, 42, 66);
this.stealthForceHoodGun1.setRotationPoint(-1.0F, 0.0F, -2.9F);
this.stealthForceHoodGun1.addBox(-0.5F, -0.5F, -1.0F, 1, 1, 1, 0.0F);
this.setRotation(stealthForceHoodGun1, 0.13962634015954636F, 0.0F, 0.0F);
this.stealthForceBackWindShield = new MowzieModelRenderer(this, 14, 78);
this.stealthForceBackWindShield.setRotationPoint(0.0F, -1.8F, 7.5F);
this.stealthForceBackWindShield.addBox(-2.5F, -0.5F, 0.0F, 5, 1, 3, 0.0F);
this.setRotation(stealthForceBackWindShield, -0.3839724354387525F, -0.0F, 0.0F);
this.stealthForceBackWheel2 = new MowzieModelRenderer(this, 0, 64);
this.stealthForceBackWheel2.setRotationPoint(0.3F, 0.5F, 0.2F);
this.stealthForceBackWheel2.addBox(0.0F, -1.0F, -1.0F, 1, 2, 2, 0.0F);
this.stealthForceRoof = new MowzieModelRenderer(this, 0, 78);
this.stealthForceRoof.setRotationPoint(0.0F, -1.8F, 5.7F);
this.stealthForceRoof.addBox(-2.5F, -0.5F, 0.0F, 5, 1, 2, 0.0F);
this.stealthForceBase = new MowzieModelRenderer(this, 0, 64);
this.stealthForceBase.setRotationPoint(0.0F, 22.5F, -6.2F);
this.stealthForceBase.addBox(-3.0F, -1.0F, 0.0F, 6, 2, 12, 0.0F);
this.stealthForceBackWheelCover2 = new MowzieModelRenderer(this, 38, 68);
this.stealthForceBackWheelCover2.setRotationPoint(3.0F, 0.0F, 10.0F);
this.stealthForceBackWheelCover2.addBox(0.0F, -1.0F, -2.0F, 1, 2, 4, 0.0F);
this.stealthForceGun2 = new MowzieModelRenderer(this, 40, 64);
this.stealthForceGun2.setRotationPoint(3.0F, -1.3F, 5.2F);
this.stealthForceGun2.addBox(-0.5F, -0.5F, -3.0F, 1, 1, 3, 0.0F);
this.stealthForceSpoiler = new MowzieModelRenderer(this, 24, 64);
this.stealthForceSpoiler.setRotationPoint(0.0F, -0.5F, 11.0F);
this.stealthForceSpoiler.addBox(-2.5F, -1.0F, -1.5F, 5, 1, 3, 0.0F);
this.setRotation(stealthForceSpoiler, 0.19198621771937624F, -0.0F, 0.0F);
this.stealthForceBumper2 = new MowzieModelRenderer(this, 0, 68);
this.stealthForceBumper2.mirror = true;
this.stealthForceBumper2.setRotationPoint(1.0F, 0.5F, 1.2F);
this.stealthForceBumper2.addBox(-0.5F, -1.5F, -2.0F, 3, 2, 2, 0.0F);
this.setRotation(stealthForceBumper2, 0.0F, -0.24434609527920614F, 0.0F);
this.stealthForceWindShield = new MowzieModelRenderer(this, 14, 82);
this.stealthForceWindShield.setRotationPoint(0.0F, -0.1F, 3.4F);
this.stealthForceWindShield.addBox(-2.5F, -1.0F, 0.0F, 5, 1, 3, 0.0F);
this.setRotation(stealthForceWindShield, 0.45378560551852565F, -0.0F, 0.0F);
this.stealthForceDoor2 = new MowzieModelRenderer(this, 24, 68);
this.stealthForceDoor2.setRotationPoint(1.8F, -0.7F, 6.7F);
this.stealthForceDoor2.addBox(0.0F, -1.0F, -1.5F, 1, 1, 3, 0.0F);
this.setRotation(stealthForceDoor2, 0.0F, -0.0F, -0.22689280275926282F);
this.stealthForceHood = new MowzieModelRenderer(this, 0, 81);
this.stealthForceHood.setRotationPoint(0.0F, -0.7F, 3.5F);
this.stealthForceHood.addBox(-2.0F, -0.5F, -3.0F, 4, 1, 3, 0.0F);
this.setRotation(stealthForceHood, -0.13962634015954636F, 0.0F, 0.0F);
this.stealthForceGun1 = new MowzieModelRenderer(this, 40, 64);
this.stealthForceGun1.setRotationPoint(-3.0F, -1.3F, 5.2F);
this.stealthForceGun1.addBox(-0.5F, -0.5F, -3.0F, 1, 1, 3, 0.0F);
this.stealthForceFrontWheel2 = new MowzieModelRenderer(this, 0, 64);
this.stealthForceFrontWheel2.setRotationPoint(0.3F, 0.5F, 0.2F);
this.stealthForceFrontWheel2.addBox(0.0F, -1.0F, -1.0F, 1, 2, 2, 0.0F);
this.stealthForceBackWheelCover1 = new MowzieModelRenderer(this, 38, 68);
this.stealthForceBackWheelCover1.setRotationPoint(-3.0F, 0.0F, 10.0F);
this.stealthForceBackWheelCover1.addBox(-1.0F, -1.0F, -2.0F, 1, 2, 4, 0.0F);
this.stealthForceDoor1 = new MowzieModelRenderer(this, 24, 68);
this.stealthForceDoor1.setRotationPoint(-1.8F, -0.7F, 6.7F);
this.stealthForceDoor1.addBox(-1.0F, -1.0F, -1.5F, 1, 1, 3, 0.0F);
this.setRotation(stealthForceDoor1, 0.0F, -0.0F, 0.22689280275926282F);
this.stealthForceHoodGun2 = new MowzieModelRenderer(this, 42, 66);
this.stealthForceHoodGun2.setRotationPoint(1.0F, 0.0F, -2.9F);
this.stealthForceHoodGun2.addBox(-0.5F, -0.5F, -1.0F, 1, 1, 1, 0.0F);
this.setRotation(stealthForceHoodGun2, 0.13962634015954636F, 0.0F, 0.0F);
this.stealthForceFrontWheelCover2 = new MowzieModelRenderer(this, 28, 68);
this.stealthForceFrontWheelCover2.setRotationPoint(3.0F, 0.0F, 1.5F);
this.stealthForceFrontWheelCover2.addBox(0.0F, -1.0F, -1.5F, 1, 2, 4, 0.0F);
this.stealthForceBackWheel1 = new MowzieModelRenderer(this, 0, 64);
this.stealthForceBackWheel1.setRotationPoint(-0.3F, 0.5F, 0.2F);
this.stealthForceBackWheel1.addBox(-1.0F, -1.0F, -1.0F, 1, 2, 2, 0.0F);
this.stealthForceBumper1 = new MowzieModelRenderer(this, 0, 68);
this.stealthForceBumper1.setRotationPoint(-1.0F, 0.5F, 1.2F);
this.stealthForceBumper1.addBox(-2.5F, -1.5F, -2.0F, 3, 2, 2, 0.0F);
this.setRotation(stealthForceBumper1, 0.0F, 0.24434609527920614F, 0.0F);
this.stealthForceFrontWheelCover1 = new MowzieModelRenderer(this, 28, 68);
this.stealthForceFrontWheelCover1.setRotationPoint(-3.0F, 0.0F, 1.5F);
this.stealthForceFrontWheelCover1.addBox(-1.0F, -1.0F, -1.5F, 1, 2, 4, 0.0F);
this.stealthForceFrontGun = new MowzieModelRenderer(this, 41, 65);
this.stealthForceFrontGun.setRotationPoint(0.0F, 0.0F, 0.0F);
this.stealthForceFrontGun.addBox(-0.5F, -0.5F, -2.0F, 1, 1, 2, 0.0F);
this.stealthForceFrontWheel1 = new MowzieModelRenderer(this, 0, 64);
this.stealthForceFrontWheel1.setRotationPoint(-0.3F, 0.5F, 0.2F);
this.stealthForceFrontWheel1.addBox(-1.0F, -1.0F, -1.0F, 1, 2, 2, 0.0F);
this.stealthForceHood.addChild(this.stealthForceHoodGun1);
this.stealthForceBase.addChild(this.stealthForceBackWindShield);
this.stealthForceBackWheelCover2.addChild(this.stealthForceBackWheel2);
this.stealthForceBase.addChild(this.stealthForceRoof);
this.stealthForceBase.addChild(this.stealthForceBackWheelCover2);
this.stealthForceBase.addChild(this.stealthForceGun2);
this.stealthForceBase.addChild(this.stealthForceSpoiler);
this.stealthForceBase.addChild(this.stealthForceBumper2);
this.stealthForceBase.addChild(this.stealthForceWindShield);
this.stealthForceBase.addChild(this.stealthForceDoor2);
this.stealthForceBase.addChild(this.stealthForceHood);
this.stealthForceBase.addChild(this.stealthForceGun1);
this.stealthForceFrontWheelCover2.addChild(this.stealthForceFrontWheel2);
this.stealthForceBase.addChild(this.stealthForceBackWheelCover1);
this.stealthForceBase.addChild(this.stealthForceDoor1);
this.stealthForceHood.addChild(this.stealthForceHoodGun2);
this.stealthForceBase.addChild(this.stealthForceFrontWheelCover2);
this.stealthForceBackWheelCover1.addChild(this.stealthForceBackWheel1);
this.stealthForceBase.addChild(this.stealthForceBumper1);
this.stealthForceBase.addChild(this.stealthForceFrontWheelCover1);
this.stealthForceBase.addChild(this.stealthForceFrontGun);
this.stealthForceFrontWheelCover1.addChild(this.stealthForceFrontWheel1);
adjustPos();
}
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5)
{
super.render(entity, f, f1, f2, f3, f4, f5);
setRotationAngles(f, f1, f2, f3, f4, f5, entity);
vehicleBody.render(f5);
stealthForceBase.render(f5);
}
public void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void setRotationAngles(float par1, float par2, float par3, float par4, float par5, float par6, Entity entity)
{
super.setRotationAngles(par1, par2, par3, par4, par5, par6, entity);
if (entity instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer)entity;
if (TFDataManager.getTransformationTimer(player) == 0)
{
for (MowzieModelRenderer modelRenderer : new MowzieModelRenderer[] {stealthForceBase, vehicleBody})
{
float f1 = this.bipedHead.rotateAngleY - (this.bipedBody.rotateAngleY - this.bipedHead.rotateAngleY) / 3;
if (modelRenderer.rotateAngleY < f1) {modelRenderer.rotateAngleY += 0.05F;}
if (modelRenderer.rotateAngleY > f1) {modelRenderer.rotateAngleY -= 0.05F;}
modelRenderer.rotateAngleY = f1;
if (player == Minecraft.getMinecraft().thePlayer)
{
modelRenderer.rotateAngleX = -(float)player.motionY - 0.0784000015258789F;
}
else
{
modelRenderer.rotateAngleX = -(float)(player.posY - player.prevPosY) * 1.5F;
}
}
if (TFDataManager.getStealthModeTimer(player) == 5)
{
vehicleFrontWheel1.rotateAngleX = par1;
vehicleFrontWheel2.rotateAngleX = par1;
vehicleBackWheel1.rotateAngleX = par1;
vehicleBackWheel2.rotateAngleX = par1;
vehicleBody.offsetY = 0F;
stealthForceBase.offsetY = 256F;
}
else
{
int t = TFDataManager.getStealthModeTimer(player) * 2;
float f = (10 - t);
stealthForceBackWheelCover1.rotationPointX = -2 - (f / 10);
stealthForceBackWheelCover2.rotationPointX = 2 + (f / 10);
stealthForceFrontWheelCover1.rotationPointX = -2 - (f / 10);
stealthForceFrontWheelCover2.rotationPointX = 2 + (f / 10);
stealthForceBumper1.rotationPointX = -(f / 10);
stealthForceBumper2.rotationPointX = (f / 10);
stealthForceFrontGun.rotationPointZ = 2 - (f / 10) * 2;
stealthForceHood.rotateAngleX = -0.13962634015954636F * (f / 10);
stealthForceHoodGun1.rotationPointY = -(f / 10) + 1;
stealthForceHoodGun2.rotationPointY = -(f / 10) + 1;
stealthForceGun1.rotationPointX = -2 - (f / 10);
stealthForceGun2.rotationPointX = 2 + (f / 10);
stealthForceGun1.rotationPointY = -(f / 10) - 0.3F;
stealthForceGun2.rotationPointY = -(f / 10) - 0.3F;
stealthForceFrontWheel1.rotateAngleX = par1;
stealthForceFrontWheel2.rotateAngleX = par1;
stealthForceBackWheel1.rotateAngleX = par1;
stealthForceBackWheel2.rotateAngleX = par1;
stealthForceBase.offsetY = 0F;
vehicleBody.offsetY = 256F;
}
bipedHead.offsetY = 256F;
bipedBody.offsetY = 256F;
bipedRightArm.offsetY = 256F;
bipedLeftArm.offsetY = 256F;
bipedRightLeg.offsetY = 256F;
bipedLeftLeg.offsetY = 256F;
}
else
{
int t = TFDataManager.getTransformationTimer(player);
float f = (float)(20 - t) / 2;
ModelOffset offsets = TFModelHelper.getOffsets(player);
this.bipedHead.rotationPointX = offsets.headOffsetX;
this.bipedHead.rotationPointY = offsets.headOffsetY;
this.bipedHead.rotationPointZ = offsets.headOffsetZ;
if(bipedHead.rotationPointY != 0)
{
bipedHead.rotationPointY -= 1;
}
vehicleBody.rotateAngleX = 0;
bipedBody.rotationPointY = f * 2.5F;
bipedBody.rotationPointZ = f / 10 * -7.5F;
bipedRightArm.rotationPointZ = f / 10 * -5F;
bipedLeftArm.rotationPointZ = f / 10 * -5F;
chest.rotationPointZ = -3.0F / 10 * f;
chest.rotateAngleX = -pi / 2 / 10 * f;
bipedRightArm.rotationPointY = f * 2;
bipedLeftArm.rotationPointY = f * 2;
bipedRightArm.rotationPointX = f / 3.5F - 5;
bipedLeftArm.rotationPointX = -f / 3.5F + 5;
bipedRightLeg.rotateAngleZ = f * pi / 10;
bipedLeftLeg.rotateAngleZ = f * pi / 10;
bipedRightLeg.rotationPointX = -f / 7.5F;
bipedLeftLeg.rotationPointX = -f / 7.5F;
if (t < 20)
{
bipedRightLeg.rotateAngleX = f * pi / 2 / 10;
bipedLeftLeg.rotateAngleX = f * pi / 2 / 10;
bipedRightLeg.rotationPointY = f * 1.3F + 12;
bipedLeftLeg.rotationPointY = f * 1.3F + 12;
bipedRightLeg.rotationPointZ = -f / 2;
bipedLeftLeg.rotationPointZ = -f / 2;
bipedBody.rotateAngleX = pi / 2 / 10 * f;
bipedHead.rotationPointY = f * 2.5F;
bipedRightArm.rotateAngleX = f / 10 * 1.5F;
bipedLeftArm.rotateAngleX = f / 10 * 1.5F;
}
bipedHead.offsetY = 0F;
bipedBody.offsetY = 0F;
bipedRightArm.offsetY = 0F;
bipedLeftArm.offsetY = 0F;
bipedRightLeg.offsetY = 0F;
bipedLeftLeg.offsetY = 0F;
vehicleBody.offsetY = 256F;
stealthForceBase.offsetY = 256F;
}
}
}
public void adjustPos()
{
// Body
chest.rotationPointY = -4F;
frontCar1.rotationPointY = -2.5F;
frontCar2.rotationPointY = -2.5F;
chestPanel1.rotationPointY = -1.5F;
chestPanel2.rotationPointY = -1.5F;
chestPanel3.rotationPointY = -3F;
windShield.rotationPointY = -5F;
frontWheel1.rotationPointY = -4.5F;
frontWheel2.rotationPointY = -4.5F;
// Arms
upperArm1.rotationPointX = 1F;
lowerArm1.setRotationPoint(-1F, 3.5F, 0);
armPanel1.setRotationPoint(-1F, 3.75F, 0F);
setRotation(armPanel1, 0F, 0F, -0.0872665F);
upperArm2.rotationPointX = -1F;
lowerArm2.setRotationPoint(1F, 3.5F, 0);
armPanel2.setRotationPoint(1F, 3.75F, 0F);
setRotation(armPanel2, 0F, 0F, 0.0872665F);
// Legs
leg1.rotationPointY = 12F;
leg2.rotationPointY = 12F;
upperLegPanel1.rotationPointX = 0F;
upperLegPanel2.rotationPointX = 0F;
}
}<file_sep>/src/Legacy/java/fiskfille/tf/data/TFPlayerDataNew.java
package fiskfille.tf.data;
import com.google.common.collect.ComputationException;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
public class TFPlayerDataNew implements IExtendedEntityProperties
{
public boolean mode;
public static final String IDENTIFIER = "TFPLAYERDATA";
public static TFPlayerDataNew getData(EntityPlayer player)
{
return (TFPlayerDataNew) player.getExtendedProperties(IDENTIFIER);
}
@Override
public void saveNBTData(NBTTagCompound compound)
{
compound.setBoolean("mode", mode);
}
@Override
public void loadNBTData(NBTTagCompound compound)
{
mode = compound.getBoolean("mode");
}
@Override
public void init(Entity entity, World world)
{
}
}
<file_sep>/README.md
# Transformers Mod
This is the Official GitHub Repository for the Transformers Mod for Minecraft.
This mod is developed by FiskFille.
If you want to contribute, feel free to submit a Pull Request.
Also, if you have any problems with the mod, submit it on the "Issues" page.
<file_sep>/src/main/java/fiskfille/tf/helper/TFModelHelper.java
package fiskfille.tf.helper;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.entity.player.EntityPlayer;
public class TFModelHelper
{
public static ModelBiped modelBipedMain;
public static Map<EntityPlayer, ModelOffset> offsets = new HashMap<EntityPlayer, ModelOffset>();
public static ModelOffset getOffsets(EntityPlayer player)
{
ModelOffset modelOffset = offsets.get(player);
if(modelOffset == null)
{
modelOffset = new ModelOffset();
offsets.put(player, modelOffset);
}
return modelOffset;
}
}
<file_sep>/src/main/java/fiskfille/tf/client/model/tileentity/ModelTransformiumSeed.java
package fiskfille.tf.client.model.tileentity;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import org.lwjgl.opengl.GL11;
import fiskfille.tf.common.entity.EntityTransformiumSeed;
public class ModelTransformiumSeed extends ModelBase
{
public ModelRenderer shape1;
public ModelRenderer shape2;
public ModelRenderer shape3;
public ModelRenderer shape4;
public ModelRenderer shape5;
public ModelRenderer shape6;
public ModelRenderer shape7;
public ModelRenderer wingA;
public ModelRenderer wingB;
public ModelRenderer wingC;
public ModelRenderer wingD;
public ModelRenderer antenna;
public ModelTransformiumSeed()
{
this.textureWidth = 64;
this.textureHeight = 32;
this.shape1 = new ModelRenderer(this, 0, 0);
this.shape1.setRotationPoint(0.0F, 4.0F, 0.0F);
this.shape1.addBox(-1.0F, 0.0F, -1.0F, 2, 1, 2, 0.0F);
this.shape2 = new ModelRenderer(this, 0, 3);
this.shape2.setRotationPoint(0.0F, 5.0F, 0.0F);
this.shape2.addBox(-1.5F, 0.0F, -1.5F, 3, 6, 3, 0.0F);
this.shape5 = new ModelRenderer(this, 0, 19);
this.shape5.setRotationPoint(0.0F, 6.0F, 0.0F);
this.shape5.addBox(-2.0F, 0.0F, -2.0F, 4, 1, 4, 0.0F);
this.antenna = new ModelRenderer(this, 14, 7);
this.antenna.setRotationPoint(0.0F, 12.5F, 0.0F);
this.antenna.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 1, 0.0F);
this.shape6 = new ModelRenderer(this, 8, 8);
this.shape6.setRotationPoint(0.0F, 14.0F, 0.0F);
this.shape6.addBox(-0.5F, -0.5F, -2.0F, 1, 2, 4, 0.0F);
this.setRotation(shape6, 0.0F, 1.5707963267948966F, 0.0F);
this.shape7 = new ModelRenderer(this, 8, 8);
this.shape7.setRotationPoint(0.0F, 14.0F, 0.0F);
this.shape7.addBox(-0.5F, -0.5F, -2.0F, 1, 2, 4, 0.0F);
this.wingA = new ModelRenderer(this, 12, 0);
this.wingA.setRotationPoint(0.0F, 14.0F, -1.5F);
this.wingA.addBox(-1.0F, -5.0F, -0.5F, 2, 6, 1, 0.0F);
this.setRotation(wingA, 0.06981317007977318F, 0.0F, 0.0F);
this.wingB = new ModelRenderer(this, 18, 0);
this.wingB.setRotationPoint(-1.5F, 14.0F, 0.0F);
this.wingB.addBox(-0.5F, -5.0F, -1.0F, 1, 6, 2, 0.0F);
this.setRotation(wingB, 0.0F, 0.0F, -0.06981317007977318F);
this.shape4 = new ModelRenderer(this, 0, 19);
this.shape4.setRotationPoint(0.0F, 8.0F, 0.0F);
this.shape4.addBox(-2.0F, 0.0F, -2.0F, 4, 1, 4, 0.0F);
this.shape3 = new ModelRenderer(this, 0, 12);
this.shape3.setRotationPoint(0.0F, 11.0F, 0.0F);
this.shape3.addBox(-1.0F, 0.0F, -1.0F, 2, 5, 2, 0.0F);
this.wingC = new ModelRenderer(this, 24, 0);
this.wingC.setRotationPoint(0.0F, 14.0F, 1.5F);
this.wingC.addBox(-1.0F, -5.0F, -0.5F, 2, 6, 1, 0.0F);
this.setRotation(wingC, -0.06981317007977318F, 0.0F, 0.0F);
this.wingD = new ModelRenderer(this, 30, 0);
this.wingD.setRotationPoint(1.5F, 14.0F, 0.0F);
this.wingD.addBox(-0.5F, -5.0F, -1.0F, 1, 6, 2, 0.0F);
this.setRotation(wingD, 0.0F, 0.0F, 0.06981317007977318F);
}
public void render(EntityTransformiumSeed seed)
{
setRotationAngles(seed);
float f5 = 0.0625F;
float scale = 1.3F;
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, -0.85F, 0.0F);
GL11.glScalef(scale, scale, scale);
this.shape1.render(f5);
this.shape2.render(f5);
this.shape5.render(f5);
this.antenna.render(f5);
this.shape6.render(f5);
this.shape7.render(f5);
this.wingA.render(f5);
this.wingB.render(f5);
this.shape4.render(f5);
this.shape3.render(f5);
this.wingC.render(f5);
this.wingD.render(f5);
GL11.glPopMatrix();
}
public void setRotation(ModelRenderer modelRenderer, float x, float y, float z)
{
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
public void setRotationAngles(EntityTransformiumSeed seed)
{
super.setRotationAngles(0, 0, 0, 0, 0, 0, seed);
float t = (float)(seed.ticksExisted <= 50 ? seed.ticksExisted : 50) / 50;
float i = 1.0F - t;
this.setRotation(wingA, (0.06981317007977318F * i + ((float)Math.PI / 2) * t), 0.0F, 0.0F);
this.setRotation(wingB, 0.0F, 0.0F, -(0.06981317007977318F * i + ((float)Math.PI / 2) * t));
this.setRotation(wingC, -(0.06981317007977318F * i + ((float)Math.PI / 2) * t), 0.0F, 0.0F);
this.setRotation(wingD, 0.0F, 0.0F, (0.06981317007977318F * i + ((float)Math.PI / 2) * t));
this.antenna.setRotationPoint(0.0F, 12.5F + (t * 3.5F), 0.0F);
}
}<file_sep>/src/Legacy/java/fiskfille/tf/gui/GuiOverlay.java
package fiskfille.tf.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.GuiIngameForge;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fiskfille.tf.data.TFPlayerData;
import fiskfille.tf.main.MainClass;
import fiskfille.tf.main.TFHelper;
import fiskfille.tf.main.TFItems;
import fiskfille.tf.main.misc.TFVehichleModeMotionManager;
public class GuiOverlay extends Gui
{
private Minecraft mc;
private RenderItem itemRenderer;
public static final ResourceLocation texture = new ResourceLocation(MainClass.modid, "textures/gui/mod_icons.png");
public GuiOverlay(Minecraft mc)
{
super();
this.mc = mc;
this.itemRenderer = new RenderItem();
}
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void onRender(RenderGameOverlayEvent.Pre event)
{
int width = event.resolution.getScaledWidth();
int height = event.resolution.getScaledHeight();
EntityPlayer player = mc.thePlayer;
if (!(event.type == ElementType.JUMPBAR || event.type == ElementType.HOTBAR))
return;
renderNitroAndSpeed(event, width, height, player);
renderKatanaDash(event, width, height, player);
renderCrossbowAmmo(event, width, height, player);
}
public void renderNitroAndSpeed(RenderGameOverlayEvent.Pre event, int width, int height, EntityPlayer player)
{
int nitro = TFVehichleModeMotionManager.nitroMap.get(player.getDisplayName()) == null ? 0 : TFVehichleModeMotionManager.nitroMap.get(player.getDisplayName());
int speed = (int)((TFVehichleModeMotionManager.velocityMap.get(player.getDisplayName()) == null ? 0 : TFVehichleModeMotionManager.velocityMap.get(player.getDisplayName())) * 100);
int i = TFPlayerData.getTransformationTimer(player) * 30;
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(0F, 0F, 0F, 0.3F);
drawTexturedModalRect(5 - i, height - 17, 0, 0, 202, 12);
drawTexturedModalRect(5 - i, height - 25, 0, 0, 202, 6);
GL11.glColor4f(0.0F, 1.0F, 1.0F, 0.5F);
drawTexturedModalRect(6 - i, height - 16, 0, 0, (int)(nitro * 1.25F), 10);
GL11.glColor4f(1.0F, 0.0F, 0.0F, 0.5F);
drawTexturedModalRect(6 - i, height - 24, 0, 0, (int)(speed * 1F), 4);
GL11.glEnable(GL11.GL_TEXTURE_2D);
drawCenteredString(mc.fontRenderer, "Nitro", 106 - i, height - 15, 0xffffff);
drawCenteredString(mc.fontRenderer, speed + " km/h", 106 - i, height - 26, 0xffffff);
}
public void renderKatanaDash(RenderGameOverlayEvent.Pre event, int width, int height, EntityPlayer player)
{
if (player.getHeldItem() != null && player.getHeldItem().getItem() == TFItems.purgesKatana && !TFPlayerData.isInVehicleMode(player) && TFHelper.isPlayerPurge(player))
{
int j = TFItems.purgesKatana.getMaxItemUseDuration(player.getHeldItem()) - player.getItemInUseCount();
double d = (double)j / 10;
if (d > 2.0D)
{
d = 2.0D;
}
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(0F, 0F, 0F, 0.15F);
drawTexturedModalRect(width / 2 - 26, height / 2 + 9, 0, 0, 52, 12);
GL11.glColor4f(1F, 0F, 0F, 0.25F);
drawTexturedModalRect(width / 2 - 25, height / 2 + 10, 0, 0, (int)(d * 25), 10);
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
}
public void renderCrossbowAmmo(RenderGameOverlayEvent.Pre event, int width, int height, EntityPlayer player)
{
}
}<file_sep>/src/Legacy/java/fiskfille/tf/model/tileentity/ModelDisplayPillar.java
package fiskfille.tf.model.tileentity;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
public class ModelDisplayPillar extends ModelBase
{
ModelRenderer main;
ModelRenderer backLeftFoot;
ModelRenderer frontLeftFoot;
ModelRenderer frontRightFoot;
ModelRenderer backRightFoot;
ModelRenderer top;
public ModelDisplayPillar()
{
textureWidth = 64;
textureHeight = 64;
main = new ModelRenderer(this, 0, 10);
main.addBox(-3F, -8F, -3F, 6, 8, 6);
main.setRotationPoint(0F, 24F, 0F);
main.setTextureSize(64, 64);
main.mirror = true;
setRotation(main, 0F, 0F, 0F);
backLeftFoot = new ModelRenderer(this, 24, 10);
backLeftFoot.addBox(-1F, 0F, -1F, 2, 10, 2);
backLeftFoot.setRotationPoint(2F, 17F, 2F);
backLeftFoot.setTextureSize(64, 64);
backLeftFoot.mirror = true;
setRotation(backLeftFoot, -0.6981317F, -2.356194F, 0F);
frontLeftFoot = new ModelRenderer(this, 24, 10);
frontLeftFoot.addBox(-1F, 0F, -1F, 2, 10, 2);
frontLeftFoot.setRotationPoint(2F, 17F, -2F);
frontLeftFoot.setTextureSize(64, 64);
frontLeftFoot.mirror = true;
setRotation(frontLeftFoot, -0.6981317F, -0.7853982F, 0F);
frontRightFoot = new ModelRenderer(this, 24, 10);
frontRightFoot.addBox(-1F, 0F, -1F, 2, 10, 2);
frontRightFoot.setRotationPoint(-2F, 17F, -2F);
frontRightFoot.setTextureSize(64, 64);
frontRightFoot.mirror = true;
setRotation(frontRightFoot, -0.6981317F, 0.7853982F, 0F);
backRightFoot = new ModelRenderer(this, 24, 10);
backRightFoot.addBox(-1F, 0F, -1F, 2, 10, 2);
backRightFoot.setRotationPoint(-2F, 17F, 2F);
backRightFoot.setTextureSize(64, 64);
backRightFoot.mirror = true;
setRotation(backRightFoot, -0.6981317F, 2.356194F, 0F);
top = new ModelRenderer(this, 0, 0);
top.addBox(-4F, -2F, -4F, 8, 2, 8);
top.setRotationPoint(0F, 17.5F, 0F);
top.setTextureSize(64, 64);
top.mirror = true;
setRotation(top, 0F, 0F, 0F);
}
public void renderAll()
{
float f5 = 0.0625F;
main.render(f5);
backLeftFoot.render(f5);
frontLeftFoot.render(f5);
frontRightFoot.render(f5);
backRightFoot.render(f5);
top.render(f5);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5)
{
super.setRotationAngles(f, f1, f2, f3, f4, f5, null);
}
}<file_sep>/src/main/java/fiskfille/tf/common/transformer/TransformerPurge.java
package fiskfille.tf.common.transformer;
import net.minecraft.item.Item;
import fiskfille.tf.client.model.transformer.ModelChildBase.Biped;
import fiskfille.tf.client.model.transformer.TFModelRegistry;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.transformer.base.TransformerTank;
public class TransformerPurge extends TransformerTank
{
public TransformerPurge()
{
super("Purge");
}
@Override
public Item getHelmet()
{
return TFItems.purgeHelmet;
}
@Override
public Item getChestplate()
{
return TFItems.purgeChestplate;
}
@Override
public Item getLeggings()
{
return TFItems.purgeLeggings;
}
@Override
public Item getBoots()
{
return TFItems.purgeBoots;
}
}<file_sep>/src/main/java/fiskfille/tf/common/item/ItemBasic.java
package fiskfille.tf.common.item;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import fiskfille.tf.TransformersMod;
public class ItemBasic extends Item
{
public ItemBasic()
{
super();
this.setCreativeTab(TransformersMod.tabTransformers);
}
public void registerIcons(IIconRegister iconRegister)
{
itemIcon = iconRegister.registerIcon(TransformersMod.modid + ":" + iconString);
}
}<file_sep>/src/main/java/fiskfille/tf/client/model/transformer/TFModelRegistry.java
package fiskfille.tf.client.model.transformer;
import java.util.HashMap;
import java.util.Map;
import fiskfille.tf.TransformerManager;
import fiskfille.tf.client.model.transformer.ModelChildBase.Biped;
import fiskfille.tf.client.model.transformer.vehicle.ModelCloudtrapVehicle;
import fiskfille.tf.client.model.transformer.vehicle.ModelPurgeVehicle;
import fiskfille.tf.client.model.transformer.vehicle.ModelSkystrikeVehicle;
import fiskfille.tf.client.model.transformer.vehicle.ModelSubwooferVehicle;
import fiskfille.tf.client.model.transformer.vehicle.ModelVehicleBase;
import fiskfille.tf.client.model.transformer.vehicle.ModelVurpVehicle;
import fiskfille.tf.common.transformer.base.Transformer;
public class TFModelRegistry
{
private static Map<Transformer, Biped> models = new HashMap<Transformer, Biped>();
private static Map<Transformer, ModelVehicleBase> vehicleModels = new HashMap<Transformer, ModelVehicleBase>();
public static ModelVehicleBase getVehicleModel(Transformer transformer)
{
return vehicleModels.get(transformer);
}
public static void registerModel(Transformer transformer, Biped model, ModelVehicleBase vehicleModel)
{
models.put(transformer, model);
vehicleModels.put(transformer, vehicleModel);
}
public static Biped getModel(Transformer transformer)
{
return models.get(transformer);
}
public static void registerModels()
{
TFModelRegistry.registerModel(TransformerManager.transformerCloudtrap, new ModelCloudtrap(), new ModelCloudtrapVehicle());
TFModelRegistry.registerModel(TransformerManager.transformerPurge, new ModelPurge(), new ModelPurgeVehicle());
TFModelRegistry.registerModel(TransformerManager.transformerSkystrike, new ModelSkystrike(), new ModelSkystrikeVehicle());
TFModelRegistry.registerModel(TransformerManager.transformerSubwoofer, new ModelSubwoofer(), new ModelSubwooferVehicle());
TFModelRegistry.registerModel(TransformerManager.transformerVurp, new ModelVurp(), new ModelVurpVehicle());
}
}
<file_sep>/src/main/java/fiskfille/tf/common/packet/PacketVurpSniperShoot.java
package fiskfille.tf.common.packet;
import fiskfille.tf.TransformersMod;
import fiskfille.tf.common.entity.EntityMiniMissile;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.packet.base.TFPacketManager;
import fiskfille.tf.common.transformer.TransformerVurp;
import fiskfille.tf.common.transformer.base.Transformer;
import fiskfille.tf.config.TFConfig;
import fiskfille.tf.helper.TFHelper;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
public class PacketVurpSniperShoot implements IMessage
{
public int id;
public PacketVurpSniperShoot()
{
}
public PacketVurpSniperShoot(EntityPlayer player)
{
id = player.getEntityId();
}
public void fromBytes(ByteBuf buf)
{
id = buf.readInt();
}
public void toBytes(ByteBuf buf)
{
buf.writeInt(id);
}
public static class Handler implements IMessageHandler<PacketVurpSniperShoot, IMessage>
{
public IMessage onMessage(PacketVurpSniperShoot message, MessageContext ctx)
{
if (ctx.side.isClient())
{
EntityPlayer player = TransformersMod.proxy.getPlayer();
Entity fromEntity = player.worldObj.getEntityByID(message.id);
if (fromEntity instanceof EntityPlayer)
{
EntityPlayer from = (EntityPlayer) fromEntity;
Transformer transformer = TFHelper.getTransformer(player);
if (transformer instanceof TransformerVurp)
{
String shootSound = TransformersMod.modid + ":missile.shoot";
from.worldObj.playSound(from.posX, from.posY - (double)from.yOffset, from.posZ, shootSound, transformer.getShootVolume(), 1, false);
}
}
}
else
{
EntityPlayer player = ctx.getServerHandler().playerEntity;
if (player != null)
{
Transformer transformer = TFHelper.getTransformer(player);
if (transformer != null)
{
if (transformer instanceof TransformerVurp)
{
boolean isCreative = player.capabilities.isCreativeMode;
boolean hasAmmo = isCreative || player.inventory.hasItem(TFItems.miniMissile);
if (hasAmmo)
{
TFPacketManager.networkWrapper.sendToAll(new PacketVurpSniperShoot(player));
World world = player.worldObj;
EntityMiniMissile entity = new EntityMiniMissile(world, player, 30, TFConfig.allowMissileExplosions);
entity.setDamage(0.01D);
--entity.posY;
world.spawnEntityInWorld(entity);
if (!isCreative)
{
player.inventory.consumeInventoryItem(TFItems.miniMissile);
}
}
}
}
}
}
return null;
}
}
}
<file_sep>/src/main/java/fiskfille/tf/common/recipe/RecipesDisplayItems.java
package fiskfille.tf.common.recipe;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import fiskfille.tf.TransformersAPI;
import fiskfille.tf.common.item.TFItems;
import fiskfille.tf.common.item.armor.ItemTransformerArmor;
import fiskfille.tf.common.transformer.base.Transformer;
public class RecipesDisplayItems implements IRecipe
{
public boolean matches(InventoryCrafting inventoryCrafting, World world)
{
ItemStack[] stacks = new ItemStack[9];
for (int i = 0; i < stacks.length; i++)
{
stacks[i] = inventoryCrafting.getStackInSlot(i);
}
ItemStack head = null;
ItemStack chest = null;
ItemStack legs = null;
ItemStack boots = null;
int emptySlots = 0;
for (ItemStack itemStack : stacks)
{
if(itemStack != null)
{
Item item = itemStack.getItem();
if(item instanceof ItemTransformerArmor)
{
ItemArmor armorItem = (ItemArmor) item;
if(armorItem.armorType == 0)
{
head = itemStack;
}
else if(armorItem.armorType == 1)
{
chest = itemStack;
}
else if(armorItem.armorType == 2)
{
legs = itemStack;
}
else if(armorItem.armorType == 3)
{
boots = itemStack;
}
}
}
else
{
emptySlots++;
}
}
if(emptySlots != 5)
{
return false;
}
if(head != null && chest != null && legs != null && boots != null)
{
return true;
}
return false;
}
public ItemStack getCraftingResult(InventoryCrafting inventoryCrafting)
{
ItemStack itemstack = new ItemStack(TFItems.displayVehicle, 1);
itemstack.setTagCompound(new NBTTagCompound());
ItemStack[] stacks = new ItemStack[9];
for (int i = 0; i < stacks.length; i++)
{
stacks[i] = inventoryCrafting.getStackInSlot(i);
}
ItemStack head = null;
ItemStack chest = null;
ItemStack legs = null;
ItemStack feet = null;
for (ItemStack itemStack : stacks)
{
if(itemStack != null)
{
Item item = itemStack.getItem();
if(item instanceof ItemTransformerArmor)
{
ItemArmor armorItem = (ItemArmor) item;
if(armorItem.armorType == 0)
{
head = itemStack;
}
else if(armorItem.armorType == 1)
{
chest = itemStack;
}
else if(armorItem.armorType == 2)
{
legs = itemStack;
}
else if(armorItem.armorType == 3)
{
feet = itemStack;
}
}
}
else
{
}
}
if(head != null && chest != null && legs != null && feet != null)
{
Item headItem = head.getItem();
Item chestItem = chest.getItem();
Item legsItem = legs.getItem();
Item feetItem = feet.getItem();
int i = 0;
boolean found = false;
for (Transformer transformer : TransformersAPI.getTransformers())
{
Item helmet = transformer.getHelmet();
Item chestplate = transformer.getChestplate();
Item leggings = transformer.getLeggings();
Item boots = transformer.getBoots();
if (headItem == helmet && chestItem == chestplate && legsItem == leggings && feetItem == boots)
{
itemstack.setItemDamage(i);
setNBTData(head, chest, legs, feet, itemstack);
found = true;
}
i++;
}
if(!found)
{
itemstack = null;
}
}
return itemstack;
}
public void setNBTData(ItemStack head, ItemStack chest, ItemStack legs, ItemStack feet, ItemStack itemstack)
{
ItemStack[] itemstacks = {head, chest, legs, feet};
NBTTagList itemsList = new NBTTagList();
for (int i = 0; i < itemstacks.length; ++i)
{
if (itemstacks[i] != null)
{
NBTTagCompound itemTag = new NBTTagCompound();
itemTag.setByte("Slot", (byte)i);
itemstacks[i].writeToNBT(itemTag);
itemsList.appendTag(itemTag);
}
}
itemstack.getTagCompound().setTag("Items", itemsList);
}
public int getRecipeSize()
{
return 10;
}
public ItemStack getRecipeOutput()
{
return null;
}
} | a62427446f5bde5770b361885a8fa68bf7b3e446 | [
"Markdown",
"Java"
] | 70 | Java | phase/TransformersMod | eb996e68bbf595d1a2bcef7b2fc86867d84dec7a | 9e170fc5357956de54b979d91c6713a3c8c0c45b |
refs/heads/master | <repo_name>DiegoZavallo/TE_Discovery<file_sep>/6.5_ideogram.R
install.packages("devtools")
library(devtools)
devtools::install_github('TickingClock1992/RIdeogram')
require(RIdeogram)
data(human_karyotype, package="RIdeogram")
data(gene_density, package="RIdeogram")
data(Random_RNAs_500, package="RIdeogram")
head(human_karyotype)
head(gene_density)
head(Random_RNAs_500)
human_karyotype <- read.table("karyotype.txt", sep = "\t", header = T, stringsAsFactors = F)
gene_density <- read.table("data_1.txt", sep = "\t", header = T, stringsAsFactors = F)
Random_RNAs_500 <- read.table("data_2.txt", sep = "\t", header = T, stringsAsFactors = F)
ideogram(karyotype = human_karyotype)
convertSVG("chromosome.svg", device = "png")
ideogram(karyotype = human_karyotype, overlaid = gene_density, label = Random_RNAs_500)
convertSVG("chromosome.svg", device = "png")
<file_sep>/README.md
This is a series of jupyter notebooks that takes Transposable Elements (TEs) sequences from different sources in .fasta format, classifies and annotates them accordingly and prepare the data for a genome-wide identification. Final result is a gff file containing all TEs and the according identification.
```
#Recommended. Create a virtual environment using python3 and venv
virtualenv --python=python3 venv
#Activate venv
source venv/bin/activate
#make sure the python3 used is in the venv
which python
#(...)TE_Discovery/venv/bin/python
#Install requirements
pip3 install -r requirements.txt
#run jupyter lab
jupyter lab
```
This will start a jupyter lab in your browser. You can start running notebooks in order. Notice that for some of them, special configuration will be required.
#### 1.1_add_annotation.ipynb
Information about paths for each TE type has to be set in _paths_fasta_ dictionary.
#### 2.1_vsearch.sh
Run vsearch for each TE type
#### 2.2_vsearch_merge.ipynb
Takes one TE from each cluster and create one .fasta file for each TE type
#### 3.1_blast.sh
Search all sequences against the full genome
#### 3.2_blast_filter.ipynb
Filter the blast results according to user-specified parameters
#### 4.1_annotate.ipynb
Tab-delimited results to a gff3 format file, adding a detailed description for each TE including TE_id (a numeric identifier of the element after clustering) source_name (original id name of the element before clustering) type (family type of the element), source (program or tool from which the TEs was detected) and uinique_id (unique identifier for copy element).
## Extras. Scripts used for plots
#### 5.1_coverage.sh
Calculate genome coverage
#### 6.1_area_plot.ipynb
Plot TE distribution across genome
#### 6.2_circos_prepare_genes.ipynb
Plot ciros with genes coverage
#### 6.3_circos_prepare.ipynb
Plot ciros with TEs coverage
#### 6.4_tes_genes_distance.ipynb
Calculate distance to closest gene
#### 6.5_ideogram.R
Plot an ideogram with coverage
#### 6.6_plot_tes_genes_distance.ipynb
Plot distance to genes
#### 7.0_tephra_ages.ipynb
Parse ages data from tephra
#### 7.1_ages_part.ipynb
Place ages data into hetero/eu chromatin
#### 7.2_age.R
Plot ages in ideograms
<file_sep>/5.1_coverage.sh
awk '{ if ($1 != "ChrUn") { print } }' data/results/all.gff > data/results/all.noun.gff
echo "" > data/results/coverage.txt
grep "TRIM_id" data/results/all.noun.gff > data/results/all_trim.gff
grep "LINE_id" data/results/all.noun.gff > data/results/all_line.gff
grep "SINE_id" data/results/all.noun.gff > data/results/all_sine.gff
grep "MITE_id" data/results/all.noun.gff > data/results/all_mite.gff
grep "LARD_id" data/results/all.noun.gff > data/results/all_lard.gff
grep "LTR_id" data/results/all.noun.gff > data/results/all_ltr.gff
grep "helitron_id" data/results/all.noun.gff > data/results/all_helitron.gff
grep "TIR_id" data/results/all.noun.gff > data/results/all_tir.gff
grep "RLG" data/results/all_ltr.gff > data/results/all_rlg.gff
grep "RLC" data/results/all_ltr.gff > data/results/all_rlc.gff
grep "RLX" data/results/all_ltr.gff > data/results/all_rlx.gff
grep "DTM" data/results/all.noun.gff > data/results/all_dtm.gff
grep "DTC" data/results/all.noun.gff > data/results/all_dtc.gff
grep "DTT" data/results/all.noun.gff > data/results/all_dtt.gff
grep "DTA" data/results/all.noun.gff > data/results/all_dta.gff
grep "DTH" data/results/all.noun.gff > data/results/all_dth.gff
grep "DTX" data/results/all.noun.gff > data/results/all_dtx.gff
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all.noun.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_rlc.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_rlx.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_rlg.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_dtm.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_dtc.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_dtt.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_dta.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_dth.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_dtx.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_trim.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_line.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_sine.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_mite.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_lard.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_ltr.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_helitron.gff >> data/results/coverage.txt
python gff2coverage.py -r data/Stuberosum_genome.gff3 -a data/results/all_tir.gff >> data/results/coverage.txt
<file_sep>/3.2_blast_filter.py
# coding: utf-8
# In[14]:
import pandas as pd
from itertools import cycle
path_blast = '/home/diego/Documents/INTA/TE_papa/PCRE-D-20-00116/TRIM//'
te_type = 'TRIM'
print('Running for', te_type)
# In[26]:
#TEs
params = {}
params['LTR'] = {'min_len':650,'max_len':False,'min_distance':5,'max_q':1.5,'min_q':0.5,'min_pident':80,'min_qcov':40,'file':'blast_clustered_ltr.csv'}
params['LINE'] = {'min_len':1500,'max_len':False,'min_distance':5,'max_q':1.2,'min_q':0.8,'min_pident':80,'min_qcov':80,'file':'blast_clustered_line.csv'}
params['SINE'] = {'min_len':150,'max_len':800,'min_distance':5,'max_q':1.1,'min_q':0.9,'min_pident':90,'min_qcov':90,'file':'blast_clustered_sine.csv'}
params['TIR'] = {'min_len':500,'max_len':False,'min_distance':5,'max_q':1.1,'min_q':0.9,'min_pident':90,'min_qcov':90,'file':'blast_clustered_tir.csv'}
params['MITE'] = {'min_len':50,'max_len':800,'min_distance':5,'max_q':1.15,'min_q':0.85,'min_pident':90,'min_qcov':90,'file':'blast_clustered_mite.csv'}
params['LARD'] = {'min_len':50,'max_len':800,'min_distance':5,'max_q':1.15,'min_q':0.85,'min_pident':90,'min_qcov':90,'file':'blast_clustered_lard.csv'}
params['TRIM'] = {'min_len':600,'max_len':False,'min_distance':5,'max_q':1.1,'min_q':0.9,'min_pident':90,'min_qcov':90,'file':'blast_clustered_trim_TRF_filtered.csv'}
params['helitron'] = {'min_len':2000,'max_len':False,'min_distance':5,'max_q':1.2,'min_q':0.8,'min_pident':80,'min_qcov':80,'file':'blast_clustered_helitron.csv'}
#select which TE type you want to run
# In[39]:
#read blast output
df = pd.read_csv(path_blast + params[te_type]['file'], sep='\t', header=None)
df.columns = ['qseqid','sseqid','qstart','qend','sstart','send','score','length','mismatch','gaps','gapopen','nident','pident','qlen','slen','qcovs']
print('initial:',len(df.index))
# In[40]:
#filter by length
if(params[te_type]['min_len']):
df = df[df.qlen > params[te_type]['min_len']]
print('Min len: ' + str(len(df.index)))
# In[41]:
if(params[te_type]['max_len']):
df = df[df.qlen < params[te_type]['max_len']]
print('Max len: ' + str(len(df.index)))
# In[42]:
#filter by query / subject length treshold
df = df[((df.length / df.qlen) >= params[te_type]['min_q'])]
print('min treshold:',len(df.index))
# In[43]:
df = df[((df.length / df.qlen) <= params[te_type]['max_q'])]
print('max treshold:',len(df.index))
# In[44]:
#filter by pident
df = df[(df.pident >= params[te_type]['min_pident'])]
print('Min_pident: ' + str(len(df.index)))
# In[45]:
#filter by qcov
df = df[(df.qcovs >= params[te_type]['min_qcov'])]
print('Min qcov: ' + str(len(df.index)))
# In[46]:
#order sstart and send
df['new_sstart'] = df[['sstart','send']].min(axis=1)
df['new_ssend'] = df[['sstart','send']].max(axis=1)
df['sstart'] = df['new_sstart']
df['send'] = df['new_ssend']
df = df.drop('new_sstart',axis=1).drop('new_ssend',axis=1)
# sep by chr
dfs = {}
for seq in df.sseqid.unique():
dfs[seq] = df[df.sseqid == seq]
# In[ ]:
# filter overlapped
rows = []
discard = []
total = len(df.index)
count = 0
curr = 0
for index, row in df.iterrows():
count += 1
curr_new = int(count * 100 * 1.0 / (total * 1.0))
if curr_new != curr:
curr = curr_new
if curr_new % 10 == 0:
print(curr_new)
if index in discard:
continue
df_2 = dfs[row.sseqid]
res = df_2[(abs(df_2.sstart - row.sstart) <= params[te_type]['min_distance']) | (abs(df_2.send - row.send) <= params[te_type]['min_distance'])]
if len(res.index) > 1:
discard.extend(res.index.values)
rows.append(row)
# In[ ]:
df = pd.DataFrame(rows)
df.sort_values(['sseqid', 'sstart'], inplace=True)
print('Non overlapped: ' + str(len(df.index)))
# In[ ]:
filename = path_blast + params[te_type]['file'] + '.filtered'
df.to_csv(filename, index=None, sep='\t')
filename
<file_sep>/requirements.txt
jupyterlab==0.35.4
biopython==1.70
pandas==0.19.0<file_sep>/2.1_vsearch.sh
mkdir data/results
rm -r data/results/clusters_line/ 2> /dev/null
mkdir data/results/clusters_line/
rm -r data/results/clusters_sine/ 2> /dev/null
mkdir data/results/clusters_sine/
rm -r data/results/clusters_mite/ 2> /dev/null
mkdir data/results/clusters_mite/
rm -r data/results/clusters_ltr/ 2> /dev/null
mkdir data/results/clusters_ltr/
rm -r data/results/clusters_helitron/ 2> /dev/null
mkdir data/results/clusters_helitron/
rm -r data/results/clusters_tir/ 2> /dev/null
mkdir data/results/clusters_tir/
rm -r data/results/clusters_trim/ 2> /dev/null
mkdir data/results/clusters_trim/
rm -r data/results/clusters_lard/ 2> /dev/null
mkdir data/results/clusters_lard/
#LINEs
grep ">" data/results/seqs_line.fasta | wc -l
nohup ./sw/vsearch-2.9.1/bin/vsearch --cluster_fast data/results/seqs_line.fasta --threads 2 --strand both --clusters data/results/clusters_line/c --iddef 1 -id 0.9 &
#TIRs
grep ">" data/results/seqs_tir.fasta | wc -l
nohup ./sw/vsearch-2.9.1/bin/vsearch --cluster_fast data/results/seqs_tir.fasta --threads 2 --strand both --clusters data/results/clusters_tir/c --iddef 1 -id 0.9 &
#SINEs
grep ">" data/results/seqs_sine.fasta | wc -l
nohup ./sw/vsearch-2.9.1/bin/vsearch --cluster_fast data/results/seqs_sine.fasta --threads 2 --strand both --clusters data/results/clusters_sine/c --iddef 1 -id 0.9 &
#LTRs
grep ">" data/results/seqs_ltr.fasta | wc -l
nohup ./sw/vsearch-2.9.1/bin/vsearch --cluster_fast data/results/seqs_ltr.fasta --threads 2 --strand both --clusters data/results/clusters_ltr/c --iddef 1 -id 0.9 &
#Helitrons
grep ">" data/results/seqs_helitron.fasta | wc -l
nohup ./sw/vsearch-2.9.1/bin/vsearch --cluster_fast data/results/seqs_helitron.fasta --threads 2 --strand both --clusters data/results/clusters_helitron/c --iddef 1 -id 0.9 &
#TIRs
grep ">" data/results/seqs_tir.fasta | wc -l
nohup ./sw/vsearch-2.9.1/bin/vsearch --cluster_fast data/results/seqs_tir.fasta --threads 2 --strand both --clusters data/results/clusters_tir/c --iddef 1 -id 0.9 &
#LARDs
grep ">" data/results/seqs_lard.fasta | wc -l
nohup ./sw/vsearch-2.9.1/bin/vsearch --cluster_fast data/results/seqs_lard.fasta --threads 2 --strand both --clusters data/results/clusters_lard/c --iddef 1 -id 0.9 &
#TRIMs
grep ">" data/results/seqs_trim.fasta | wc -l
nohup ./sw/vsearch-2.9.1/bin/vsearch --cluster_fast data/results/seqs_trim.fasta --threads 2 --strand both --clusters data/results/clusters_trim/c --iddef 1 -id 0.9 &
#MITEs
grep ">" data/results/seqs_mite.fasta | wc -l
nohup ./sw/vsearch-2.9.1/bin/vsearch --cluster_fast data/results/seqs_mite.fasta --threads 2 --strand both --clusters data/results/clusters_mite/c --iddef 1 -id 0.9 &
cd data/results
tar -zcvf clusters_ltr.tar.gz clusters_ltr/
tar -zcvf clusters_mite.tar.gz clusters_mite/
tar -zcvf clusters_line.tar.gz clusters_line/
tar -zcvf clusters_trim.tar.gz clusters_trim/
tar -zcvf clusters_helitron.tar.gz clusters_helitron/
tar -zcvf clusters_lard.tar.gz clusters_lard/
tar -zcvf clusters_sine.tar.gz clusters_sine/
tar -zcvf clusters_tir.tar.gz clusters_tir/
<file_sep>/gff2coverage.py
import pandas as pd
def gff2coverage(annotations, reference):
print('Calculating coverage for %s in %s' % (annotations, reference,))
df_ann = pd.read_csv(annotations, index_col=False, sep='\t', header=None, comment='#')
df_ann.columns = ['seqname', 'source', 'feature', 'start', 'end', 'score', 'strand', 'frame', 'attribute']
df_ref = pd.read_csv(reference, index_col=False, sep='\t', header=None, comment='#')
df_ref.columns = ['seqname', 'source', 'feature', 'start', 'end', 'score', 'strand', 'frame', 'attribute']
total = {}
for k, v in df_ref.iterrows():
total[v.seqname] = v.end
overlapped = {}
for k, v in df_ann.iterrows():
overlapped.setdefault(v.seqname, []).append((v.start, v.end))
sequences = df_ref.seqname.unique().tolist()
for seqname in sequences:
if not seqname in overlapped:
continue
overlapped[seqname] = merge_overlap(overlapped[seqname])
gran_total_length = 0
gran_ref_length = 0
for seqname in sequences:
current_ref = df_ref[(df_ref.seqname == seqname)].iloc[0]
ref_len = abs(current_ref.end - current_ref.start)
gran_ref_length += ref_len
if not seqname in overlapped:
continue
current = overlapped[seqname]
total_length = 0
for (start, end) in current:
total_length += abs(end - start)
perc = total_length * 100.0 / ref_len
gran_total_length += total_length
print('seqname %s len: %s covered: %s percentage: %f ' % (seqname, ref_len, total_length, perc,))
gran_perc = gran_total_length * 100.0 / gran_ref_length
print('Total len: %s covered: %s percentage: %f ' % (gran_ref_length, gran_total_length, gran_perc,))
def calc_coverage_part(df_ann, ref_len):
seqs = []
for k, v in df_ann.iterrows():
seqs.append((v.start, v.end))
seqs_non_overlapped = merge_overlap(seqs)
total_length = 0
for (start, end) in seqs_non_overlapped:
total_length += abs(end - start)
perc = total_length * 100.0 / ref_len
return perc
def merge_overlap(intervals):
sorted_by_lower_bound = sorted(intervals, key=lambda tup: tup[0])
merged = []
for higher in sorted_by_lower_bound:
if not merged:
merged.append(higher)
else:
lower = merged[-1]
# test for intersection between lower and higher:
# we know via sorting that lower[0] <= higher[0]
if higher[0] <= lower[1]:
upper_bound = max(lower[1], higher[1])
merged[-1] = (lower[0], upper_bound) # replace by merged interval
else:
merged.append(higher)
return merged
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser() # pylint: disable=invalid-name
parser.add_argument("-a", "--annotation", help="Annotation file (.gff3 format)", required=True)
parser.add_argument("-r", "--reference", help="Reference genome file (.gff3 format)", required=True)
args = parser.parse_args() # pylint: disable=invalid-name
gff2coverage(args.annotation, args.reference)
<file_sep>/7.2_age.R
install.packages("devtools")
library(devtools)
devtools::install_github('TickingClock1992/RIdeogram')
require(RIdeogram)
setwd("/Users/juan/Documents/manu/dev/vms/bio/TEs_papa/data")
#data(human_karyotype, package="RIdeogram")
data(gene_density, package="RIdeogram")
#data(Random_RNAs_500, package="RIdeogram")
potato_karyotype <- read.table("karyotype.csv",sep="\t", header = T, stringsAsFactors = F)
potato_karyotype$CE_start = potato_karyotype$CE_start - 1000000
potato_karyotype$CE_end = potato_karyotype$CE_end + 1000000
head(potato_karyotype)
potato_gene_density <- read.table("lrx_ages.csv", sep = "\t", header = T, stringsAsFactors = F)
nrow(potato_gene_density)
head(potato_gene_density)
potato_gene_density = potato_gene_density[complete.cases(potato_gene_density), ]
nrow(potato_gene_density)
head(potato_gene_density)
ideogram(karyotype = potato_karyotype, overlaid = potato_gene_density)
convertSVG("chromosome.svg", device = "png")
| 2ce6f630d0b344f5bf9a09c4827015ed732b7f29 | [
"Markdown",
"Python",
"Text",
"R",
"Shell"
] | 8 | R | DiegoZavallo/TE_Discovery | 93d63d562bb8b798f096185efb9c972c09510f9e | 6399aa375afed9090b3f9e50db112888ac1c728f |
refs/heads/master | <file_sep>import React from 'react';
import './style.css';
const Footer = () => {
return (
<div className="footer">
<p class="footertext">When the need for better results overcomes the fear of change, we can help.</p>
<a href="https://twitter.com/artemissearch" target="blank"><img src="assets/social_icons/twitter-icon-artemis.png" class="icon"/></a>
<a href="https://www.facebook.com/artemissearchgroup/" target="blank"><img src="assets/social_icons/facebook-icon-artemis.png" class="icon"/></a>
<a href="https://www.linkedin.com/company/artemis-search-group-inc./" target="blank"><img src="assets/social_icons/linkedin-icon-artemis.png" class="icon"/></a>
<a href="mailto:<EMAIL>"><img src="assets/social_icons/email-icon-artemis.png" class="icon"/></a>
<p class="call">Call Artemis Search Group today! (248)499-8001</p>
</div>
);
}
export default Footer;<file_sep>import IndexPage from './IndexPage';
export default IndexPage<file_sep>import RecruitPage from './RecruitPage';
export default RecruitPage;<file_sep>import React, { Component } from "react";
import "./style.css";
// import { toElement as scrollToElement } from "../../utils/scroll";
// class RecruitPage extends Component {
// scrollToPage = pageSelector => {
// const nextPage = document.querySelector(pageSelector);
// scrollToElement(nextPage);
// };
// render() {
const RecruitPage = () => {
return (
<div className="recruit-page">
<h1>Recruiting Solutions</h1>
<h5>Executive Search</h5>
<h3>"Don't expect tactics to solve a strategic problem."</h3>
<p className="paragraph">
This mantra drives our day to day activity on behalf of our clients.
Artemis Search Group continues to deliver on critical personnel needs
for distinct and key reasons:{" "}
</p>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>
We are selective in our client relationships and are experts in their
industries.
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>
We are methodical in applying our process.
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>
We work directly with executive leadership to understand the metrics
of long-term excellent performance.
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>
We encourage clients to seek aspects of: Fit, Character and
Performance, as these are the true indicators of success.
</li>
<h5>Critical Questions regarding your talent brand.</h5>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>
Do you currently have a resume key-word search tool driving your
hiring inputs?
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>
Are YOUR top performers looking for work on The Job Boards? Why would
you assume this of your competitor’s top performers?
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>
Are the qualities that define your strongest player, visible on their
resume?
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>
When you were forced to make a personnel change, were the flaws in
that team member found on their resume?
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>
Is your talent team telling you that there is a skill-set shortage?
</li>
<h5>Our Process</h5>
<p className="paragraph">
Artemis Search Group has an uncommon perspective on recruiting and
talent acquisition. We work directly with organizational leadership as
Opportunity Sales Agents (OSA). We actively represent outstanding
opportunities within vibrant, growing organizations to the highest
performing industry professionals.
</p>
<li>
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>
Conduct Opportunity design consulting with PARTNER.
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Identify Opportunity Sales Team Champion
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Develop firm project timeline and pre-arrange dates with team
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Develop firm project timeline and pre-arrange dates with team
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Develop firm project timeline and pre-arrange dates with team
</li>
<li>
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Develop in-depth understanding of Opportunity performance criteria
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Develop Opportunity Summary and verbal brochure with PARTNER
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Discuss competitors, associated value-chain(s), jointly identify
possible candidates
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Identify and attract targeted professionals
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Conduct in-depth interviews utilizing behavioral based interviewing
techniques
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Present most committed professionals to PARTNER for arranged
interviews
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Consult with candidate(s) prior to interview
</li>
<li>
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Consult with PARTNER prior to interview
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Close candidate on offer acceptance threshold
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Counsel candidate on perils of counteroffer/minimize PARTNER
vulnerability
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Simultaneous offer extension and acceptance gaining start date
commitment
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Assist candidate with completing all pre-employment contingencies
</li>
<li>
{" "}
<img
src="assets/images/artemisbullet.png"
className="bullet"
width="18px"
height="18px"
/>{" "}
Follow-up with PARTNER and candidate on and after start date
</li>
<p className="paragraph">
{" "}
Skilled executives and trained business development professionals may
see striking similarity to a formalized sales process. If you
recognized this, you are our type of Partner. Artemis Search Group
distinguishes itself from the competition with this philosophical
perspective. We outshine our competitors because our process mirrors
this belief system. If your Talent Acquisition Process hasn’t been the
vanguard of your sales effort, you are missing opportunity to grow
your organization. Let us show you how! We won’t let you down. Let’s
get to work!
</p>
<h1>Recruitment Process In-sourcing</h1>
<h3>Recapture and Revitalize your Talent Brand with our RPI Offering</h3>
<p>The trend toward recruitment process outsourcing (RPO) has
succeeded in masking truth of the talent acquisition processes
by leveraging the inherent weaknesses of traditional talent
acquisition metrics. The damage you may be doing to your talent brand and the
long-term damage to your cultural sustainment or transformation
efforts could be catastrophic.</p>
<h4>When evaluating your talent strategy what are your desired
outcomes?</h4>
<ul className="list1">
<li>Cost Savings</li>
<li>Speed</li>
<li>Compliance</li>
<li>Quality</li>
</ul>
<h4>This viewpoint sets-up the classic and unnecessary conflict between:</h4>
<p>Human Resources vs Procurement vs Operations</p>
<h4>Break out of this thinking model.</h4>
<h3>Has it reduced third party spending? No!</h3>
<p>RPO merely consolidates the same or often greater
total spend under the RPO provider, a handful special vendors,
and The BIG BOYS when it comes to executive and board member hire.</p>
<h3>Has it increased speed of hire? No!</h3>
<p>The RPO process merely consolidates the limited sources
of inputs (resumes). Therefore, the quality of the inputs
hasn't increased nor has the screen through which the inputs
are sorted. Moreover, the hiring process, now being administered
by an outsourced supplier, hasn't changed at all. How could this possibly
increase the speed of hire? And is speed really what you are after?</p>
<h3>Has it increased compliance or enhanced corporate culture? Maybe?</h3>
<p>RPO, in reality, has merely matrixed the responsibility of compliance to the RPO provider. RPO has merely outsourced compliance to an auditable line-item on the invoice remitted from the RPO provider.</p>
<h3>Has it increased the quality of your hires?</h3>
<p>Here is where the rubber really meets the road. Were your hires poor before the choice to move to RPO? Are they better now? Based on what criteria?</p>
<h4>Don't expect tactics to solve a strategic problem.</h4>
<li>Does the CEO feel acquiring and retaining talent is a problem?</li>
<li>Who is accountable to solve this problem?</li>
<li>Does the solution have a budget fitting the size of the problem?</li>
<h4>Interested in taking control of your talent brand? Interested in hearing more about recruitment process insourcing? (RPI)
We can help! Call Artemis Search Group today! <br/>(248)499-8001</h4>
<h1>Hire A Veteran</h1>
<p>Artemis Search Group, Inc is passionate about helping our transitioning service men and women. We are committed to bringing our clients and our heroes together to continue the mission - keeping Americans safe by keeping the American economy strong. Ask us about hiring a transitioning service member or industry experienced service member. 100% of clients hiring a former uniformed service member from Artemis Search Group, hired another within 1 year.</p>
<img src="assets/images/aerospace.jpg" className="vetpic"></img>
</div>
);
}
// }
// }
export default RecruitPage;
<file_sep>import React from "react";
import "./style.css";
import Nav from "../../components/Nav";
// <EMAIL>
// ThirdWell!
const ContactPage = () => {
return (
<div className="contact-page">
<h1>Contact Us</h1>
<p className="quote">
There is nothing else than now. There is neither yesterday, certainly,
nor is there any tomorrow. How old must you be before you know that?"
</p>
<p className="ernest">-<NAME></p>
<p>
We are very interested in hearing from you! If you are exploring options
for better opportunities or you are looking for new solutions to today's
team building realities, we can help! Always error on the side of
action!
</p>
<form
className="form"
action="//formspree.io/<EMAIL>"
method="POST"
>
<input
className="email"
type="text"
name="_replyto"
placeholder="Email"
/>
<input
className="company"
type="text"
name="company"
placeholder="Company"
/>
<input className="title" type="text" name="title" placeholder="Title" />
<input
className="firstname"
type="text"
name="firstname"
placeholder="First Name"
/>
<input
className="lastname"
type="text"
name="lastname"
placeholder="<NAME>"
/>
<input
className="address"
type="text"
name="address"
placeholder="Address"
/>
<input className="city" type="text" name="city" placeholder="City" />
<div className="selection">
<select className="state" name="state">
<option value="State">State</option>
<option value="AL">AL</option>
<option value="AK">AK</option>
<option value="AZ">AZ</option>
<option value="AR">AR</option>
<option value="CA">CA</option>
<option value="CO">CO</option>
<option value="CT">CT</option>
<option value="DE">DE</option>
<option value="FL">FL</option>
<option value="GA">GA</option>
<option value="HI">HI</option>
<option value="ID">ID</option>
<option value="IL">IL</option>
<option value="IN">IN</option>
<option value="IA">IA</option>
<option value="KS">KS</option>
<option value="KY">KY</option>
<option value="LA">LA</option>
<option value="ME">ME</option>
<option value="MA">MA</option>
<option value="MI">MI</option>
<option value="MN">MN</option>
<option value="MS">MS</option>
<option value="MO">MO</option>
<option value="MT">MT</option>
<option value="NE">NE</option>
<option value="NV">NV</option>
<option value="NH">NH</option>
<option value="NJ">NJ</option>
<option value="NM">NM</option>
<option value="NY">NY</option>
<option value="NC">NC</option>
<option value="ND">ND</option>
<option value="OH">OH</option>
<option value="OK">OK</option>
<option value="OR">OR</option>
<option value="PA">PA</option>
<option value="RI">RI</option>
<option value="SC">SC</option>
<option value="SD">SD</option>
<option value="TN">TN</option>
<option value="TX">TX</option>
<option value="UT">UT</option>
<option value="VT">VT</option>
<option value="VA">VA</option>
<option value="WA">WA</option>
<option value="WV">WV</option>
<option value="WY">WY</option>
</select>
</div>
<input className="zip" type="text" name="zip" placeholder="zip" />
<input className="phone" type="text" name="phone" placeholder="Phone" />
<input
className="industry"
type="text"
name="industry"
placeholder="Industry"
/>
<textarea className="comments" name="comments" placeholder="Comments" />
<input className="submit" type="submit" value="Send" />
<input type="hidden" name="_subject" value="New submission!" />
</form>
</div>
);
};
export default ContactPage;
<file_sep>import React from 'react';
import './style.css';
import Nav from '../../components/Nav';
const IndustryPage = () => {
return (
<div className="industry-page">
<div id="tiptop">
<h1 className="title">Industry Expertise</h1>
<div id="links">
<a href="#defense" className="pagelink">Defense</a>
<a href="#automotive" className="pagelink">Automotive</a>
<a href="#materials" className="pagelink">Advanced Materials</a>
<a href="#building"className="pagelink">Building Materials</a>
<a href="#aerospace"className="pagelink2">Aerospace</a>
</div>
</div>
<p>Artemis Search Group has developed extensive relationships with manufacturing leaders of
small and mid-market tier suppliers. We specialize in delivering on senior leadership
engagements within the fastest growing areas of industry.</p>
<div id="defense" className="industry">
<h1>Defense</h1>
<img src="assets/images/defense.jpg" className="industrypic"></img>
<p>The unique aspects of the US and International defense sector present specific challenges when
it comes to identifying talent. We understand mission critical requirements and speak the
language of government acquisition. We serve those who protect our warfighters and security
personnel.</p>
<a href="#tiptop" className="top">top</a>
</div>
<div id="automotive" className="industry">
<h1>Automotive</h1>
<img src="assets/images/automotive.jpg" className="industrypic"></img>
<p>We excel in the ultra-competitive automotive tier supply world. If you need expertise in your
engineering, operations, quality, program management, product management, continuous
improvement or sales functions, we can help. Our depth of experience within powertrain,
torque conversion, injection and compression molding, stamping, energy storage and composite
applications allow us to serve a wide portion of the industry.</p>
<a href="#tiptop" className="top">top</a>
</div>
<div id="materials" className="industry">
<h1>Advanced Materials</h1>
<img src="assets/images/materials.jpg" className="industrypic"></img>
<p>This rapidly expanding group of material solutions may be the fastest growing segment of
American and global industry. It is the thread of continuity that runs through our firm. We are
composite experts! If your need is carbon fiber, thermoplastic, thermoset, FRP, TFL, or even
raw material, we are the ones the call. We are deeply embedded within the world of advanced
composite applications for structural aerospace, specialty vehicle, wind energy, RV, off-
highway, and architectural/designed interiors. We are strongly tied to life-saving application
providers of armor and survivability solutions. Bottom line, if you are involved with composites
we can help you.</p>
<a href="#tiptop" className="top">top</a>
</div>
<div id="building" className="industry">
<h1>Building Materials</h1>
<img src="assets/images/buildingmaterials.jpg" className="industrypic"></img>
<p>Our building and construction materials practice clients fall predominantly into two categories.
With decades of direct experience with manufacturers of architecturally/specified interior
products (CSI: 08, 09, 10, 12) and materials (CSI: 03, 04, 05, 06) product classifications. We
have worked with commercial and residential product manufacturers as well as the two-step
distributors of materials, consumables, hardware and MRO products. If your tradesman
need it or if your architect or designer has specified it, we have most likely worked with the
manufacturer. We can help!</p>
<a href="#tiptop" className="top">top</a>
</div>
<div id="aerospace" className="industry">
<h1>Aerospace</h1>
<img src="assets/images/aerospace.jpg" className="industrypic"></img>
<p>Our depth of knowledge extends to both fixed wing or rotary wing aircraft for defense, security
forces or commercial applications. We are particularly experienced with structural composites,
survivability solutions, stampings, machined parts and fabricated metals.</p>
<a href="#tiptop" className="top">top</a>
</div>
</div>
);
}
export default IndustryPage;<file_sep>import IndustryPage from './IndustryPage';
export default IndustryPage; | e9e291896f9a62db975f7dd0b6050ca116a0e37c | [
"JavaScript"
] | 7 | JavaScript | morganmcpeak/artemis2 | 112946b5b31eec69154b6981bec7668b45ef1703 | 0c62939dbaec146937eae661cfa1dfc99b5f776d |
refs/heads/master | <file_sep><?php
include_once 'business.class.php';
$datoscrudos = file_get_contents("php://input"); //Leemos los datos
$datos = json_decode($datoscrudos);
$lista = DB::getDataSecureLike('%'.$datos->Buscar.'%',$datos->Opciones);
for ($i = 0; $i < count($lista); $i++) {
$lista[$i]['imagen'] = base64_encode($lista[$i]['imagen']);
}
header('Content-type: application/json');
echo json_encode($lista);
?><file_sep><?php
include_once 'business.class.php';
class View{
public static function start($title){
$html = "<!DOCTYPE html>
<html>
<head>
<meta charset=\"utf-8\">
<script src=\"scripts.js\"></script>
<script src=\"//code.jquery.com/jquery-1.11.1.min.js\"></script>
<title>$title</title>";
User::session_start();
echo $html;
}
public static function navigation(array $links){
echo "<nav id=\"navigation\">";
foreach (array_keys($links) as $link) {
echo "<a href=$link>$links[$link]</a>";
}
echo "</nav>";
}
public static function style(array $styles){
foreach ($styles as $s) {
echo "<link rel=\"stylesheet\" type=\"text/css\" href=$s>";
}
}
public static function LibreriaDeIconos(){
echo "<link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\"
integrity=\"<KEY> crossorigin=\"anonymous\">";
}
public static function closeHead(){
echo "</head>
<body>";
}
public static function createHeader($title){
echo "<header><h1><span class=\"title\">$title</span></h1></header>";
}
public static function createHeaderIndex(){
echo "<header><h1>GCShop</h1></header>";
}
public static function end(){
echo '</body>
</html>';
}
public static function LogInform(){
print <<<Formulario
<main>
<div id="body">
<div class="row">
<div class="card">
<form id="loginUser" action="script_login.php" method="post">
<fieldset>
<legend>Sign in Gshop</legend>
<label>Usuario: </label>
<input type="text" name="usuario"><br>
<label>Password:</label>
<input type="<PASSWORD>" name="<PASSWORD>"><br>
<input type="submit" value="Log In" name="SingIn">
</fieldset>
</form>
</div>
</div>
</div>
</main>
Formulario;
}
public static function LogOut(){
$datos=User::getLoggedUser();
switch ($datos['tipo']) {
case 1:
$tipo = "Administrador";
break;
case 2:
$tipo = "Gestor";
break;
case 3:
$tipo = "Repartidor";
break;
case 4:
$tipo = "Cliente";
break;
case 5:
$tipo = "Provedor";
break;
}
echo "
<main>
<div id='body'>
<div class='row'>
<div class='card'>
<h2>Bienvenido {$datos['cuenta']}</h2>
<h3>Información:</h3>
<table>
<tr class='cabecera'>
<th>Nombre</th>
<th>Tipo</th>
<th>Email</th>
<th>Población</th>
<th>Dirección</th>
<th>Teléfono</th>
</tr>
<tr>
<td>{$datos['nombre']}</td>
<td>$tipo</td>
<td>{$datos['email']}</td>
<td>{$datos['poblacion']}</td>
<td>{$datos['direccion']}</td>
<td>{$datos['telefono']}</td>
</tr>
</table>";
print<<<Formulario
<form action="script_login.php" method="post">
<input type="submit" value="Log Out" name="SingOut">
</form>
</div>
</div>
</div>
</main>
Formulario;
}
public static function cesta(){
echo "<main>";
if(isset($_SESSION['bag']) and count($_SESSION['bag']) > 0){
echo '<div id="body">
<div class="row">
<div class="card">
<table>';
print<<<Enc
<tr>
<th>Producto</th>
<th>Tipo</th>
<th>Cantidad</th>
<th>Eliminar</th>
</tr>
Enc;
foreach ($_SESSION['bag'] as $key=>$value) {
$datos=DB::getAnyDataQuery("nombre,tipo", "productos", "where id=$key");
echo "<tr>";
echo "<td>{$datos[0]['nombre']}</td>";
echo "<td>{$datos[0]['tipo']}</td>";
echo "<td>$value unidades</td>";
echo "<td>
<form action=\"cesta.php?id=$key\" method=\"post\">
<input type=\"number\" name=\"cantidad\" min=\"1\" max=\"$value\">
<input type=\"submit\" value=\"Eliminar\" name=\"Eliminar\">
</form></td>";
echo "</tr>";
}
echo "</table>
</div>
</div>
</div>";
if(User::getLoggedUser() and count($_SESSION['bag']) > 0){
print<<<Formulario
<form id="compra" action="pago.php?metodo=1" method="post">
<input type="submit" value="Comprar" name="comparar">
</form>
Formulario;
}
} else {
echo '<div id="body">
<div class="row">
<div class="card">';
echo "<h2>La cesta está vacía ";
echo "<i class=\"fas fa-cart-arrow-down\"></i></h2>
</div>
</div>
</div>";
}
echo "</main>";
}
public static function gestorArticulosLista(array $productos){
echo "<main>
<div id='body'>
<div class='row'>
<div class='card'>";
echo "<ul>";
foreach ($productos as $value) {
echo "<li><a href=\"gestor.php?tipo=producto&id={$value['id']}\">{$value['nombre']}</a></li><br>";
}
echo "</ul>";
}
public static function gestorBotonAñadir(){
print<<<Formulario
<form action="gestor.php?tipo=añadir" method="post">
<input type="submit" value="Añadir Producto">
</form>
Formulario;
echo "</div>
</div>
</div>
</main>";
}
public static function gestorAñadir(){
print<<<Form
<main>
<div id='body'>
<div class='row'>
<div class='card'>
<form id="form" action="script_gestorAñadir.php" method="post" enctype="multipart/form-data" onSubmit="return validateForm();">
<label>Nombre:</label><p id="warningName"></p><br>
<input type="text" id="nombre" name="nombre"><br><br>
<label>Código:</label><p id="warningCode"></p><br>
<input type="text" id="codigo" name="codigo"><br><br>
<label>Tipo:</label><p id="warningType"></p><br>
<input type="text" id="tipo" name="tipo"><br><br>
<label>Precio:</label><p id="warningPrice"></p><br>
<input type="number" width="10" placeholder="1.0" step="0.01" id="precio" name="precio"><br><br>
<label>Stock:</label><p id="warningStock"></p><br>
<input type="number" id="stock" name="stock" value="0"><br><br>
<label>Descripción:</label><p id="warningDescription"></p><br>
<input type="text" id="descripcion" name="descripcion"><br><br>
<label for="imagen">Seleciona una imagen:</label><p id="warningFile"></p><br>
<input type="file" id="imagen" name="imagen" size="20"><br><br>
<input type="submit" name="add" value="Añadir">
</form>
</div>
</div>
</div>
</main>
Form;
}
public static function gestorModificar(array $producto){
$imgb64 = base64_encode($producto[0]["imagen"]);
echo"
<main>
<div id='body'>
<div class='row'>
<div class='card'>
<form action=\"script_gestorModificar.php?id={$producto[0]['id']}\"method=\"post\" enctype=\"multipart/form-data\" onSubmit=\"return validateForm();\">
<label>Nombre:</label><p id=\"warningName\"></p><br>
<input type=\"text\" id=\"nombre\"name=\"nombre\" value=\"{$producto[0]['nombre']}\"><br><br>
<label>Código:</label><p id=\"warningCode\"></p><br>
<input type=\"text\" id=\"codigo\" name=\"codigo\" value={$producto[0]['codigo']}><br><br>
<label>Tipo:</label><p id=\"warningType\"></p><br>
<input type=\"text\" id=\"tipo\" name=\"tipo\" value={$producto[0]['tipo']}><br><br>
<label>Precio:</label><p id=\"warningPrice\"></p><br>
<input type=\"number\" id=\"precio\" name=\"precio\" placeholder=\"1.0\"
step=\"0.01\" value={$producto[0]['precio']}><br><br>
<label>Stock:</label><p id=\"warningStock\"></p><br>
<input type=\"number\" id=\"stock\" name=\"stock\" value={$producto[0]['stock']}><br><br>
<label>Descripción:</label><p id=\"warningDescription\"></p><br>
<input type=\"text\" id=\"descripcion\" name=\"descripcion\" value=\"{$producto[0]['descripcion']}\"><br><br>
<lable>Imagen Actual:</label><br>
<input type=\"image\" src=\"data:image/jpeg;base64,$imgb64\"
alt=\"Supuesta imagen del producto\"><br><br>
<label for=\"imagen\">Seleciona una nueva imagen:</label><p id=\"warningFile\"></p><br>
<input type=\"file\" id=\"imagen\" name=\"imagen\" size=\"20\"><br><br>
<input type=\"submit\" value=\"Modificar\" name=\"Modificar\">
</form>
</div>
</div>
</div>
</main>
";
}
public static function BuscadorMain(){
print <<<Main
<main>
<div id="body">
<div class="row">
<div class="search">
<div class="card">
<span class="icon"><i class="fa fa-search"></i></span>
<input type="search" id="search" placeholder="Search..." name="Buscar" onkeyup="setTimeout(search(),100)"/>
<select id="selector" name="Opciones">
<option value="nombre">Nombre</option>
<option value="tipo">Tipo</option>
</select>
</div>
</div>
Main;
}
public static function Buscador($like,$opcion){
$lista = DB::getDataSecureLike('%'.$like.'%', $opcion);
$html="";
foreach ($lista as $value) {
$imgb64 = base64_encode($value['imagen']);
$html.= "<div class=\"gallery\">";
$html.= "<a target=\"_blank\" href=\"productos.php?id={$value['id']}\">";
$html.= "<img src='data:image/jpeg;base64,$imgb64' alt=\"Forest\" width=\"600\" height=\"400\">";
$html.= "</a>";
$html.= "<div class=\"desc\">{$value['nombre']}</div>";
$html.= "</div>";
}
return $html;
}
public static function menuAdm(){
print <<<Menu
<main>
<div id="body">
<div class="row">
<div class="card">
<a href=informeAdm.php?tipo=ventas>Informe de Ventas</a>
</div>
<div class="card">
<a href=informeAdm.php?tipo=stock>Informe de Stock</a>
</div>
</div>
</div>
</main>
Menu;
}
public static function informeVentas(){
$lista = User::listaFacturas();
echo "<main>
<div id='body'>
<div class='row'>";
foreach ($lista as $value) {
echo "<div class='card'>";
$usuario=DB::getAnyDataQuery("nombre", "usuarios", "where id={$value['idcliente']}")[0]['nombre'];
echo "<h3>Cliente que solicitó el pedido: $usuario</h3>";
$producto=User::productoFactura($value['id']);
foreach ($producto as $i) {
$nombre=DB::getAnyDataQuery("nombre","productos","where id={$i['idproducto']}")[0]['nombre'];
echo "<ul>";
echo "<li>Producto: $nombre</li>";
echo "<li>Precio: {$i['precio']}</li>";
echo "<li>Unidades: {$i['unidades']}</li>";
echo "</ul><br>";
}
echo "<li>Dirección de entrega: {$value['direccionentrega']}</li>";
echo "<li>Repartidor: {$value['idrepartidor']}</li>";
$fecha=date('r',$value['fechaventa']);
echo "<li>Fecha de venta: $fecha</li>";
$fecha=date('r',$value['fechaentrega']);
echo "<li>Fecha de entrega: $fecha</li>";
echo "<li>Suma total: {$value['total']} €</li>";
echo "</ul>";
echo "</div>";
}
echo "</div>
</div>
</main>";
}
public static function productosStock(){
$lista=User::listaProductosStock();
echo "<main>
<div id='body'>
<div class='row'>";
foreach ($lista as $value) {
echo "<div class='card'>";
echo "<ul>";
echo "<li>Nombre: {$value['nombre']}</li>";
echo "<li>Tipo: {$value['tipo']}</li>";
echo "<li>Precio: {$value['precio']}€ por kilo</li>";
echo "<li><b>Stock</b>: {$value['stock']} unidades</li>";
echo "<li>{$value['descripcion']}</li>";
echo "<ul>";
echo "</div>";
}
$suma=User::sumaProductosStock();
echo "<div class='card'>
<h3>Valor total de venta: $suma €</h3>
</div>
</div>
</div>
</main>";
}
public static function listaProductos(array $datos, $id){
echo "<main>";
echo '<div id="body">
<div class="row">
<div class="leftProductColumn">
<div class="card">';
$imgb64 = base64_encode($datos[0]["imagen"]);
echo "<img class='fakeimg' src=\"data:image/jpeg;base64,$imgb64\">
</div>";
echo "<div class='card'>
<ul>";
$nombre = $datos[0]["nombre"];
$tipo=$datos[0]["tipo"];
$precio = $datos[0]["precio"];
$des = $datos[0]["descripcion"];
echo "<h2>Nombre del producto: ".$nombre."</h2>";
echo "<li>Tipo: $tipo</li>";
echo "<li>Precio: $precio € por kilo</li>";
echo "<li>$des</li>";
echo "</ul>
</div>
</div>";
echo "<div class='rightProductColumn'>
<div class='card'>
<div class=\"formulario\">
<fieldset>
<legend>Comprar ".$nombre."</legend>";
$stock=$datos[0]["stock"];
if ($stock == 0) {
echo '<div id="anuncio"><p>No disponemos de stock en estos momentos. Disculpe las molestias.</p></div>';
} else {
echo "<div id=\"anuncio\"><input type=\"number\" id=\"stock\" name=\"cantidad\" value=\"0\" min=\"1\" max=\"$stock\"><br><br>
<button type=\"button\" onclick=\"add($id)\" name=\"cesta\">Añadir a la cesta</button></div>
</fieldset>
</div>
</div>
</div>
</div>
</div>
</main>";
}
}
public static function mainIndex(){
echo '<main>
<div id="body">
<div class="row">
<div class="leftColumn">
<div class="card">
<img class="fakeimg" src="images/logoAvion.png" alt="Logotipo GCShop">
<h2>Bienvenido a GCShop, tu sitio ideal de shopping canario</h2>
<ul>
<li>Ventajas para los Clientes: Ofrecerle al cliente una
plataforma donde adquirir de manera fácil diferentes
productos.</li>
<li>Ventajas para las Empresas: GCShop es una plataforma
al por mayor que está a la entera disposición de
cualquier empresa que desee utilizar para la compra
de productos.</li>
<li>Ventajas para los Visitantes: Tener una página web para
comparar con otras además de un formulario de contacto
para enviar comentarios y dudas.</li>
</ul>
</div>
<div class="card">
<h2>¿De dónde proceden nuestros productos?</h2>
<h3>Gran Canaria</h3>
<p>Gran Canaria es conocida por sus playas de arena blanca y de lava negra. Al sur, destacan las bulliciosas playas del Inglés y de Puerto Rico, además de las playas más tranquilas de Puerto de Mogán y San Agustín. Al norte, la ciudad capitalina de Las Palmas es una parada principal para los cruceros y una zona de compras sin impuestos. El interior de la isla es rural y montañoso.</p>
<img class="fakeimgNoBorder" src="images/grancanaria.png" alt="Isla de Gran Canaria">
<h3>Tenerife</h3>
<p>La orografía montañosa es marca de la casa de Tenerife, lo que significa que podrías ir de punta a punta de la isla pasando únicamente de una montaña a otra sin más. Sin embargo, encuentras excepciones como los dos grandes valles de la isla: el de Güímar y el de La Orotava.</p>
<img class="fakeimgNoBorder" src="images/tenerife.png" alt="Isla de Tenerife">
<h3>Fuerteventura</h3>
<p>Es principalmente conocida como destino turístico debido a sus playas de arena blanca. También contribuyen sus temperaturas cálidas todo el año, que los vientos constantes ayudan a rebajar. Cuenta con una gran cantidad de playas que se intercalan con zonas de acantilados y ensenadas. Es una isla muy popular para practicar deportes acuáticos, como el surf, el windsurf y el esquí acuático.</p>
<img class="fakeimgNoBorder" src="images/fuerteventura.png" alt="Isla de Fuerteventura">
</div>
</div>
<div class="rightColumn">
<div class = "card">
<h2>Información</h2>
<p id="text1">
<b>GCShop</b> se dedica a la venta de productos por internet
para su entrega inmediata al cliente.Los productos se pueden
elegir entre un amplio abanico de productos de locales.
</p>
<img class="polaroid" src="logo.jpg" alt="Foto de nuestro logo">
</div>
</div>
</div>
</div>
</main>';
}
public static function cantidadPagar($suma){
echo"
<main>
<div id='body'>
<div class='row'>
<div class='card'>
<h2>Cantidad a pagar: $suma €</h2>
<h3>Puedes pagar vía PayPal o mediante tarjeta de crédito</h3>
<h3>No se aceptan devoluciones</h3>";
}
public static function pago(){
print<<<Pago
<form action="script_pago.php" method="post">
<fieldset>
Pago;
$datos=User::getLoggedUser();
echo "<label>Nombre:</label>";
echo "<input type=\"text\" name=\"nombre\" minlength=\"2\" value=\"{$datos['nombre']}\"><br><br>";
echo "<label>Cuenta:</label>";
echo "<input type=\"text\" name=\"cuenta\" minlength=\"2\" value=\"{$datos['cuenta']}\"><br><br>";
print<<<Pago
<select name="Opciones">
<option value="1">Tarjeta de crédito</option>
<option value="2">PayPal</option>
</select><br>
<input type="submit" value="Pagar" name="pagar"><br>
</fieldset>
</form>
</div>
</div>
</div>
</main>
Pago;
}
public static function pagoEfectivo(){
$datos=User::getLoggedUser();
echo "
<form action=\"script_pago.php\" method=\"post\">
<fieldset>
<label>Nombre:</label><br>
<input type=\"text\" name=\"nombre\" value=\"{$datos['nombre']}\"><br><br>
<label>Cuenta:</label><br>
<input type=\"text\" name=\"cuenta\" value=\"{$datos['cuenta']}\"><br><br>
<label>Calle:</label><br>
<input type=\"text\" name=\"calle\" value=\"{$datos['direccion']}\"><br><br>
<label>Teléfono:</label><br>
<input type=\"tel\" name=\"telefono\" value=\"{$datos['telefono']}\"><br><br>
<label>Cuenta PayPal:</label><br>
<input type=\"text\" name=\"paypal\"><br><br>
<label>Contraseña PayPal:</label><br>
<input type=\"password\" name=\"passsword\"><br><br>
<input type=\"submit\" value=\"Completar pago\" name=\"completarEfectivo\">
</fieldset>
</form>
</div>
</div>
</div>
</main>";
}
public static function pagoTarjeta(){
$datos=User::getLoggedUser();
echo "
<form action=\"script_pago.php\" method=\"post\">
<fieldset>
<label>Nombre:</label><br>
<input type=\"text\" name=\"nombre\" value=\"{$datos['nombre']}\"><br><br>
<label>Cuenta:</label><br>
<input type=\"text\" name=\"cuenta\" value=\"{$datos['cuenta']}\"><br><br>
<label>Calle:</label><br>
<input type=\"text\" name=\"calle\" value=\"{$datos['direccion']}\"><br><br>
<label>Teléfono:</label><br>
<input type=\"tel\" name=\"telefono\" value=\"{$datos['telefono']}\"><br><br>
<label>Número de tarjeta:</label><br>
<input type=\"text\" name=\"tarjeta\"><br><br>
<input type=\"submit\" value=\"Completar pago\" name=\"completarTarjeta\">
</fieldset>
</form>
</div>
</div>
</div>
</main>";
}
public static function mostrarTabla() {
echo "<div class='card'>
<div class=\"busqueda\"></div>
<table>
<tr class='cabecera'>
<th>Nombre</th>
<th>Precio</th>
<th>Imagen</th>
</tr>";
$datos = DB::getAnyRow("*","productos");
foreach($datos as $registro){
echo "<tr>";
echo "<td><a href='productos.php?id={$registro['id']}'>{$registro['nombre']}</a></td>";
echo "<td>{$registro['precio']} €</td>";
$imgb64 = base64_encode($registro['imagen']);
echo "<td><img class='fakeimg' src='data:image/jpeg;base64,$imgb64'></td>";
echo "</tr>";
}
echo "</table>
</div>
</div>
</div></main>";
}
}<file_sep><?php
include_once 'presentation.class.php';
View::start('GCShop Buscador');
View::LibreriaDeIconos();
View::style(array("estilos.css"));
View::closeHead();
View::createHeader("Buscador de Productos");
if(User::getLoggedUser()){
View::navigation(array("index.php" => "Volver al Inicio","cesta.php" => "Cesta"
,"LogIn.php" => "Información Usuario"));
}else{
View::navigation(array("index.php" => "Volver al Inicio","cesta.php" => "Cesta"));
}
View::BuscadorMain();
View::mostrarTabla();
View::end();
<file_sep><?php
include_once 'business.class.php';
User::session_start();
$datoscrudos = file_get_contents("php://input"); //Leemos los datos
$datos = json_decode($datoscrudos);
$id = $datos->id;
$cantidad= $datos->cantidad;
if(isset($_SESSION['bag'])){
if(array_key_exists($id,$_SESSION['bag'])){
$_SESSION['bag'][$id]+= $cantidad;
}else{
$_SESSION['bag'][$id] = $cantidad;
}
} else {
$_SESSION['bag']=array($id => $cantidad);
}
$res=array("id" => $id, "stock"=>DB::getAnyDataQuery("stock","productos","where id=$id")[0]['stock']-$cantidad);
User::actualizarStock($id,$cantidad);
header('Content-type: application/json');
echo json_encode($res);<file_sep><?php
include_once 'business.class.php';
if(isset($_POST['SingIn'])){
User::login($_POST['usuario'], $_POST['password']);
header("location:LogIn.php");
}
if(isset($_POST['SingOut'])){
User::logout();
header("location:LogIn.php");
}
?><file_sep><?php
include_once 'presentation.class.php';
View::start('GCShop');
View::style(array("estilos.css"));
View::closeHead();
View::createHeaderIndex();
if(User::getLoggedUser()){
switch (User::getLoggedUser()['tipo']) {
case 1:
View::navigation(array("LogIn.php" => "Información Usuario",
"informeAdm.php?tipo=menu" => "Enterprise Manager"));
break;
case 2:
View::navigation(array("LogIn.php" => "Información Usuario",
"gestor.php?tipo=lista" => "Gestor de artículos"));
break;
default:
View::navigation(array("buscador.php" => "¡Nuestros productos!",
"cesta.php" => "Cesta",
"LogIn.php" => "Información Usuario"));
break;
}
} else {
View::navigation(array("buscador.php" => "¡Nuestros productos!", "cesta.php" => "Cesta",
"LogIn.php" => "Log In"));
}
View::mainIndex();
View::end();<file_sep><?php
include_once 'business.class.php';
function isAnyEmpty(){
$info=array("codigo","nombre", "tipo", "descripcion", "precio", "stock");
foreach ($info as $value) {
if(empty($_POST[$value]))return true;
}
return false;
}
if(isset($_POST['Modificar']) and !isAnyEmpty()){
if(!empty($_FILES['imagen']['name'])){
if($_FILES['imagen']['type'] == "image/jpeg"){
$arch=fopen($_FILES['imagen']['tmp_name'], "r");
$archBi=fread($arch,$_FILES['imagen']['size']);
fclose($arch);
User::modificarProductosImagen(
array($_POST['codigo'],$_POST['nombre'],$_POST['tipo'],$_POST['descripcion'],$_POST['precio'],$_POST['stock'],$archBi,$_GET['id']));
}
} else {
User::modificarProductos(array($_POST['codigo'],$_POST['nombre'],$_POST['tipo'],$_POST['descripcion'],$_POST['precio'],$_POST['stock'],$_GET['id']));
}
}
header("location:gestor.php?tipo=producto&id={$_GET['id']}");
?><file_sep># Canarian_Webshop
Online webshop of Canarian products, developed during my career at the ULPGC. It was a simulation of a real shop with cart, different user profiles, items list, ratings and more... It uses HTML, CSS, PHP and JavaScript.
<file_sep><?php
include_once 'presentation.class.php';
if(User::getLoggedUser() != false and User::getLoggedUser()['tipo'] == 1){
View::start('GCShop EM');
View::style(array("estilos.css"));
View::closeHead();
View::createHeader("Enterprise Manager");
switch ($_GET['tipo']) {
case 'ventas':
View::navigation(array("LogIn.php" => "Informe de Usuario",
"informeAdm.php?tipo=menu" => "Volver al Menu"));
View::informeVentas();
break;
case 'stock':
View::navigation(array("LogIn.php" => "Informe de Usuario",
"informeAdm.php?tipo=menu" => "Volver al Menu"));
View::productosStock();
break;
default:
View::navigation(array("LogIn.php" => "Volver"));
View::menuAdm();
break;
}
View::end();
}
<file_sep><?php
include_once 'presentation.class.php';
if(User::getLoggedUser() != false and User::getLoggedUser()['tipo'] == 2){
View::start('GCShop GA');
View::style(array("estilos.css"));
View::closeHead();
View::createHeader("Gestor de Artículos");
switch ($_GET['tipo']) {
case 'lista':
View::navigation(array("LogIn.php" => "Volver"));
View::gestorArticulosLista(DB::getAnyRow("id,nombre", "productos"));
View::gestorBotonAñadir();
break;
case 'añadir':
View::navigation(array("gestor.php?tipo=lista" => "Volver"));
View::gestorAñadir();
break;
default:
View::navigation(array("gestor.php?tipo=lista" => "Volver"));
View::gestorModificar(DB::getAnyDataQuery("*","productos","where id={$_GET['id']}"));
break;
}
View::end();
}<file_sep><?php
include_once 'presentation.class.php';
View::start('Producto');
View::style(array("estilos.css"));
View::closeHead();
$id = $_GET['id'];
$datos = DB::getAnyDataQuery("*", "productos", "where id=$id");
$nombre=$datos[0]["nombre"];
View::createHeader("Producto: $nombre");
View::navigation(array("buscador.php" => "Buscador","index.php" => "Inicio"
, "cesta.php" => "Cesta"));
View::listaProductos($datos,$id);
View::end();<file_sep><?php
include_once 'presentation.class.php';
if(User::getLoggedUser() != false and User::getLoggedUser()['tipo'] == 4){
View::start('GCShop Pago');
View::style(array("estilos.css"));
View::closeHead();
View::createHeader("Tu cesta de Compra");
$suma=User::sumaCesta();
if($_GET['metodo']==1){
View::navigation(array("cesta.php" => "Volver a la cesta"));
View::cantidadPagar($suma);
View::pago();
}elseif($_GET['metodo']==2){
View::navigation(array("pago.php?metodo=1" => "Volver atrás"));
View::cantidadPagar($suma);
View::pagotarjeta();
}else{
View::navigation(array("pago.php?metodo=1" => "Volver atrás"));
View::cantidadPagar($suma);
View::pagoEfectivo();
}
View::end();
}
<file_sep><?php
include_once 'data_access.class.php';
class User{
public static function session_start(){
if(session_status () === PHP_SESSION_NONE){
session_start();
}
}
public static function getLoggedUser(){ //Devuelve un array con los datos del cuenta o false
self::session_start();
if(!isset($_SESSION['user'])) return false;
return $_SESSION['user'];
}
public static function login($usuario,$pass){ //Devuelve verdadero o falso según
self::session_start();
if(DB::user_exists($usuario, $pass, $res)){
$_SESSION['user']=$res[0]; //Almacena datos del usuario en la sesión
return true;
}
return false;
}
public static function logout(){
self::session_start();
unset($_SESSION['user']);
}
public static function listaFacturas(){
return DB::getAnyRow("*", "facturaventas");
}
public static function productoFactura($id){
return DB::getAnyDataQuery("idproducto,precio,unidades","detallefacturaventas","where idfacturaventas=$id");
}
public static function listaProductosStock(){
return DB::getAnyRow("*","productos");
}
public static function sumaProductosStock(){
return DB::getAnyDataQuery("sum(stock*precio) as suma","productos","where stock > 0")[0]['suma'];
}
public static function sumaCesta(){
$suma = 0;
foreach ($_SESSION['bag'] as $key=>$value) {
$suma+=($value*DB::getAnyDataQuery("precio","productos","where id=$key")[0]['precio']);
}
return $suma;
}
public static function vaciarCesta(){
unset($_SESSION['bag']);
$_SESSION['bag'] = array();
}
public static function actualizarStock(int $id,int $value){
$stock=DB::getAnyDataQuery("stock","productos","where id=$id")[0]['stock']-$value;
if($stock > 0){
DB::execute_sql(
"
UPDATE productos
SET stock=$stock
where id=$id
"
);
return false;
} else {
DB::execute_sql(
"
UPDATE productos
SET stock=0
where id=$id
"
);
return true;
}
}
public static function crearFacturas($id,$calle,$fecha,$suma){
DB::execute_sql(
"
INSERT INTO [facturaventas] ([idcliente],[direccionentrega],[fechaventa], [total])
VALUES (?,?,?,?);
" , array($id,$calle,$fecha, $suma)
);
}
public static function crearDetallesFacturas($idfact,$key,$precio,$value){
DB::execute_sql(
"
INSERT INTO [detallefacturaventas] ([idfacturaventas], [idproducto], [precio], [unidades])
VALUES (?, ?, ?, ?);
",array($idfact, $key, $precio, $value)
);
}
public static function crearProductos(array $datos){
DB::execute_sql(
"
INSERT INTO [productos] ([codigo], [nombre], [tipo], [descripcion], [precio], [stock], [imagen])
VALUES (?,?,?,?,?,?,?);
",
$datos
);
}
public static function modificarProductosImagen(array $datos){
DB::execute_sql(
"
UPDATE productos
SET codigo=?, nombre=?, tipo=?,
descripcion=?, precio=?, stock=?, imagen=?
where id=?
",$datos
);
}
public static function modificarProductos(array $datos){
DB::execute_sql(
"
UPDATE productos
SET codigo=?, nombre=?, tipo=?,
descripcion=?, precio=?, stock=?
where id=?
",$datos
);
}
}<file_sep><?php
include_once 'business.class.php';
if(isset($_POST['Opciones'])){
if($_POST['Opciones']==1){
header("location:pago.php?metodo=2");
} elseif($_POST['Opciones']==2) {
header("location:pago.php?metodo=3");
}
}
function completarVenta(){
$datos=User::getLoggedUser();
$fecha=time();
$suma=User::sumaCesta();
User::crearFacturas($datos['id'],$_POST['calle'],$fecha,$suma);
$idfact=DB::getAnyDataQuery("max(id) as maximo","facturaventas","where idcliente={$datos['id']}")[0]['maximo'];
foreach ($_SESSION['bag'] as $key=>$value) {
$precio=DB::getAnyDataQuery("precio","productos","where id='$key'")[0]['precio'];
User::crearDetallesFacturas($idfact,$key,$precio,$value);
}
User::vaciarCesta();
header("location:cesta.php");
}
if(isset($_POST['completarEfectivo']) and
!empty($_POST['nombre']) and !empty($_POST['cuenta']) and !empty($_POST['calle']) and !empty($_POST['telefono'])
and !empty($_POST['paypal']) and !empty($_POST['passsword']) ){
completarVenta();
}
if(isset($_POST['completarTarjeta']) and
!empty($_POST['nombre']) and !empty($_POST['cuenta']) and !empty($_POST['telefono']) and !empty($_POST['tarjeta'])){
completarVenta();
}
?><file_sep><?php
include_once 'presentation.class.php';
View::start('GCShop Cesta');
View::LibreriaDeIconos();
View::style(array("estilos.css"));
View::closeHead();
View::createHeader("Tu cesta de Compra");
if(User::getLoggedUser()){
View::navigation(array("index.php" => "Volver al Inicio",
"buscador.php" => "¡Nuestros productos!","LogIn.php" => "Información Usuario"));
} else {
View::navigation(array("index.php" => "Volver al Inicio", "buscador.php" => "¡Nuestros productos!"));
}
if(isset($_GET['id'])){
if(isset($_POST['cantidad'])){
$_SESSION['bag'][$_GET['id']]-=$_POST['cantidad'];
User::actualizarStock($_GET['id'],-$_POST['cantidad']);
}
if ($_SESSION['bag'][$_GET['id']] === 0){
unset($_SESSION['bag'][$_GET['id']]);
}
}
View::cesta();
View::end();
?> | 95655282af30dac726d9b8f1d272d58e9af35db9 | [
"Markdown",
"PHP"
] | 15 | PHP | NSRdev/Canarian_Webshop | 3f065e3490d048051a5cbbd8e2bdd73d0cd9a609 | 5d849ecbdba9a9ac751d781a9ec9849ddaddf604 |
refs/heads/master | <file_sep># ToKindle
### 推送文件到Kindle的工具,支持包括中亚地区在内的所有用户
#### 虽然亚马逊已经推出了向Kindle推送文件的SendToKindle插件和客户端,但是却都不支持中亚地区的用户,推送文件时只能手动发送邮件,不免有些麻烦,这款ToKindle工具的目的就是方便用户发送附件,只要在使用前配置好使用时一个命令就能搞定。
#### 本工具已用qq,163,126,gmail邮箱测试过,都可以正常实现文件到kindle设备的推送
___
### 环境要求
保证Python版本>=2.6,可使用`python -V`查看
### 如何使用
1. 首先`git clone <EMAIL>:mingyangShang/ToKindle.git`,或者fork一个,clone的地址改为自己仓库的地址
2. 在`config.py`文件中配置邮件相关参数,如现在项目中的例子所示:
```
MAIL_HOST = "smtp.163.com" # 选用的邮件服务器,这里选择163邮箱服务器
MAIL_USER = "<EMAIL>" # 发件人的邮箱地址
MAIL_PWD = "<PASSWORD>" # 发件人的邮箱密码,若像qq邮箱一样单独打开smtp服务的话要用专门的授权码
KINDLE_MAIL = "<EMAIL>" # kindle邮箱,即接收文件的邮箱
```
3. 此时进入该项目的根目录下,运行
`python kindle.py 附件1 附件2`
即可将附件1和附件2发送到`KINDLE_MAIL`即kindle绑定的邮箱中,附件个数不限,以空格分隔开就可以
4. 为了在任何位置都可以方便地使用该工具而不用一定要进入项目所在目录,可以用alias将命令简单化.
- Mac用户:编辑`~/.bash_profile`文件,添加`alias kindle="python kindle.py所在位置"`,使用`source ~/.bash_profile`持久化该别名
- Linux用户:编辑`~/.bashrc`文件,添加`alias kindle="python kindle.py所在位置"`,使用`source ~/.bashrc`持久化该别名
这样,在任何文件位置都可以使用 `kindle 附件全名`发送文件到Kindle了。
<file_sep># -*- coding: utf-8 -*-
import smtplib
import os
import sys
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from config import MAIL_HOST, MAIL_USER, MAIL_PWD, KINDLE_MAIL, SMTP_TIMEOUT
class EmailSender(object):
def __init__(self, mailHost, mailUser, mailPwd):
self.mailHost = mailHost
self.mailUser = mailUser
self.mailPwd = mailPwd
# send email with multi attachments
def emailFile(self, sender, receiver, filePaths):
if len(filePaths) == 0:
print "附件名不能为空"
return False
msg = MIMEMultipart()
first = filePaths[0]
i = first.rfind(os.sep)
if i != -1:
subject = first[i+1:]
else:
subject = first
if len(filePaths) > 1:
subject = subject + "等" + str(len(filePaths)) + "个附件"
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
# 针对qq邮箱的单独处理,伪造身份模仿foxmail发送邮件
if self.mailHost == "smtp.qq.com":
msg["X-Mailer"] = " Foxmail 7, 2, 7, 26[cn]" #客户端标识
msg["Mime-Version"] = "1.0" #mime版本
# Message-ID表示唯一标识该邮件,格式为<年月日时分秒><秒7位精确值>@qq.com,如"<EMAIL>08081052<EMAIL>"
# 这里简单起见,将秒后的精确值都置为0
msg["Message-ID"] = time.strftime("%Y%m%d%H%M%S", time.localtime()) + "<EMAIL>"
# 按序构造附件列表
# map(lambda att:msg.attach(att), [self.attachFile(filePath) for filePath in filePaths])
for filePath in filePaths:
att = self.attachFile(filePath)
if att:
msg.attach(att)
try:
s = smtplib.SMTP(timeout = SMTP_TIMEOUT)
s.connect(self.mailHost)
s.starttls()
s.login(self.mailUser, self.mailPwd)
s.sendmail(sender, receiver, msg.as_string())
s.quit()
except smtplib.SMTPException, e:
print "error:", e.__str__().encode("utf-8")
return False
return True
# return an attachment object with specific type
def attachFile(self, filePath):
i = filePath.rfind(os.sep)
# 文件名
if i != -1:
fileName = filePath[i + 1 : ]
else:
fileName = filePath
# 文件格式,以后缀区分
i = fileName.rfind(".")
if i != -1:
suffix = fileName[i + 1 : ]
else:
suffix = "txt"
# 根据附件的格式选择不同的读取方式:按字符还是按二进制字节
try:
if suffix in ["jpeg", "jpg", "png"]:
att = MIMEText(open(filePath, "rb").read(), "base64", "utf-8")
else:
att = MIMEText(open(filePath, "r").read(), _charset = "utf-8")
except IOError:
print "<<" + fileName + ">>" + "读取失败,请检查文件是否存在"
return None
att["Content-Type"] = 'application/octet-stream'
# filename will be displayed as attachment's name,should be extracted from filePath
# 邮件中附件的名字即为该附件文件的名字
att["Content-Disposition"] = "attachment; filename={fileName}".format(fileName = fileName)
return att
if __name__ == "__main__":
fileList = []
for i in range(len(sys.argv)):
if i > 0:
fileList.append(sys.argv[i])
e = EmailSender(MAIL_HOST, MAIL_USER, MAIL_PWD)
print "邮件发送中……"
if e.emailFile(MAIL_USER, KINDLE_MAIL, fileList):
print "邮件已成功发送"
else:
print "邮件发送失败,请检查网络和参数重试"
<file_sep># -*- coding: utf-8 -*-
MAIL_HOST = "smtp.gmail.com" # 选用的邮件服务器,这里选择163邮箱服务器
MAIL_USER = "<EMAIL>" # 发件人的邮箱地址
MAIL_PWD = "<PASSWORD>" # 发件人的邮箱密码,若像qq邮箱一样单独打开smtp服务的话要用专门的授权码
# qeftdbniepcsecbc
KINDLE_MAIL = "<EMAIL>" # kindle邮箱,即接收文件的邮箱
KINDLE_MAIL = "<EMAIL>" # kindle邮箱,即接收文件的邮箱
#连接服务器超时时间
SMTP_TIMEOUT = 30 # 单位:s
| cec2484d7b3449dacf27324805743cd83b2ff251 | [
"Markdown",
"Python"
] | 3 | Markdown | imasimpleboy/ToKindle | 09f9903a1c98ac46203996f7d6025ce2a3ff5c83 | 7616833d59bcb7cd527aaeb71a7fc3805fe20471 |
refs/heads/master | <file_sep>#!/usr/bin/python2.7
#
# Assignment2 Interface
#
import psycopg2
import os
import sys
import Assignment1 as a
# Donot close the connection inside this file i.e. do not perform openconnection.close()
#range__metadata = RangeRatingsMetadata
#roundR_metadata = RoundRobinRatingsMetadata
#rangetablepartition = rangeratingspart
def RangeQuery(ratingsTableName, ratingMinValue, ratingMaxValue, openconnection):
try:#Implement RangeQuery Here.
cur = openconnection.cursor()
ratings_Min = ratingMinValue
ratings_Max = ratingMaxValue
if ((0.0<=ratings_Min <= 5.0) and (0.0<=ratings_Max<= 5.0) and (ratings_Max >=ratings_Min)):
cur.execute("SELECT maxrating from rangeratingsmetadata") ### Lines to make him look at
upperbound_range = cur.fetchall() #print the last column of the select function execute above
i=0
#print upperbound_range
while(1):
#print upperbound_range[i][0]
if (ratings_Min > upperbound_range[i][0]):
i = i+1
else:
lower_bound = i
#print "the lower table index is", lower_bound
break
i = 0
while(1):
if (ratings_Max > upperbound_range[i][0]):
i = i+1
else:
upper_bound = i
#print "the upper table index is", upper_bound
break
range_list_table_lookup = range(lower_bound,upper_bound+1)
#print range_list_table_lookup
file = open("RangeQueryOut.txt","w")
for l in range_list_table_lookup:
rows = []
cur.execute('SELECT * from rangeratingspart' + str(l)) ### Lines to make him look at
rows = cur.fetchall()
#print rows
### Lines to make him look at
for row in rows:
rat = row[2]
if (ratings_Min <= rat <= ratings_Max):
file.write("{},{},{},{} \n".format("rangeratingspart" + str(l),row[0],row[1],row[2])) ### Lines to make him look at
#file.close()
cur.execute('SELECT * from RoundRobinRatingsMetadata')
numberofpartitionslist = cur.fetchall()
numberofpartitions = numberofpartitionslist[0][0]
for l in range(numberofpartitions):
cur.execute('SELECT * from RoundRobinRatingsPart' + str(l)) ### Lines to make him look at
rows = []
rows = cur.fetchall()
for row in rows:
rat = row[2]
if (ratings_Min <= rat <= ratings_Max):
file.write("{},{},{},{} \n".format("roundrobinratingspart" + str(l),row[0],row[1],row[2])) ### Lines to make him look at
file.close()
else:
print ("Please enter the valid values")
cur.close()
except Exception as E:
print E
def PointQuery(ratingsTableName, ratingValue, openconnection):
#Implement PointQuery Here.
# Remove this once you are done with implementation
cur = openconnection.cursor()
pointvalue = ratingValue
if ((0.0<=pointvalue<= 5.0)):
cur.execute('SELECT maxrating from RangeRatingsMetadata')
Range_upper = cur.fetchall()
i=0
while(1):
if (pointvalue > Range_upper[i][0]):
i = i+1
else:
table_suffxi = i
#print "the table suffix to look is", table_suffix
break
rows = []
cur.execute('SELECT * from rangeratingspart'+str(table_suffix))
rows = cur.fetchall()
file1 = open("PointQueryOut.txt","w")
for row in rows:
rat = row[2]
if (rat == pointvalue):
file1.write("{},{},{},{} \n".format("rangeratingspart"+str(table_suffix),row[0],row[1],row[2]))
#file1.close()
cur.execute('SELECT * from RoundRobinRatingsMetadata')
numberofpartitionslist = cur.fetchall()
numberofpartitions = numberofpartitionslist[0][0]
for l in range(numberofpartitions):
cur.execute('SELECT * from RoundRobinRatingsPart'+str(l))
rows = []
rows = cur.fetchall()
#file1 = open("PointQueryOut.txt","w")
for row in rows:
rat = row[2]
if (rat == pointvalue):
file1.write ("{},{},{},{} \n".format("roundrobinratingspart" + str(l),row[0],row[1],row[2]))
file1.close()
else:
print("please enter a valid rating value")
cur.close()
| 8090538c55eb4a60eccdec6d00de69371a9ae69a | [
"Python"
] | 1 | Python | saiteja93/Range-and-Point-Query-PostgreSQL | 2fb5720ab14b4245ec23e85325f9a186eec10b7b | 7bb982806f9331abc85b485d53433ab23792e2d9 |
refs/heads/master | <file_sep>package datos;
public class Coordinador extends Solicitante {
public Coordinador(String Identificacion, String Nombre, String Apellidos, String Correo, String Telefono) {
super(Identificacion, Nombre, Apellidos, Correo, Telefono);
}
public void verSolicitud(int codigoSolicitud)
{
}
public void agregarAnotacion(DTOSolicitud solicitud)
{
}
public int tramitarSolicitud(DTOSolicitud solicitud)
{
return 0;
}
}
<file_sep>package datos;
public class OfertaAcademica {
private Curso curso;
private int numeroGrupo;
private Docente docente;
private Horario horario;
private Aula aula;
public OfertaAcademica(Curso curso, int numeroGrupo, Docente docente, Horario horario, Aula aula) {
this.curso = curso;
this.numeroGrupo = numeroGrupo;
this.docente = docente;
this.horario = horario;
this.aula = aula;
}
public Curso getCurso() {
return curso;
}
public void setCurso(Curso curso) {
this.curso = curso;
}
public int getNumeroGrupo() {
return numeroGrupo;
}
public void setNumeroGrupo(int numeroGrupo) {
this.numeroGrupo = numeroGrupo;
}
public Docente getDocente() {
return docente;
}
public void setDocente(Docente docente) {
this.docente = docente;
}
public Horario getHorario() {
return horario;
}
public void setHorario(Horario horario) {
this.horario = horario;
}
public Aula getAula() {
return aula;
}
public void setAula(Aula aula) {
this.aula = aula;
}
}
<file_sep>package controlador.dto;
public class DTOofertaAcademica {
// CODIGO, NOMBRE, NUMERO_GRUPO, ID_PROFESOR_ NOMBRE, HORARIO, AULA
// CURSO, INT, DOCENTE, HORARIO ,AULA
private String codigo;
private String nombre;
private String numeroGrupo;
private String idProfesor;
private String nombreProfesor;
private String primeraFechaHora;
private String segundaFechaHora;
private String aula;
public DTOofertaAcademica(String codigo, String nombre, String numeroGrupo, String idProfesor, String nombreProfesor, String primeraFechaHora, String segundaFechaHora, String aula) {
this.codigo = codigo;
this.nombre = nombre;
this.numeroGrupo = numeroGrupo;
this.idProfesor = idProfesor;
this.nombreProfesor = nombreProfesor;
this.primeraFechaHora = primeraFechaHora;
this.segundaFechaHora = segundaFechaHora;
this.aula = aula;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getNumeroGrupo() {
return numeroGrupo;
}
public void setNumeroGrupo(String numeroGrupo) {
this.numeroGrupo = numeroGrupo;
}
public String getIdProfesor() {
return idProfesor;
}
public void setIdProfesor(String idProfesor) {
this.idProfesor = idProfesor;
}
public String getNombreProfesor() {
return nombreProfesor;
}
public void setNombreProfesor(String nombreProfesor) {
this.nombreProfesor = nombreProfesor;
}
public String getPrimeraFechaHora() {
return primeraFechaHora;
}
public void setPrimeraFechaHora(String primeraFechaHora) {
this.primeraFechaHora = primeraFechaHora;
}
public String getSegundaFechaHora() {
return segundaFechaHora;
}
public void setSegundaFechaHora(String segundaFechaHora) {
this.segundaFechaHora = segundaFechaHora;
}
public String getAula() {
return aula;
}
public void setAula(String aula) {
this.aula = aula;
}
}
<file_sep>package datos;
import java.io.Serializable;
public class Solicitante implements Serializable {
private String Identificacion;
private String Nombre;
private String Apellidos;
private String Correo;
private String Telefono;
public Solicitante(String Identificacion, String Nombre, String Apellidos, String Correo, String Telefono) {
this.Identificacion = Identificacion;
this.Nombre = Nombre;
this.Apellidos = Apellidos;
this.Correo = Correo;
this.Telefono = Telefono;
}
public DTOSolicitud registrarSolicitud(
Periodo periodoLectivo,
int codigoCurso,
Estudiante estudiante,
InconsistenciaEnum inconsistencia,
String descripcion,
Object evidencia
)
{
SolicitudStrategy strategy = null;
return strategy.registrarSolicitud(this, periodoLectivo, codigoCurso, estudiante, inconsistencia, descripcion, evidencia);
}
public String getIdentificacion() {
return Identificacion;
}
public void setIdentificacion(String Identificacion) {
this.Identificacion = Identificacion;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String Nombre) {
this.Nombre = Nombre;
}
public String getApellidos() {
return Apellidos;
}
public void setApellidos(String Apellidos) {
this.Apellidos = Apellidos;
}
public String getCorreo() {
return Correo;
}
public void setCorreo(String Correo) {
this.Correo = Correo;
}
public String getTelefono() {
return Telefono;
}
public void setTelefono(String Telefono) {
this.Telefono = Telefono;
}
}
<file_sep>package datos;
import java.io.Serializable;
public class Curso implements Serializable {
public String codigoCurso;
public String nombreCurso;
public CreditosEnum creditos;
public Curso(String nombreCurso) {
this.nombreCurso = nombreCurso;
}
public Curso(String codigoCurso, String nombreCurso, CreditosEnum creditos) {
this.codigoCurso = codigoCurso;
this.nombreCurso = nombreCurso;
this.creditos = creditos;
}
public String getCodigoCurso() {
return codigoCurso;
}
public void setCodigoCurso(String codigoCurso) {
this.codigoCurso = codigoCurso;
}
public String getNombreCurso() {
return nombreCurso;
}
public void setNombreCurso(String nombreCurso) {
this.nombreCurso = nombreCurso;
}
public CreditosEnum getCreditos() {
return creditos;
}
public void setCreditos(CreditosEnum creditos) {
this.creditos = creditos;
}
}
<file_sep>
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controlador;
import controlador.dto.DTOResolucion;
/**
*
* @author Giova
*/
public interface GeneradorStrategy {
DTOResolucion resolucion = new DTOResolucion();
public void generarDocumento(DTOResolucion resolucion);
}
<file_sep>package datos;
public class Horario {
private FechaHorarios PrimeraFecha;
private FechaHorarios SegundaFecha;
public Horario(FechaHorarios PrimeraFecha, FechaHorarios SegundaFecha) {
this.PrimeraFecha = PrimeraFecha;
this.SegundaFecha = SegundaFecha;
}
public FechaHorarios getPrimeraFecha() {
return PrimeraFecha;
}
public void setPrimeraFecha(FechaHorarios PrimeraFecha) {
this.PrimeraFecha = PrimeraFecha;
}
public FechaHorarios getSegundaFecha() {
return SegundaFecha;
}
public void setSegundaFecha(FechaHorarios SegundaFecha) {
this.SegundaFecha = SegundaFecha;
}
}<file_sep>package controlador.ui;
import controlador.ConfigurationPaths;
import controlador.controlador;
import controlador.dao.DAOsolicitudes;
import controlador.dto.DTOResolucion;
import datos.EstadoEnum;
import datos.DTOSolicitud;
import gui.TramiteSolicitud;
import gui.VisionSolicitud;
import java.util.Date;
public class uiVisionSolicitud
{
private final VisionSolicitud visionSolicitud;
private DTOSolicitud solicitud;
private controlador control = new controlador();
public uiVisionSolicitud(VisionSolicitud visioSolicitud) {
this.visionSolicitud = visioSolicitud;
}
public void llenarDatos()
{
String codigo = solicitud.getCodigo();
String fecha = solicitud.getFecha().getDate().toString();
String idSolicitante = solicitud.getIdentificacion();
String nombreSolicitante = solicitud.getNombreSolicitante();
String periodo = solicitud.getPeriodo().getNombre();
String curso = solicitud.getCurso().getNombreCurso();
String grupo = String.valueOf(solicitud.getGrupo().getNumeroGrupo());
String inconsistencia = String.valueOf(solicitud.getInconsistencia());
String estado = String.valueOf(solicitud.getEstado());
visionSolicitud.getTxtSolNumero().setText(codigo);
visionSolicitud.getTxtSolFecha().setText(fecha);
visionSolicitud.getTxtSolID().setText(idSolicitante);
visionSolicitud.getTxtSolNombreSolicitante().setText(nombreSolicitante);
visionSolicitud.getTxtSolPeriodo().setText(periodo);
visionSolicitud.getTxtSolCurso().setText(curso);
visionSolicitud.getTxtSolGrupo().setText(grupo);
visionSolicitud.getTxtSolInconsistencia().setText(inconsistencia);
visionSolicitud.getTxtSolEstado().setText(estado);
String carnetEstudiante = String.valueOf(solicitud.getEstudiante().getCarnet());
String nombreEstudiante = solicitud.getEstudiante().getNombre() + " " +
solicitud.getEstudiante().getApellidos();
String numeroTelefonico = solicitud.getEstudiante().getTelefono();
visionSolicitud.getTxtEstCarnet().setText(carnetEstudiante);
visionSolicitud.getTxtEstNombre().setText(nombreEstudiante);
visionSolicitud.getTxtEstNumero().setText(numeroTelefonico);
String detalles = solicitud.getDetalles();
visionSolicitud.getAreaTextDetalles().setText(detalles);
}
public void accionBtnTramitar()
{
TramiteSolicitud tramiteSolicitud = new TramiteSolicitud();
tramiteSolicitud.setDefaultCloseOperation(TramiteSolicitud.DISPOSE_ON_CLOSE);
tramiteSolicitud.getUi().setSolicitud(solicitud);
tramiteSolicitud.getUi().llenarDatos();
tramiteSolicitud.setVisible(true);
}
public void accionBtnAnular()
{
solicitud.setEstado(EstadoEnum.ANULADA);
visionSolicitud.getTxtSolEstado().setText("ANULADA");
DAOsolicitudes dao = new DAOsolicitudes();
dao.actualizarSolicitud(solicitud);
visionSolicitud.getBtnTramitar().setVisible(false);
visionSolicitud.getBtnGenerarHTML().setVisible(false);
}
public void setSolicitud(DTOSolicitud solicitud) {
this.solicitud = solicitud;
}
public void generarPDF()
{
Date date = new Date();
date = solicitud.getFecha().getDate();
String annoTemp = date.toString().substring(date.toString().length() - 4, date.toString().length());
int anno = Integer.valueOf(annoTemp);
DTOResolucion resolucion = new DTOResolucion();
resolucion.setAnno(anno);
resolucion.setCarneEstudiante(solicitud.getEstudiante().getCarnet());
resolucion.setNombreEstudiante(solicitud.getEstudiante().getNombre()+ " " + solicitud.getEstudiante().getApellidos());
resolucion.setConsiderados(solicitud.getConsiderandos());
resolucion.setIdSolicitud(solicitud.getCodigo());
resolucion.setTipoCaso(solicitud.getInconsistencia());
resolucion.setiDcurso(solicitud.getCurso().codigoCurso);
resolucion.setNombreCurso(solicitud.getCurso().getNombreCurso());
resolucion.setDirectorAdmision(ConfigurationPaths.getInstance().getDirectorAdminisionRegistro());
resolucion.setDirectorCarrera(ConfigurationPaths.getInstance().getDirectorEscuelaComputacion());
resolucion.setPeriodo(solicitud.getPeriodo().getNombre());
control.generarDocumento(resolucion, 1);
}
public void generarHTML()
{
Date date = new Date();
date = solicitud.getFecha().getDate();
String annoTemp = date.toString().substring(date.toString().length() - 4, date.toString().length());
int anno = Integer.valueOf(annoTemp);
DTOResolucion resolucion = new DTOResolucion();
resolucion.setAnno(anno);
resolucion.setCarneEstudiante(solicitud.getEstudiante().getCarnet());
resolucion.setNombreEstudiante(solicitud.getEstudiante().getNombre()+ " " + solicitud.getEstudiante().getApellidos());
resolucion.setConsiderados(solicitud.getConsiderandos());
resolucion.setIdSolicitud(solicitud.getCodigo());
resolucion.setTipoCaso(solicitud.getInconsistencia());
resolucion.setiDcurso(solicitud.getCurso().codigoCurso);
resolucion.setNombreCurso(solicitud.getCurso().getNombreCurso());
resolucion.setDirectorAdmision(ConfigurationPaths.getInstance().getDirectorAdminisionRegistro());
resolucion.setDirectorCarrera(ConfigurationPaths.getInstance().getDirectorEscuelaComputacion());
resolucion.setPeriodo(solicitud.getPeriodo().getNombre());
control.generarDocumento(resolucion, 2);
}
}
<file_sep>package test;
import com.my.GoogleForms;
import controlador.ConfigurationPaths;
import controlador.DataLoader;
import controlador.dao.DAOsolicitudes;
import datos.Curso;
import datos.EstadoEnum;
import datos.Estudiante;
import datos.FechaHora;
import datos.Grupo;
import datos.InconsistenciaEnum;
import datos.Periodo;
import datos.DTOSolicitud;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class testGoogle {
public static void main(String args[])
{
DataLoader loader = new DataLoader();
loader.cargarPrimerosDatos();
/*
ArrayList<Solicitud> test = cargarSolicitudesGoogle();
DAOsolicitudes dao = new DAOsolicitudes();
try{
dao.salvarSolicitudesLocal(test);
} catch(IOException ex)
{
System.out.println("Error " + ex.getLocalizedMessage());
}*/
try{
ArrayList<DTOSolicitud> nuevas = loader.cargaInicialSolicitudes();
for(DTOSolicitud solicitud: nuevas)
{
System.out.println(solicitud.getCodigo());
}
nuevas.get(0).setNombreSolicitante("Fulano");
DAOsolicitudes dao = new DAOsolicitudes();
dao.salvarSolicitudesLocal(nuevas);
ArrayList<DTOSolicitud> nuevas3 = loader.cargaInicialSolicitudes();
for(DTOSolicitud solicitud: nuevas3)
{
System.out.println(solicitud.getNombreSolicitante());
}
} catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
public static ArrayList<DTOSolicitud> cargarSolicitudesGoogle() {
String hojaID = "1aUZUKRCIfhH-pO8iTeyN30kZmByrVyOthv9-N5arUjE";
String hojaFormato = "Sheet1!A2:L";
GoogleForms forms = new GoogleForms(hojaID, hojaFormato, "APP");
List<List<Object>> values = forms.getResponse().getValues();
ArrayList<DTOSolicitud> solicitudes = new ArrayList<>();
if (values == null || values.size() == 0) {
System.out.println("No data found.");
} else {
values.forEach((row) -> {
try {
String fechaExcel = String.valueOf(row.get(0));//.replace("/", "-");
String fecha = fechaExcel.split("\\s+")[0];
String tiempo = fechaExcel.split("\\s+")[1];
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date fechaDate = (Date) df.parse(fecha);
FechaHora fechaHora = new FechaHora(fechaDate, tiempo);
String idSolicitante = String.valueOf(row.get(2));
String nombreSolicitante = String.valueOf(row.get(3));
String carnetEstudiante = String.valueOf(row.get(4));
String nombreEstudiante = String.valueOf(row.get(5));
String correoEstudiante = String.valueOf(row.get(5));
String numeroEstudiante = String.valueOf(row.get(6));
Estudiante estudiante = new Estudiante(" ", nombreEstudiante, " ", correoEstudiante, numeroEstudiante, Integer.parseInt(carnetEstudiante));
String periodoNombre = String.valueOf(row.get(7));
Periodo periodo = new Periodo(periodoNombre);
String cursoNombre = String.valueOf(row.get(8));
Curso curso = new Curso(cursoNombre);
int numeroGrupo = Integer.parseInt(String.valueOf(row.get(9)));
Grupo grupo = new Grupo(numeroGrupo);
InconsistenciaEnum inconsistencia = InconsistenciaEnum.valueOf(String.valueOf(row.get(10)));
String detallesInconsistencia = String.valueOf(row.get(11));
DTOSolicitud solicitud = new DTOSolicitud(fechaHora, idSolicitante, nombreSolicitante, periodo, grupo, curso, estudiante, inconsistencia,
detallesInconsistencia, EstadoEnum.PENDIENTE
);
solicitud.setCodigo(solicitud.generarCodigo());
solicitudes.add(solicitud);
} catch (Exception ex) {
System.out.println("Google " + ex.getMessage());
}
});
}
return solicitudes;
}
}
<file_sep>package datos;
public class Resolucion {
public int Codigo;
public String NotaAclaratoria;
public Resolucion(int Codigo, String NotaAclaratoria) {
this.Codigo = Codigo;
this.NotaAclaratoria = NotaAclaratoria;
}
public int getCodigo() {
return Codigo;
}
public void setCodigo(int Codigo) {
this.Codigo = Codigo;
}
public String getNotaAclaratoria() {
return NotaAclaratoria;
}
public void setNotaAclaratoria(String NotaAclaratoria) {
this.NotaAclaratoria = NotaAclaratoria;
}
}
<file_sep>
package controlador.ui;
import controlador.DataLoader;
import datos.Docente;
import gui.CarteraDocente;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
public class uiCarteraDocentes
{
private final CarteraDocente carteraDocente;
public uiCarteraDocentes(CarteraDocente pCartera)
{
this.carteraDocente = pCartera;
}
public void populateTablaDocentes()
{
DataLoader loader = new DataLoader();
ArrayList<Docente> docentes = loader.cargarCarteraDocente();
DefaultTableModel model = (DefaultTableModel) carteraDocente.getTablaDocentes().getModel();
Object rowData [] = new Object[4];
for(int i = 0; i < docentes.size(); i++)
{
rowData[0] = docentes.get(i).getIdentificacion();
rowData[1] = docentes.get(i).getNombre();
rowData[2] = docentes.get(i).getCorreo();
rowData[3] = docentes.get(i).getTelefono();
model.addRow(rowData);
}
}
}
<file_sep>
nombreAplicacion = Solicitudes
sheetid = 1aUZUKRCIfhH-pO8iTeyN30kZmByrVyOthv9-N5arUjE
range = Sheet1!A2:K
pathSolicitudesLocal = C:\\Users\\USER\\Desktop\\ExcelDiseno\\Solicitudes.ld
pathCarteraDocentes = C:\\Users\\USER\\Desktop\\ExcelDiseno\\profesores.xls
pathCursos = C:\\Users\\USER\\Desktop\\ExcelDiseno\\cursos.xls
pathOfertaAcademica = C:\\Users\\USER\\Desktop\\ExcelDiseno\\ofertaacademica.xls
directorEscuelaComputacion = Ing. <NAME>
directorAdminisionRegistro = M\u00e1ster <NAME>\u00edguez
<file_sep>package datos;
public interface SolicitudStrategy {
// Es mejor cambiar los parámetros por un DTO
public DTOSolicitud registrarSolicitud(Solicitante solicitante,
Periodo periodoLectivo,
int codigoCurso,
Estudiante estudiante,
InconsistenciaEnum inconsistencia,
String descripcion,
Object evidencia
);
}
<file_sep>compile.on.save=true
file.reference.jxl.jar=C:\\Users\\USER\\Documents\\NewTest\\jxl.jar
user.properties.file=C:\\Users\\USER\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
<file_sep>package controlador.ui;
import controlador.DataLoader;
import controlador.dto.DTOofertaAcademica;
import datos.Curso;
import datos.Docente;
import gui.PlanEstudios;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
public class uiPlanEstudios {
PlanEstudios planEstudios;
public uiPlanEstudios(PlanEstudios planEstudios) {
this.planEstudios = planEstudios;
}
public void populateTablaCursos()
{
DataLoader loader = new DataLoader();
ArrayList<Curso> cursos = loader.cargarCursos();
DefaultTableModel model = (DefaultTableModel) planEstudios.getTablaCursos().getModel();
Object rowData [] = new Object[3];
for(int i = 0; i < cursos.size(); i++)
{
rowData[0] = String.valueOf(cursos.get(i).getCodigoCurso());
rowData[1] = cursos.get(i).getNombreCurso();
rowData[2] = String.valueOf(cursos.get(i).getCreditos());
model.addRow(rowData);
}
}
public void populateTablaOfertaAcademica()
{
DataLoader loader = new DataLoader();
ArrayList<DTOofertaAcademica> ofertas = loader.cargarOfertaAcademica();
DefaultTableModel model = (DefaultTableModel) planEstudios.getTablaOfertaAcademica().getModel();
Object rowData [] = new Object[8];
for(int i = 0; i < ofertas.size(); i++)
{
rowData[0] = ofertas.get(i).getCodigo();
rowData[1] = ofertas.get(i).getNombre();
rowData[2] = ofertas.get(i).getNumeroGrupo();
rowData[3] = ofertas.get(i).getIdProfesor();
rowData[4] = ofertas.get(i).getNombreProfesor();
rowData[5] = ofertas.get(i).getPrimeraFechaHora();
rowData[6] = ofertas.get(i).getSegundaFechaHora();
rowData[7] = ofertas.get(i).getAula();
model.addRow(rowData);
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controlador.dto;
import datos.Considerando;
import datos.InconsistenciaEnum;
import java.util.ArrayList;
/**
*
* @author Giova
*/
public class DTOResolucion {
private String fecha;
private String directorCarrera;
private String idSolicitud;
private int numeroResolucion;
private String iDcurso;
private String nombreCurso;
private int grupoCurso;
private String nombreEstudiante;
private int carneEstudiante;
private String periodo;
private String resultado;
private ArrayList<Considerando> considerados;
private String resolucion;
private InconsistenciaEnum tipoCaso;
private String profesor;
private int anno;
private String directorAdmision;
public DTOResolucion(String pFecha,String pDirector,InconsistenciaEnum pTipoCaso,String pProfesor,int pAnno,String pIdSol,int pNumeroRes, String pIdCurso,String pNombreCurso, int pGrupo,
String pEstudiante, int pCarne, String pPeriodo,String pResultado, ArrayList<Considerando> pConsiderados,String pResolucion,String pDirectorAdmision) {
this.fecha = pFecha;
this.directorCarrera = pDirector;
this.idSolicitud = pIdSol;
this.tipoCaso = pTipoCaso;
this.numeroResolucion = pNumeroRes;
this.iDcurso = pIdCurso;
this.nombreCurso = pNombreCurso;
this.grupoCurso = pGrupo;
this.nombreEstudiante = pEstudiante;
this.carneEstudiante = pCarne;
this.periodo = pPeriodo;
this.considerados = pConsiderados;
this.resultado = pResultado;
this.resolucion = pResolucion;
this.profesor = pProfesor;
this.anno = pAnno;
this.directorAdmision = pDirectorAdmision;
}
public DTOResolucion()
{}
/**
* @return the directorCarrera
*/
public String getDirectorCarrera() {
return directorCarrera;
}
/**
* @param directorCarrera the directorCarrera to set
*/
public void setDirectorCarrera(String directorCarrera) {
this.directorCarrera = directorCarrera;
}
/**
* @return the idSolicitud
*/
public String getIdSolicitud() {
return idSolicitud;
}
/**
* @param idSolicitud the idSolicitud to set
*/
public void setIdSolicitud(String idSolicitud) {
this.idSolicitud = idSolicitud;
}
/**
* @return the numeroResolucion
*/
public int getNumeroResolucion() {
return numeroResolucion;
}
/**
* @param numeroResolucion the numeroResolucion to set
*/
public void setNumeroResolucion(int numeroResolucion) {
this.numeroResolucion = numeroResolucion;
}
/**
* @return the iDcurso
*/
public String getiDcurso() {
return iDcurso;
}
/**
* @param iDcurso the iDcurso to set
*/
public void setiDcurso(String iDcurso) {
this.iDcurso = iDcurso;
}
/**
* @return the nombreCurso
*/
public String getNombreCurso() {
return nombreCurso;
}
/**
* @param nombreCurso the nombreCurso to set
*/
public void setNombreCurso(String nombreCurso) {
this.nombreCurso = nombreCurso;
}
/**
* @return the grupoCurso
*/
public int getGrupoCurso() {
return grupoCurso;
}
/**
* @param grupoCurso the grupoCurso to set
*/
public void setGrupoCurso(int grupoCurso) {
this.grupoCurso = grupoCurso;
}
/**
* @return the nombreEstudiante
*/
public String getNombreEstudiante() {
return nombreEstudiante;
}
/**
* @param nombreEstudiante the nombreEstudiante to set
*/
public void setNombreEstudiante(String nombreEstudiante) {
this.nombreEstudiante = nombreEstudiante;
}
/**
* @return the carneEstudiante
*/
public int getCarneEstudiante() {
return carneEstudiante;
}
/**
* @param carneEstudiante the carneEstudiante to set
*/
public void setCarneEstudiante(int carneEstudiante) {
this.carneEstudiante = carneEstudiante;
}
/**
* @return the periodo
*/
public String getPeriodo() {
return periodo;
}
/**
* @param periodo the periodo to set
*/
public void setPeriodo(String periodo) {
this.periodo = periodo;
}
/**
* @return the considerados
*/
public ArrayList<Considerando> getConsiderados() {
return considerados;
}
/**
* @param considerados the considerados to set
*/
public void setConsiderados(ArrayList<Considerando> considerados) {
this.considerados = considerados;
}
/**
* @return the resolucion
*/
public String getResolucion() {
return resolucion;
}
/**
* @param resolucion the resolucion to set
*/
public void setResolucion(String resolucion) {
this.resolucion = resolucion;
}
/**
* @return the fecha
*/
public String getFecha() {
return fecha;
}
/**
* @param fecha the fecha to set
*/
public void setFecha(String fecha) {
this.fecha = fecha;
}
/**
* @return the tipoCaso
*/
public String getTipoCaso() {
return tipoCaso.toString();
}
public void setTipoCaso(InconsistenciaEnum pTipo)
{
this.tipoCaso = pTipo;
}
/**
* @return the profesor
*/
public String getProfesor() {
return profesor;
}
/**
* @param profesor the profesor to set
*/
public void setProfesor(String profesor) {
this.profesor = profesor;
}
/**
* @return the anno
*/
public int getAnno() {
return anno;
}
/**
* @param anno the anno to set
*/
public void setAnno(int anno) {
this.anno = anno;
}
/**
* @return the directorAdmision
*/
public String getDirectorAdmision() {
return directorAdmision;
}
/**
* @param directorAdmision the directorAdmision to set
*/
public void setDirectorAdmision(String directorAdmision) {
this.directorAdmision = directorAdmision;
}
/**
* @return the resultado
*/
public String getResultado() {
return resultado;
}
/**
* @param resultado the resultado to set
*/
public void setResultado(String resultado) {
this.resultado = resultado;
}
}
<file_sep>package datos;
public class RealizarSolicitudCoordinador implements SolicitudStrategy {
@Override
public DTOSolicitud registrarSolicitud(Solicitante solicitante, Periodo periodoLectivo, int codigoCurso, Estudiante estudiante, InconsistenciaEnum inconsistencia, String descripcion, Object evidencia) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
<file_sep>package test;
import controlador.Excel;
import gui.PanelSolicitudes;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import jxl.Cell;
public class UITestCarga
{
private final PanelSolicitudes panel;
public UITestCarga(PanelSolicitudes pPanel)
{
this.panel = pPanel;
}
public ArrayList<TestClass> getData()
{
try{
Excel excel = new Excel("C:\\Users\\USER\\Desktop\\LibroPrueba.xls");
ArrayList<TestClass> testList = new ArrayList<>();
int rows = excel.getSheet().getRows();
int columns = excel.getSheet().getColumns();
for(int i = 0; i < rows; i++)
{
ArrayList<Cell> cells = new ArrayList<>();
for(int j = 0; j < columns; j++)
{
Cell cell = excel.getSheet().getCell(j, i);
System.out.println(cell.getContents());
cells.add(cell);
}
TestClass testClass = new TestClass(cells.get(0).getContents(), cells.get(1).getContents());
testList.add(testClass);
}
return testList;
} catch (Exception ex)
{
return null;
}
}
public void populateTable()
{
DefaultTableModel model = (DefaultTableModel) panel.getTablaSolicitudes().getModel();
Object rowData [] = new Object[4];
ArrayList<TestClass> data = getData();
for(int i = 0; i < data.size(); i++)
{
rowData[0] = data.get(i).getTextOne();
rowData[1] = data.get(i).getTextTwo();
model.addRow(rowData);
}
}
}
<file_sep>package controlador;
import datos.DTOSolicitud;
import java.util.ArrayList;
public class DatosSolicitudes
{
private ArrayList<DTOSolicitud> solicitudes;
private static DatosSolicitudes instance;
private DatosSolicitudes()
{
}
public static DatosSolicitudes getInstance()
{
if(instance == null)
instance = new DatosSolicitudes();
return instance;
}
public DTOSolicitud getSolicitudCodigo(String pCodigo)
{
for(DTOSolicitud solicitud: solicitudes)
{
if(solicitud.getCodigo().equals(pCodigo))
{
return solicitud;
}
}
System.out.println("Error");
return null;
}
public ArrayList<DTOSolicitud> getSolicitudes() {
return solicitudes;
}
public void setSolicitudes(ArrayList<DTOSolicitud> solicitudes) {
this.solicitudes = solicitudes;
}
}
| 8b8764405c185cfecccff4f81108f92de661aa19 | [
"Java",
"INI"
] | 19 | Java | luisdiego19/NewTest | 3aa94a506f340a5dd06cf10edd359c089ecd0f1c | ed27a8f5f9d5d11d7dbe0e5a8fb0bd0c727272fe |
refs/heads/master | <repo_name>mrSlack/steps-OnTimer1<file_sep>/steps-OnTimer1.ino
#include "TimerOne.h"
#include "Step.h"
byte i;
const int stepsPerRevolution = 200;
Stepper secStepper(stepsPerRevolution, 13, 12, 11, 10);
Stepper minStepper(stepsPerRevolution, 9, 8, 7, 6);
void setup() {
i=0;
Timer1.initialize(200000); // Set 200ms interrupt
Timer1.attachInterrupt(Timer1_action); // attach interrupt handler
}
void Timer1_action(){
i++;
secStepper.step(1);
if ( i >= 60 ) {
minStepper.step(1);
i=0;
}
}
void loop() {
}
| 28cffd589f5b81ba248317dcd24d142f18457c1b | [
"C++"
] | 1 | C++ | mrSlack/steps-OnTimer1 | 2c4db5e8068e9c10b862849e4dd0ee6abb97ab9e | 8bef0edd7206e8da807942da9877cc686db56ce1 |
refs/heads/master | <file_sep>package com.android.raspicontrol;
import com.android.control.Function;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity implements
ActionBar.TabListener {
// Khai bao bien
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
public static String ip;
private String[] tabs = { "Setting", "Streaming", "About" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
ip="192.168.1.111";
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab()
.setText(tab_name)
.setTabListener(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onDestroy() {
super.onDestroy();
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position)
{
switch (position)
{
case 0: return new SettingFrame();
case 1: return new StreamingFrame();
case 2: return new AboutFrame();
}
return null;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
| af1b1cd0825e75d2f3c749ef631197293911fdce | [
"Java"
] | 1 | Java | trongnhanuit/RaspiControl | b6fcedeb6209bf9eecbb16c247cd697976acc05b | fcdd70cbba441fb4b85d6b24edb38b035cbf02ab |
refs/heads/master | <file_sep>import numpy as np
import scipy.optimize
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(
rc={
"grid.alpha": 1.0,
"grid.color": "black",
"grid.linestyle": "-",
"grid.linewidth": 0.1,
"axes.facecolor": "white",
"axes.titlesize": 20.0,
"axes.labelsize": 14.0,
"font.sans-serif": ["Futura", "sans-serif"],
"figure.figsize": [14.0, 6.0],
"legend.shadow": False,
}
)
sns.set_palette(["#16315a", "#ff4800", "#c4d82e", "#000000", "#8C8C8C", "#27AAE1"])
class LogisticCurve:
def __init__(self, parameters: tuple = (1, 1, 100)):
self.fit_errors = None
self.duration = None
self.total_cases = None
self.optimized_parameters = None
self.duration_errors = None
self.total_cases_errors = None
self.optimized_parameters = None
self.parameters = parameters
self.exponential_decay_model = lambda x, C, k: C * np.exp((-k * x))
self.logistic_model = lambda x, a, b, c: c / (1 + np.exp(-(x - b) / a))
def fit(self, y: np.array):
X = np.arange(0, len(y))
optimized_fit = scipy.optimize.curve_fit(
self.logistic_model,
X,
y,
self.parameters,
maxfev=100000,
bounds=(0, [50, 50, 300000]),
)
self.optimized_parameters = optimized_fit[0]
(
duration_predictions,
total_cases_predictions,
) = self._get_predictions_recursively(y)
self.duration_errors = self._get_error_curve(duration_predictions)
self.total_cases_errors = self._get_error_curve(total_cases_predictions)
self.fit_errors = [np.sqrt(optimized_fit[1][i][i]) for i in [0, 1, 2]]
def predict(self, y: np.array):
a, b, c = self.optimized_parameters
if None in (a, b, c):
raise ValueError("You must fit this model first! Call the .fit() method")
X = np.arange(0, len(y)).tolist()
self.total_cases = np.round(c, 0)
self.duration = int(
scipy.optimize.fsolve(lambda x: self.logistic_model(x, a, b, c) - int(c), b)
)
X_pred = np.concatenate([X, np.arange(max(X) + 1, self.duration)])
y_pred = [self.logistic_model(i, a, b, c) for i in X_pred]
y_pred = np.array(y_pred)
duration_upper = self.duration + (
self.duration * self.duration_errors[-1]
) # self.fit_errors[0])
total_cases_upper = c + (c * self.total_cases_errors[-1])
X_pred_upper = np.concatenate([X, np.arange(max(X) + 1, duration_upper)])
y_pred_upper = [
self.logistic_model(i, a, b, total_cases_upper) for i in X_pred_upper
]
y_pred_upper = np.concatenate([y_pred[: len(y)], y_pred_upper[len(y) + 1 :]])
duration_lower = self.duration - (self.duration * self.fit_errors[0])
total_cases_lower = c - (c * (self.fit_errors[2] / c))
X_pred_lower = np.concatenate([X, np.arange(max(X) + 1, duration_lower)])
y_pred_lower = [
self.logistic_model(i, a, b, total_cases_lower) for i in X_pred_lower
]
y_pred_lower = np.concatenate([y_pred[: len(y)], y_pred_lower[len(y) + 1 :]])
return y_pred, (y_pred_upper, y_pred_lower)
def _get_predictions_recursively(self, y):
duration_predictions = list()
total_cases_predictions = list()
for i in range(1, len(y) + 1):
y_ = y[:i]
X_ = np.arange(0, len(y_))
optimized_fit = scipy.optimize.curve_fit(
self.logistic_model,
X_,
y_,
(1, 1, 100),
maxfev=100000,
bounds=(0, [50, 50, 300000]),
)
a, b, c = optimized_fit[0]
duration = int(
scipy.optimize.fsolve(
lambda x: self.logistic_model(x, a, b, c) - int(c), b
)
)
total_cases = np.round(c, 0)
duration_predictions.append(duration)
total_cases_predictions.append(total_cases)
return duration_predictions, total_cases_predictions
def _get_error_curve(self, predictions):
y_mean = [predictions[0]]
for i in range(2, len(predictions) + 1):
w = list([x ** 3 for x in range(1, len(predictions[:i]) + 1)])
m = np.average(list(predictions[:i]), weights=w)
y_mean.append(m)
# calculate error at each time step
real_value = np.mean(y_mean[-1])
error = (predictions - real_value) / real_value
# fit an exponential decay curve
error_fit, error_cov = scipy.optimize.curve_fit(
self.exponential_decay_model,
range(len(error)),
abs(error),
[1, 0.1],
maxfev=10000,
)
tdata = np.arange(0, len(error))
error_curve = [
self.exponential_decay_model(i, error_fit[0], error_fit[1]) for i in tdata
]
return error_curve
def plot(self, y, title: str = "", ylab: str = ""):
self.fit(y)
y_pred, (y_pred_upper, y_pred_lower) = self.predict(y)
lower_duration = len(y_pred_lower)
upper_duration = len(y_pred_upper)
y_pred = np.concatenate(
[y_pred, [max(y_pred)] * (upper_duration - len(y_pred))]
)
y_pred_lower = np.concatenate(
[y_pred_lower, [max(y_pred_lower)] * (upper_duration - len(y_pred_lower))]
)
title += (
"\nEstimated duration of virus spread from today: "
+ str(lower_duration - len(y))
+ " to "
+ str(upper_duration - len(y))
+ " days"
)
ylab += ("Number of total cases")
plt.title(title)
plt.plot(range(len(y_pred)), y_pred, label="Predicted")
plt.scatter(range(len(y)), y, label="Actuals")
plt.fill_between(
range(len(y_pred_upper)),
y_pred_lower,
y_pred_upper,
color=sns.color_palette()[4],
alpha=0.15,
label="Confidence Interval",
)
plt.ylabel(ylab)
plt.xlabel('Days from first infection case')
plt.legend()
plt.show()
<file_sep># Logistic Growth Model for estimating Corona Virus spread
The purpose of this model is to estimate the duration and the total number of cases of the [COVID-19](https://www.who.int/emergencies/diseases/novel-coronavirus-2019/) spread by country.
## Data source
The model reads data from the [data repository](https://github.com/CSSEGISandData/COVID-19) for the 2019 Novel Coronavirus Visual Dashboard operated by the Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE)
## How to use
1. Clone the repo to your local machine and install the package:
```bash
# go to the repo directory and run from the terminal:
pip install -e .
```
2. Import the functions:
```python
# in Python
from data import corona.read_covid_cases
from models import corona.LogisticCurve
```
3. Download data for a specific country:
```python
df = read_covid_cases(countries=["ITALY"])
```
4. Fit the Logistic Growth Model
```python
# select "confirmed" to predict cases or "deaths" for fatalities
y = df["confirmed"].values
lc = LogisticCurve()
lc.fit(y)
```
5. Run predictions
```python
y_pred, (y_pred_upper, y_pred_lower) = lc.predict(y)
```
6. Plot results
```python
lc.plot(y)
```
## Output example
<p align="center">
<img src="italy prediction.png" width=8700>
</p>
<file_sep>""" Setup script for package """
from setuptools import setup, find_packages
with open("requirements.txt") as reqs:
requirements = reqs.read().splitlines()
setup(
name="corona",
version="0.0.1",
packages=find_packages(),
install_requires=requirements,
python_requires=">=3.5"
)
<file_sep>""" Defines functions for importing data"""
from pathlib import Path
from functools import reduce
import logging
import inflection
import numpy as np
import pandas as pd
logger = logging.getLogger()
def read_covid_cases(
countries: list = None
) -> pd.DataFrame:
"""
Returns number of COVID-19 confirmed cases, deaths, and recovered cases
as a pandas DataFrame. Data will be streamed from Github every time this
function is called to ensure the most recent data is available.
Args
countries: A list of countries to subset by
Returns
df_cases: A pandas DataFrame
"""
base_url = (
"https://raw.githubusercontent.com/CSSEGISandData/"
"COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/"
"time_series_19-covid-{field}.csv"
)
dfs = list()
for field in ["Confirmed", "Recovered", "Deaths"]:
df_cases_ = pd.melt(
pd.read_csv(base_url.format(field=field)),
id_vars=["Province/State", "Country/Region", "Lat", "Long"],
var_name="Date",
value_name=field,
)
df_cases_.columns = [
inflection.underscore(col).replace(" ", "_").replace("/", "_")
for col in df_cases_.columns
]
df_cases_["date"] = pd.to_datetime(df_cases_["date"])
dfs.append(df_cases_)
df_cases = reduce(
lambda left, right: pd.merge(
left,
right,
on=["date", "country_region", "province_state", "lat", "long"],
how="left",
),
dfs,
)
mask = (df_cases[["confirmed", "recovered", "deaths"]] > 0).any(1)
df_cases = df_cases[mask]
df_cases[["country_region", "province_state"]] = df_cases[
["country_region", "province_state"]
].fillna("UNKNOWN")
df_cases[["confirmed", "recovered", "deaths"]] = df_cases[
["confirmed", "recovered", "deaths"]
].fillna(0)
for column in df_cases.dtypes[df_cases.dtypes == "object"].index.values:
df_cases[column] = df_cases[column].str.upper()
if countries:
countries = [c.upper() for c in countries]
groupby = ["country_region"]
for country in countries:
if country not in df_cases["country_region"].unique():
countries_ = str(df_cases["country_region"].unique())
error = "Country " + country + " is not in \n" + countries_
logger.error(error)
raise ValueError(error)
df_cases = df_cases[df_cases["country_region"].isin(countries)]
else:
groupby = ["country_region", "province_state"]
df_cases = df_cases.groupby(["date"] + groupby).sum().reset_index()
df_cases["virus_active"] = np.where(df_cases["confirmed"] > 0, 1, 0)
df_cases["virus_active20"] = np.where(df_cases["confirmed"] > 20, 1, 0)
df_cases["days_active"] = df_cases.groupby(groupby)["virus_active"].apply(
lambda x: x.cumsum()
)
df_cases["days_active20"] = df_cases.groupby(groupby)["virus_active20"].apply(
lambda x: x.cumsum()
)
df_cases["total_active"] = df_cases["confirmed"] - df_cases["recovered"]
df_cases["new_cases"] = df_cases.groupby(groupby)["confirmed"].diff()
df_cases = df_cases[
["date"]
+ groupby
+ [
"confirmed",
"recovered",
"deaths",
"virus_active",
"virus_active20",
"days_active",
"days_active20",
"total_active",
"new_cases",
]
]
return df_cases
<file_sep>numpy
pandas
matplotlib
seaborn
jupyter
inflection | f1feb1e6485fc5f74cd747bc06054b46627a4c5e | [
"Markdown",
"Python",
"Text"
] | 5 | Python | pvilar/predict-covid-cases | a5b82534bd85a8f908effdc99d5e63b3a07272be | 79477b643fea5b5c260c7bfda0604b00b33c5fab |
refs/heads/main | <repo_name>AssTrahanec/BmpDownscaling<file_sep>/Project9/BitMapInfoHeader.cpp
#include <iostream>
#include "Converter.h"
#include "BitmapInfoHeader.h"
using namespace std;
void BitmapInfoHeader::parse(char* bytes) {
bisize = Converter::getuint32(bytes, 14);
width = Converter::getuint32(bytes, 18);
height= Converter::getuint32(bytes, 22);
planes = Converter::getuint16(bytes, 26);
bitcount = Converter::getuint16(bytes, 28);
compression = Converter::getuint32(bytes, 30);
sizeimage = Converter::getuint32(bytes, 34);
xpelspermeter = Converter::getuint32(bytes, 38);
ypelspermeter = Converter::getuint32(bytes, 42);
clrused = Converter::getuint32(bytes, 46);
clrimportant = Converter::getuint32(bytes, 50);
}
char* BitmapInfoHeader::toBytes() {
char* bytes = new char[40];
Converter::setuint32(bisize, bytes, 0);
Converter::setuint32(width, bytes, 4);
Converter::setuint32(height, bytes, 8);
Converter::setuint16(planes, bytes, 12);
Converter::setuint16(bitcount, bytes, 14);
Converter::setuint32(compression, bytes, 16);
Converter::setuint32(sizeimage, bytes, 20);
Converter::setuint32(xpelspermeter, bytes, 24);
Converter::setuint32(ypelspermeter, bytes, 28);
Converter::setuint32(clrused, bytes, 32);
Converter::setuint32(clrimportant, bytes, 36);
return bytes;
}
uint32_t BitmapInfoHeader::getHeight() {
return height;
}
uint32_t BitmapInfoHeader::getWidth() {
return width;
}
void BitmapInfoHeader::setWidth(uint32_t width)
{
this->width = width;
}
void BitmapInfoHeader::setHeight(uint32_t height)
{
this->height = height;
}
void BitmapInfoHeader::setSizeImage(uint32_t sizeimage)
{
this->sizeimage = sizeimage;
}
<file_sep>/Project9/Converter.cpp
#include <iostream>
#include "Converter.h"
uint8_t Converter::getuint8(char* bytes, size_t pos) {
return uint32_t((unsigned char)(bytes[pos]));
}
uint16_t Converter::getuint16(char* bytes, size_t pos) {
return uint32_t((unsigned char)(bytes[pos]) | (unsigned char)(bytes[pos + 1]) << 8);
}
uint32_t Converter::getuint32(char* bytes, size_t pos) {
return uint32_t ((unsigned char)(bytes[pos]) | (unsigned char)(bytes[pos + 1]) << 8 | (unsigned char)(bytes[pos + 2]) << 16 | (unsigned char)(bytes[pos + 3]) << 24);
}
void Converter::setuint8(uint8_t x, char* bytes, size_t pos) {
bytes[pos] = x;
}
void Converter::setuint16(uint16_t x, char* bytes, size_t pos) {
bytes[pos] = x;
bytes[pos + 1] = x >> 8;
}
void Converter::setuint32(uint32_t x, char* bytes, size_t pos) {
bytes[pos] = x;
bytes[pos + 1] = x >> 8;
bytes[pos + 2] = x >> 16;
bytes[pos + 3] = x >> 24;
}<file_sep>/Project9/Image.cpp
#include "Image.h"
#include <fstream>
Image::Image() {
palette = (Pixel*)malloc(sizeof(Pixel) * 256);
for (size_t i = 0; i < 256; i++) {
palette[i] = Pixel(i);
}
for (size_t i = 0; i < 10005; i++) {
pixels[i] = new uint8_t[10005];
}
}
Image::~Image() {
delete[] palette;
for (size_t i = 0; i < 10005; i++) {
delete[] pixels[i];
}
delete[] pixels;
}
void Image::loadFromFile(string path) {
std::ifstream infile(path, std::ios_base::binary);
char *buffer = new char[11000 * 10000];
infile.seekg(0, infile.end);
int length = infile.tellg();
infile.seekg(0, infile.beg);
infile.read(buffer, length);
infile.close();
fileHeader.parse(buffer);
infoHeader.parse(buffer);
for (size_t i = 0; i < 256; i++) {
palette[i].parse(buffer);
}
size_t rowSize = infoHeader.getWidth() + (4 - infoHeader.getWidth() % 4);
for (size_t i = 0; i < infoHeader.getHeight(); i++) {
for (size_t j = 0; j < rowSize; j++) {
pixels[i][j] = Converter::getuint8(buffer, 54 + 256 * 4 + i * rowSize + j);
}
}
delete[] buffer;
}
void Image::saveToFile(string path) {
size_t rowSize = infoHeader.getWidth() + (4 - infoHeader.getWidth() % 4);
char* buffer = new char[54 + 256 * 4 + rowSize * infoHeader.getHeight()];
char* fhb = fileHeader.toBytes();
char* ihb = infoHeader.toBytes();
for (size_t i = 0; i < 14; i++) {
buffer[i] = fhb[i];
}
for (size_t i = 14; i < 54; i++) {
buffer[i] = ihb[i - 14];
}
for (size_t i = 0; i < 256; i++) {
char* palettebuffer = palette[i].toBytes();
for (size_t j = 0; j < 4; j++) {
buffer[54 + i * 4 + j] = palettebuffer[j];
}
delete[] palettebuffer;
}
for (size_t i = 0; i < infoHeader.getHeight(); i++) {
for (size_t j = 0; j < rowSize; j++) {
buffer[54 + 256 * 4 + i * rowSize + j] = pixels[i][j];
}
}
ofstream fout(path,ofstream::binary);
fout.write(buffer, 54 + 256 * 4 + rowSize * infoHeader.getHeight());
fout.close();
delete[] buffer;
delete[] fhb;
delete[] ihb;
}
void Image::downscale(size_t v, size_t h) {
if (infoHeader.getHeight() % v != 0 || infoHeader.getWidth() % h != 0)
return;
uint32_t height = infoHeader.getHeight() / v;
uint32_t width = infoHeader.getWidth() / h;
size_t rowSize = width + ((4 - width % 4)) % 4;
uint8_t** newpixels = new uint8_t*[10005];
for (size_t i = 0; i < 10005; i++) {
newpixels[i] = new uint8_t[10005];
}
for (size_t i = 0; i < height; i++) {
for (size_t j = 0; j < rowSize; j++) {
if(j >= width){
newpixels[i][j] = 0;
}
else
newpixels[i][j] = pixels[i*v][j*h];
}
}
infoHeader.setHeight(height);
infoHeader.setWidth(width);
infoHeader.setSizeImage(height * rowSize);
fileHeader.setbmpSize(54 + 256 * 4 + height * rowSize);
for (size_t i = 0; i < 10005; i++) {
delete[] pixels[i];
}
delete[] pixels;
pixels = newpixels;
}<file_sep>/Project9/Source.cpp
#include "BitmapInfoHeader.h"
#include "BitmapFileHeader.h"
#include "Pixel.h"
#include "Image.h"
#include <fstream>
int main()
{
{Image a;
a.loadFromFile("original.bmp");
a.saveToFile("copy.bmp");
a.downscale(2, 2);
a.saveToFile("downscale.bmp");
}
system("pause");
}<file_sep>/Project9/BitmapFileHeader.h
#ifndef BITMAP_FILE_HEADER_H
#define BITMAP_FILE_HEADER_H
#include <iostream>
#include "Converter.h"
class BitmapFileHeader {
private:
uint16_t bfType = 0x4D42;
uint32_t bmpSize;
uint16_t reserved1 = 0;
uint16_t reserved2 = 0;
uint32_t offBits;
public:
void parse(char* bytes);
char* toBytes();
void setbmpSize(uint32_t bmpSize);
};
#endif<file_sep>/Project9/Pixel.h
#ifndef PIXEL_H
#define PIXEL_H
#include <iostream>
class Pixel {
private:
uint8_t blue;
uint8_t green;
uint8_t red;
uint8_t reserved;
size_t palettePosition;
public:
Pixel(size_t palettePosition);
void parse(char* byte);
char* toBytes();
};
#endif
<file_sep>/Project9/BitmapInfoHeader.h
#ifndef BITMAP_INFO_HEADER_H
#define BITMAP_INFO_HEADER_H
#include <iostream>
#include "Converter.h"
class BitmapInfoHeader {
private:
uint32_t bisize = 40;
uint32_t width;
uint32_t height;
uint16_t planes;
uint16_t bitcount;
uint32_t compression = 0;
uint32_t sizeimage;
uint32_t xpelspermeter = 0;
uint32_t ypelspermeter = 0;
uint32_t clrused;
uint32_t clrimportant;
public:
void parse(char* bytes);
char* toBytes();
uint32_t getHeight();
uint32_t getWidth();
void setWidth(uint32_t width);
void setHeight(uint32_t height);
void setSizeImage(uint32_t sizeimage);
};
#endif<file_sep>/Project9/BitmapFileHeader.cpp
#include <iostream>
#include "Converter.h"
#include "BitmapFileHeader.h"
using namespace std;
void BitmapFileHeader::parse(char* bytes) {
bfType = Converter::getuint16(bytes, 0);
bmpSize = Converter::getuint32(bytes, 2);
reserved1 = Converter::getuint16(bytes, 6);
reserved2 = Converter::getuint16(bytes, 8);
offBits = Converter::getuint32(bytes, 10);
}
char* BitmapFileHeader::toBytes() {
char* bytes = new char[14];
Converter::setuint16(bfType, bytes, 0);
Converter::setuint32(bmpSize, bytes, 2);
Converter::setuint16(reserved1, bytes, 6);
Converter::setuint16(reserved2, bytes, 8);
Converter::setuint32(offBits, bytes, 10);
return bytes;
}
void BitmapFileHeader::setbmpSize(uint32_t bmpSize)
{
this->bmpSize = bmpSize;
}
<file_sep>/Project9/Converter.h
#ifndef CONVERTER_H
#define CONVERTER_H
#include <iostream>
static class Converter {
public:
static uint8_t getuint8(char* bytes, size_t pos);
static uint16_t getuint16(char* bytes, size_t pos);
static uint32_t getuint32(char* bytes, size_t pos);
static void setuint8(uint8_t x, char* bytes, size_t pos);
static void setuint16(uint16_t x, char* bytes, size_t pos);
static void setuint32(uint32_t x, char* bytes, size_t pos);
};
#endif<file_sep>/Project9/Image.h
#ifndef IMAGE_H
#define IMAGE_H
#include <iostream>
#include "BitmapFileHeader.h"
#include "BitmapInfoHeader.h"
#include "Pixel.h"
#include <string>
using namespace std;
class Image{
private:
BitmapFileHeader fileHeader;
BitmapInfoHeader infoHeader;
Pixel* palette;
uint8_t** pixels = new uint8_t*[10005];
public:
Image();
void loadFromFile(string path);
void saveToFile(string path);
~Image();
void downscale(size_t v,size_t h);
};
#endif
<file_sep>/Project9/Pixel.cpp
#include "Pixel.h"
#include "Converter.h"
Pixel::Pixel(size_t palettePosition) {
this->palettePosition = palettePosition;
}
void Pixel::parse(char* bytes) {
blue = Converter::getuint8(bytes, palettePosition * 4 + 54);
green = Converter::getuint8(bytes, palettePosition * 4 + 1 + 54);
red = Converter::getuint8(bytes, palettePosition * 4 + 2 + 54);
reserved = Converter::getuint8(bytes, palettePosition * 4 + 3 + 54);
}
char* Pixel::toBytes() {
char* bytes = new char[4];
Converter::setuint8(blue, bytes, 0);
Converter::setuint8(green, bytes, 1);
Converter::setuint8(red, bytes, 2);
Converter::setuint8(reserved, bytes, 3);
return bytes;
}
| c83ea169be4677f23f1a4815776bfa1d85af3233 | [
"C++"
] | 11 | C++ | AssTrahanec/BmpDownscaling | a18595ec0f49ef6468b52c9e762da8d143251ec0 | 0093beab73535b43a4126fad6935bde6ca1c79f2 |
refs/heads/master | <file_sep>#!/usr/bin/Rscript
#Description: This script runs in a bash terminal. you must supply three positonal arguments
# 1. 4D Nifti Dataset
# 2. Binary Roi mask
# 3. Desired ouput file name
### commands that will make possible interaction between bash and R
args <- commandArgs(T)
dataset <- as.character(args[1])
roi <- as.character(args[2])
output <- as.character(args[3])
### load packages
library(magrittr)
library(oro.nifti)
library(neurobase)
## read data
func <- RNifti::readNifti(dataset)
roi <- readNIfTI(roi,reorient = FALSE)
d <- dim(func)
### creat mask
func_mask <- niftiarr(img= roi, arr = 0)
func_mask@.Data <- func[,,,1]
func_mask[func_mask !=0] <- 1
### Extract ROI time series
ts <- matrix(func[roi!=0],ncol = d[4]) %>%
colMeans()
## linearize non zero voxels of 4D dataset and compute correlation coeficients with ROI time series in every row of the matrix
rvalues <- matrix(func[func_mask !=0],ncol=d[4]) %>%
apply(.,1,cor,ts)
### reshape computed data to create whole brain map
rmap <- func_mask
rmap[rmap !=0] <- rvalues
### write output in nifti format
write_nifti(rmap,output)
<file_sep>
## a repo to put some data for tutorials
<file_sep>#!/bin/bash
# generate correlation maps
### Required files
### functional image
### ROI mask
### AfNI comand: 3dTcorr1D -prefix <output.nii.gz> -mask <func_mask.nii.gz> <imput.nii.gz > <timeseriesfile.ts>
func=$1
roi_mask=$2
output=$3
### Estract time series
fslmeants -i $func -m $roi_mask -o ${output}.ts
## compute 3dmap
3dTcorr1D -prefix ${output}_rmap.nii.gz $func ${output}.ts
rm ${output}.ts
| c9c0f0209b17476ec3ae4d5b90bc979fbfb57b8c | [
"Markdown",
"R",
"Shell"
] | 3 | R | alffajardo/mri_data | 97f97ddce4ec310fc7ac30e52f0dcea77a1ee832 | 3093704c67538ffa226db8f4b498f5e17f2dc7af |
refs/heads/master | <repo_name>totycro/requests-builder<file_sep>/src/components/wms/WmsRequestPreview.js
import React from 'react';
import { getWmsUrl, getFisUrl } from './wmsRequests';
import { connect } from 'react-redux';
const WmsRequestPreview = ({ wmsState, requestState, mode }) => {
const url = mode === 'WMS' ? getWmsUrl(wmsState, requestState) : getFisUrl(wmsState, requestState);
const handleClipboardCopy = () => {
navigator.clipboard.writeText(url);
};
return (
<>
<h2 className="heading-secondary u-margin-bottom-small">Request Preview (URL)</h2>
<div className="form">
<textarea className="textarea" value={url} readOnly />
<button style={{ width: 'fit-content' }} className="secondary-button" onClick={handleClipboardCopy}>
Copy
</button>
</div>
</>
);
};
const mapStateToProps = (state) => ({
wmsState: state.wms,
requestState: state.request,
mode: state.wms.mode,
});
export default connect(mapStateToProps)(WmsRequestPreview);
<file_sep>/src/components/tpdi/TPDISources.js
import React from 'react';
import { connect } from 'react-redux';
import store, { tpdiSlice } from '../../store';
import AirbusOptions from '../tpdi/AirbusOptions';
import PlanetOptions from '../tpdi/PlanetOptions';
const generateProviderRelatedOptions = (provider) => {
if (provider === 'AIRBUS') {
return <AirbusOptions />;
} else if (provider === 'PLANET') {
return <PlanetOptions />;
}
};
const TPDISources = ({ provider }) => {
const handleChange = (e) => {
store.dispatch(tpdiSlice.actions.setProvider(e.target.value));
};
return (
<>
<h2 className="heading-secondary">Search Options</h2>
<div className="form">
<label className="form__label">Provider</label>
<select className="form__input" value={provider} onChange={handleChange}>
<option value="AIRBUS">Airbus</option>
<option value="PLANET">Planet Scope</option>
</select>
{generateProviderRelatedOptions(provider)}
</div>
</>
);
};
const mapStateToProps = (state) => ({
provider: state.tpdi.provider,
});
export default connect(mapStateToProps)(TPDISources);
<file_sep>/src/components/batch/CancelBatchRequestButton.js
import React from 'react';
import RequestButton from '../RequestButton';
import { addAlertOnError, batchIdValidation } from './BatchActions';
import { cancelBatchRequest } from '../../utils/batchActions';
import { connect } from 'react-redux';
import store, { batchSlice } from '../../store';
const CancelBatchRequestButton = ({ selectedBatchId, token }) => {
const cancelResponseHandler = () => {
store.dispatch(
batchSlice.actions.setExtraInfo('Successfully Cancelled request with Id: ' + selectedBatchId),
);
};
return (
<div>
<RequestButton
validation={batchIdValidation(token, selectedBatchId)}
disabledTitle="Log in and set a batch request to use this"
className="secondary-button"
buttonText="Cancel"
responseHandler={cancelResponseHandler}
errorHandler={addAlertOnError}
request={cancelBatchRequest}
args={[token, selectedBatchId]}
/>
</div>
);
};
const mapStateToProps = (state) => ({
selectedBatchId: state.batch.selectedBatchId,
token: state.auth.user.access_token,
});
export default connect(mapStateToProps)(CancelBatchRequestButton);
<file_sep>/src/components/batch/BatchActions.js
import React from 'react';
import { connect } from 'react-redux';
import store, { alertSlice, batchSlice } from '../../store';
import AnalyseBatchRequestButton from './AnalyseBatchRequestButton';
import StartBatchRequestButton from './StartBatchRequestButton';
import CancelBatchRequestButton from './CancelBatchRequestButton';
import GetSingleRequestButton from './GetSingleRequestButton';
import RestartPartialRequestButton from './RestartPartialRequestButton';
export const addAlertOnError = (err, message) => {
if (err.response && err.response.status === 403) {
store.dispatch(
alertSlice.actions.addAlert({
type: 'WARNING',
text: "You don't have enough permissions to use this",
}),
);
console.error(err);
} else if (message) {
store.dispatch(alertSlice.actions.addAlert({ type: 'WARNING', text: message }));
console.error(err);
} else {
console.error(err);
store.dispatch(alertSlice.actions.addAlert({ type: 'WARNING', text: 'Something went wrong' }));
}
};
//check if valid uuid.
const checkValidId = (id) =>
/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id);
export const batchIdValidation = (token, batchId) => token && checkValidId(batchId);
const BatchActions = ({ selectedBatchId, setFetchedRequests }) => {
const handleBatchIdChange = (e) => {
store.dispatch(batchSlice.actions.setSelectedBatchId(e.target.value));
};
return (
<>
<h2 className="heading-secondary u-margin-top-small">Batch Actions</h2>
<div className="form">
<label className="form__label u-margin-top-tiny">Batch Request Id</label>
<input onChange={handleBatchIdChange} className="form__input" type="text" value={selectedBatchId} />
<div className="buttons-container">
<AnalyseBatchRequestButton />
<StartBatchRequestButton />
<CancelBatchRequestButton />
<RestartPartialRequestButton />
<GetSingleRequestButton setFetchedRequests={setFetchedRequests} />
</div>
</div>
</>
);
};
const mapStateToProps = (state) => ({
selectedBatchId: state.batch.selectedBatchId,
});
export default connect(mapStateToProps)(BatchActions);
<file_sep>/src/components/catalog/CatalogSendRequest.js
import React from 'react';
import { connect } from 'react-redux';
import store, { catalogSlice } from '../../store';
import CatalogSendRequestButton from './CatalogSendRequestButton';
import CatalogSendRequestNextButton from './CatalogSendRequestNextButton';
//limit, get next, send
const CatalogSendRequest = ({ limit, next, setResults }) => {
const handleLimitChange = (e) => {
store.dispatch(catalogSlice.actions.setLimit(parseInt(e.target.value)));
};
return (
<>
<h2 className="heading-secondary u-margin-top-small">Request Options</h2>
<div className="form">
<label className="form__label">Limit</label>
<input onChange={handleLimitChange} value={limit} className="form__input" type="number" />
<label className="form__label">Next</label>
<input value={next} className="form__input" type="number" readOnly />
<div className="buttons-container">
<CatalogSendRequestButton setResults={setResults} />
{next ? <CatalogSendRequestNextButton setResults={setResults} /> : null}
</div>
</div>
</>
);
};
const mapStateToProps = (state) => ({
limit: state.catalog.limit,
next: state.catalog.next,
});
export default connect(mapStateToProps)(CatalogSendRequest);
<file_sep>/src/components/Toggle.js
import React from 'react';
const Toggle = ({ onChange, className, id, checked, name, defaultChecked }) => {
return (
<div className={className ? className : ''}>
<label className="switch">
<input
defaultChecked={defaultChecked}
name={name}
checked={checked}
id={id}
onChange={onChange}
type="checkbox"
/>
<span className="slider round"></span>
</label>
</div>
);
};
export default Toggle;
<file_sep>/src/components/ProcessHeaderButtons.js
import React from 'react';
import SendRequest from './SendRequest';
import AuthHeader from './AuthHeader';
const ProcessHeaderButtons = () => {
return (
<div className="header__buttons">
<SendRequest />
<AuthHeader />
</div>
);
};
export default ProcessHeaderButtons;
<file_sep>/src/components/tpdi/AirbusAdvancedOptions.js
import React, { useEffect } from 'react';
import store, { airbusSlice } from '../../store';
import { connect } from 'react-redux';
const AirbusAdvancedOptions = ({ dataFilterOptions }) => {
const handleMaxCCChange = (e) => {
store.dispatch(airbusSlice.actions.setDataFilterOptions({ maxCloudCoverage: parseInt(e.target.value) }));
};
const handleProcessingLevelChange = (e) => {
store.dispatch(airbusSlice.actions.setDataFilterOptions({ processingLevel: e.target.value }));
};
const handleMaxSnowChange = (e) => {
store.dispatch(airbusSlice.actions.setDataFilterOptions({ maxSnowCoverage: parseInt(e.target.value) }));
};
const handleMaxIncidenceChange = (e) => {
store.dispatch(airbusSlice.actions.setDataFilterOptions({ maxIncidenceAngle: parseInt(e.target.value) }));
};
// Reset to default advanced options on unmount.
useEffect(() => {
return () => {
store.dispatch(airbusSlice.actions.defaultAdvancedOptions());
};
}, []);
return (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<label className="form__label">Cloud Coverage - {dataFilterOptions.maxCloudCoverage} %</label>
<input
value={dataFilterOptions.maxCloudCoverage}
className="form__input form__input--range"
onChange={handleMaxCCChange}
type="range"
min="0"
max="100"
/>
<label className="form__label">Processing Level</label>
<select
value={dataFilterOptions.processingLevel}
className="form__input"
onChange={handleProcessingLevelChange}
>
<option value="DEFAULT">Default</option>
<option value="SENSOR">Sensor</option>
<option value="ALBUM">Album</option>
</select>
<label className="form__label">Snow Coverage - {dataFilterOptions.maxSnowCoverage} %</label>
<input
value={dataFilterOptions.maxSnowCoverage}
className="form__input form__input--range"
onChange={handleMaxSnowChange}
type="range"
min="0"
max="90"
/>
<label className="form__label">Incidence Angle - {dataFilterOptions.maxIncidenceAngle} °</label>
<input
value={dataFilterOptions.maxIncidenceAngle}
className="form__input form__input--range"
onChange={handleMaxIncidenceChange}
type="range"
min="0"
max="90"
/>
</div>
);
};
const mapStateToProps = (state) => ({
dataFilterOptions: state.airbus.dataFilterOptions,
});
export default connect(mapStateToProps)(AirbusAdvancedOptions);
<file_sep>/src/components/batch/BatchInformation.js
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import BatchRequestSummary from './BatchRequestSummary';
import GetAllBatchRequestsButton from './GetAllBatchRequestsButton';
const filterRequestsResults = (searchText, requests) => {
if (searchText === '') {
return requests;
} else {
return requests.filter((req) => {
if (req.description) {
return (
req.description.toLowerCase().includes(searchText.toLowerCase()) || req.id.includes(searchText)
);
} else {
return req.id.includes(searchText);
}
});
}
};
const renderBatchRequestSummary = (requests, limit, token) => {
let res = [];
for (let i = 0; i < requests.length; i++) {
if (i > limit) {
break;
}
res.push(<BatchRequestSummary token={token} key={requests[i].id} props={requests[i]} />);
}
return res;
};
const BatchInformation = ({ fetchedRequests, extraInfo, setFetchedRequests, token }) => {
const [searchText, setSearchText] = useState('');
const [filteredRequests, setFilteredRequests] = useState(fetchedRequests);
// limit to render amount of BatchRequestSummary
const [limit, setLimit] = useState(50);
useEffect(() => {
if (fetchedRequests.length > 0) {
setFilteredRequests(filterRequestsResults(searchText, fetchedRequests));
} else {
setFilteredRequests([]);
}
}, [fetchedRequests, searchText]);
const handleSearchTextChange = (e) => {
setSearchText(e.target.value);
};
// Check if scroll is in the bottom and update limit if it is.
const handleScroll = (e) => {
const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) {
setLimit(limit + 50);
}
};
return (
<>
<h2 className="heading-secondary">Batch Information</h2>
<div className="form">
<GetAllBatchRequestsButton setFetchedRequests={setFetchedRequests} />
<hr className="u-margin-top-small u-margin-bottom-small" />
<input
value={searchText}
onChange={handleSearchTextChange}
type="text"
className="form__input"
placeholder="Search Requests"
style={{ width: 'fit-content' }}
/>
{extraInfo !== '' ? (
<>
<p className="text text--info">{extraInfo}</p>
<hr></hr>
</>
) : null}
<div onScroll={handleScroll} style={{ overflowY: 'scroll', maxHeight: '450px' }}>
{filteredRequests.length > 0 ? renderBatchRequestSummary(filteredRequests, limit, token) : null}
</div>
</div>
</>
);
};
const mapStateToProps = (state) => ({
extraInfo: state.batch.extraInfo,
token: state.auth.user.access_token,
});
export default connect(mapStateToProps)(BatchInformation);
<file_sep>/src/components/forms/TPDIRequestForm.js
import React from 'react';
import TPDISourcesAndOptions from '../tpdi/TPDISources';
import TimeRangeSelect from '../input/TimeRangeSelect';
import MapContainer from '../input/MapContainer';
import TPDIOrderOptions from '../tpdi/TPDIOrderOptions';
import TPDIRequestPreview from '../tpdi/TPDIRequestPreview';
import QuotaContainer from '../tpdi/QuotaContainer';
import SearchResultsContainer from '../tpdi/SearchResultsContainer';
import TPDIOrdersContainer from '../tpdi/TPDIOrdersContainer';
// Components needed to do TPDI Requests:
// Timerange + AOI
// TPDI Related options and actions
const TPDIRequestForm = () => {
return (
<div>
<div className="tpdi-first-row">
<div className="tpdi-first-row-first-item">
<TimeRangeSelect />
</div>
<div className="tpdi-first-row-second-item">
<MapContainer />
</div>
</div>
<div className="tpdi-second-row">
<div className="tpdi-second-row-first-item">
<TPDISourcesAndOptions />
</div>
<div className="tpdi-second-row-second-item">
<TPDIOrderOptions />
</div>
<div className="tpdi-second-row-third-item">
<QuotaContainer />
<SearchResultsContainer />
<TPDIOrdersContainer />
</div>
</div>
<div className="tpdi-third-row">
<div className="tpdi-third-row-first-item">
<TPDIRequestPreview />
</div>
</div>
</div>
);
};
export default TPDIRequestForm;
<file_sep>/src/components/wms/WMSHeaderButtons.js
import React from 'react';
import SendWmsRequest from './SendWmsRequest';
import AuthHeader from '../AuthHeader';
const WMSHeaderButtons = () => {
return (
<div className="header__buttons">
<SendWmsRequest />
<AuthHeader />
</div>
);
};
export default WMSHeaderButtons;
<file_sep>/src/components/batch/BatchOptions.js
import React from 'react';
import { connect } from 'react-redux';
import store, { batchSlice } from '../../store';
import Toggle from '../Toggle';
import GetLowResPreviewButton from './GetLowResPreviewButton';
import CreateBatchRequestButton from './CreateBatchRequestButton';
const generateResolutions = (tillingGridId) => {
switch (tillingGridId) {
case 0:
return [10.0, 20.0, 60.0];
case 1:
return [10.0, 20.0];
case 2:
return [60.0, 120.0, 240.0, 360.0];
default:
return [];
}
};
const BatchOptions = ({
resolution,
tillingGrid,
description,
bucketName,
cogOutput,
tilePath,
specifyingBucketName,
setFetchedRequests,
}) => {
const handleGridChange = (e) => {
store.dispatch(batchSlice.actions.setTillingGrid(Number(e.target.value)));
// If 100.08 select 60.0 as resolution.
if (Number(e.target.value) === 2) {
store.dispatch(batchSlice.actions.setResolution(60.0));
}
};
const handleResChange = (e) => {
store.dispatch(batchSlice.actions.setResolution(Number(e.target.value)));
};
const handleBucketNameChange = (e) => {
store.dispatch(batchSlice.actions.setBucketName(e.target.value));
};
const handleDescriptionChange = (e) => {
store.dispatch(batchSlice.actions.setDescription(e.target.value));
};
const handleCogOutputChange = () => {
store.dispatch(batchSlice.actions.setCogOutput(!cogOutput));
};
const handleSpecifyingBucketNameChange = () => {
store.dispatch(batchSlice.actions.setSpecifyingBucketName(!specifyingBucketName));
};
const handleTilePathChange = (e) => {
store.dispatch(batchSlice.actions.setDefaultTilePath(e.target.value));
};
return (
<>
<h2 className="heading-secondary">Batch Options</h2>
<div className="form">
<label className="form__label">Tilling Grid</label>
<select className="form__input" value={tillingGrid} onChange={handleGridChange}>
<option value={0}>S2GM Grid</option>
<option value={1}>10km Grid</option>
<option value={2}>100,08km Grid</option>
</select>
<label className="form__label">Resolution</label>
<select className="form__input" value={resolution} onChange={handleResChange}>
{generateResolutions(tillingGrid).map((res) => {
return (
<option key={res} value={res}>
{res}
</option>
);
})}
</select>
<label className="form__label">Bucket Name</label>
<input className="form__input" type="text" onChange={handleBucketNameChange} value={bucketName} />
<label className="form__label">Description</label>
<input className="form__input" type="text" onChange={handleDescriptionChange} value={description} />
<div className="toggle-with-label">
<label htmlFor="cogOutput" className="form__label">
COG Output
</label>
<Toggle id="cogOutput" onChange={handleCogOutputChange} checked={cogOutput} />
</div>
<div className="toggle-with-label">
<label htmlFor="specify-bucket" className="form__label">
{!specifyingBucketName ? 'Specifying Tile Path' : 'Specifying bucket name'}
</label>
<Toggle
checked={specifyingBucketName}
onChange={handleSpecifyingBucketNameChange}
id="specify-bucket"
/>
</div>
{!specifyingBucketName ? (
<>
<div className="label-with-info">
<label className="form__label">Tile Path</label>
<span
className="info"
title="Use this to specify the path on your bucket. Input text comes after: 's3://<your-bucket>/<input-text-here>'"
>
ℹ
</span>
</div>
<input className="form__input" type="text" onChange={handleTilePathChange} value={tilePath} />
</>
) : null}
<div className="buttons-container">
<GetLowResPreviewButton />
<CreateBatchRequestButton setFetchedRequests={setFetchedRequests} />
</div>
</div>
</>
);
};
const mapStateToProps = (store) => ({
resolution: store.batch.resolution,
tillingGrid: store.batch.tillingGrid,
description: store.batch.description,
bucketName: store.batch.bucketName,
cogOutput: store.batch.cogOutput,
specifyingBucketName: store.batch.specifyingBucketName,
tilePath: store.batch.defaultTilePath,
});
export default connect(mapStateToProps)(BatchOptions);
<file_sep>/src/utils/crsTransform.js
import bboxPolygon from '@turf/bbox-polygon';
import proj4 from 'proj4';
import { CRS } from '../utils/const';
import bbox from '@turf/bbox';
import { transformGeometryToWGS84IfNeeded } from '../components/input/MapContainer';
//parsed Geometry -> parsed geo in newCRS
export const transformGeometryToNewCrs = (geometry, toCrs, fromCrs) => {
try {
if (!fromCrs) {
fromCrs = 'EPSG:4326';
}
//bbox
if (geometry.length === 4) {
return transformBboxToNewCrs(geometry, CRS[toCrs].projection, CRS[fromCrs].projection);
}
//polygon
else if (geometry.type === 'Polygon') {
return transformPolygonToNewCrs(geometry, CRS[toCrs].projection, CRS[fromCrs].projection);
} else if (geometry.type === 'MultiPolygon') {
return transformMultiPolygonToNewCrs(geometry, CRS[toCrs].projection, CRS[fromCrs].projection);
}
} catch (err) {
console.error('Invalid geometry', err);
}
};
const getCoordsFromBbox = (bbox) => {
if (bbox.length !== 4) {
throw Error('Not valid bbox');
}
const polygonFromBbox = bboxPolygon(bbox);
return polygonFromBbox.geometry.coordinates;
};
//cords [[[x,y],[x,y]]]
const transformArrayOfCoordinatesToNewCrs = (coords, toProj, fromProj) => {
return [coords[0].map((c) => proj4(fromProj, toProj, c))];
};
export const transformBboxToNewCrs = (bboxToTransform, toProj, fromProj) => {
const bboxCoords = getCoordsFromBbox(bboxToTransform);
const transformedCoords = transformArrayOfCoordinatesToNewCrs(bboxCoords, toProj, fromProj);
const polygon = {
type: 'Polygon',
coordinates: transformedCoords,
};
return bbox(polygon);
};
export const transformPolygonToNewCrs = (polygonToTransform, toProj, fromProj) => {
const transformedCoords = transformArrayOfCoordinatesToNewCrs(
polygonToTransform.coordinates,
toProj,
fromProj,
);
const polygon = {
type: 'Polygon',
coordinates: transformedCoords,
};
return polygon;
};
const transformCoordMultiPolygon = (coords, toProj, fromProj) => {
return [coords[0].map((listOfPairs) => listOfPairs.map((c) => proj4(fromProj, toProj, c)))];
};
const transformMultiPolygonToNewCrs = (multiPolygon, toProj, fromProj) => {
const transformedCoords = transformCoordMultiPolygon(multiPolygon.coordinates, toProj, fromProj);
const resultMultiPolygon = {
type: 'MultiPolygon',
coordinates: transformedCoords,
};
return resultMultiPolygon;
};
export const getTransformedGeometryFromBounds = (bounds) => {
let geo;
if (bounds.geometry) {
geo = bounds.geometry;
} else if (bounds.bbox) {
geo = bounds.bbox;
}
const selectedCrs = Object.keys(CRS).find((key) => CRS[key].url === bounds.properties.crs);
return transformGeometryToWGS84IfNeeded(selectedCrs, geo);
};
<file_sep>/src/components/DataSourceSpecificOptions/BYOCOptions.js
import React, { useEffect, useState } from 'react';
import store, { requestSlice } from '../../store';
import { connect } from 'react-redux';
import { getCustomCollections } from '../../utils/generateRequest';
const generateCollectionOptions = (collections) => {
return collections.map((collection) => (
<option key={collection.id} value={collection.id}>
{collection.name} - {collection.id}
</option>
));
};
const BYOCOptions = ({ dataFilterOptions, token, byocLocation }) => {
const [collections, setCollections] = useState([]);
const handleCollectionIdChange = (e) => {
store.dispatch(requestSlice.actions.setDataFilterOptions({ collectionId: e.target.value }));
};
useEffect(() => {
const loadCustomCollections = async () => {
if (!token) {
return;
}
try {
const res = await getCustomCollections(token, byocLocation);
if (res.data) {
setCollections(res.data.data.map((d) => ({ name: d.name, id: d.id })));
}
} catch (err) {
console.error('Unable to load custom collections', err);
}
};
loadCustomCollections();
}, [token, byocLocation]);
const handleByocLocationChange = (e) => {
store.dispatch(requestSlice.actions.setByocLocation(e.target.value));
};
return (
<div className="byoc-options">
<label className="form__label">Location</label>
<select value={byocLocation} onChange={handleByocLocationChange} className="form__input">
<option value="EU-CENTRAL-1">AWS eu-central-1</option>
<option value="US-WEST-2">AWS us-west-2</option>
</select>
<label className="form__label">Collection Id</label>
<input
required
value={!dataFilterOptions.collectionId ? '' : dataFilterOptions.collectionId}
onChange={handleCollectionIdChange}
type="text"
className="form__input"
/>
{collections.length > 0 ? (
<>
<label className="form__label">Personal collections</label>
<select onChange={handleCollectionIdChange} className="form__input">
<option value="">Select a custom collection</option>
{generateCollectionOptions(collections)}
</select>
</>
) : null}
</div>
);
};
const mapStateToProps = (state) => ({
dataFilterOptions: state.request.dataFilterOptions[0].options,
token: state.auth.user.access_token,
byocLocation: state.request.byocLocation,
});
export default connect(mapStateToProps)(BYOCOptions);
<file_sep>/src/components/DataSourceSpecificOptions/BasicOptions.js
import React, { useState, useEffect } from 'react';
import store, { requestSlice } from '../../store';
import BaseOptionsNoCC from './BaseOptionsNoCC';
import { connect } from 'react-redux';
//Options appliable to all CC Datasources
const BasicOptions = ({ stateMaxCC, idx }) => {
const [maxCC, setMaxCC] = useState('100');
const handleCCChange = (e) => {
setMaxCC(e.target.value);
};
useEffect(() => {
if (maxCC === '100') {
store.dispatch(requestSlice.actions.setDataFilterOptions({ maxCloudCoverage: 'DEFAULT', idx }));
} else {
store.dispatch(requestSlice.actions.setDataFilterOptions({ maxCloudCoverage: maxCC, idx }));
}
}, [maxCC, idx]);
useEffect(() => {
if (stateMaxCC && stateMaxCC !== 'DEFAULT') {
setMaxCC(stateMaxCC);
}
}, [stateMaxCC]);
return (
<div>
<label className="form__label">Cloud Coverage</label>
<div style={{ display: 'flex', alignItems: 'center' }}>
<input
className="form__input form__input--range"
type="range"
min="0"
max="100"
value={maxCC}
onChange={handleCCChange}
style={{ display: 'inline-block' }}
/>
<p className="text" style={{ display: 'inline-block', marginLeft: '1.5rem', marginBottom: '0.8rem' }}>
{maxCC ? maxCC + ' %' : 'Default'}
</p>
</div>
<BaseOptionsNoCC withCC={true} idx={idx} />
</div>
);
};
const mapStateToProps = (store, ownProps) => ({
stateMaxCC: store.request.dataFilterOptions[ownProps.idx].options.maxCloudCoverage,
});
export default connect(mapStateToProps)(BasicOptions);
<file_sep>/src/components/input/TimeRangeSelect.js
import React from 'react';
import moment from 'moment';
import store, { requestSlice } from '../../store';
import { connect } from 'react-redux';
import { DATAFUSION } from '../../utils/const';
import Toggle from '../Toggle';
export const convertUtcDateToInput = (utcDate) => {
if (utcDate) {
return utcDate.split('T')[0];
}
return '';
};
export const returnValidatedTimeFrom = (stringDate) => {
let d = moment.utc(stringDate);
let today = moment().utc().startOf('day');
if (today - d < 0) {
d = today;
}
return d;
};
export const returnValidatedTimeTo = (stringDate) => {
let d = moment.utc(stringDate).endOf('day');
let today = moment().utc().endOf('day');
if (today - d < 0) {
d = today;
}
return d;
};
const multipleTimeRangeIsValid = (mode, datasource) => {
return (mode === 'PROCESS' || mode === 'BATCH') && datasource === DATAFUSION;
};
const TimeRangeSelect = ({ timeFromArray, timeToArray, datasource, isDisabled, mode, datafusionSources }) => {
const generateTimeRanges = () => {
let timerangeLength = multipleTimeRangeIsValid(mode, datasource)
? Math.min(timeFromArray.length, timeToArray.length)
: 1;
let jsxResult = [];
for (let i = 0; i < timerangeLength; i++) {
jsxResult.push(
<div className="timerange" key={i}>
{timerangeLength > 1 ? <label className="form__label">Timerange Datasource {i + 1}</label> : null}
<label className="form__label">From</label>
<input
disabled={isDisabled}
value={convertUtcDateToInput(timeFromArray[i])}
required
className="form__input"
onChange={handleChangeTimeFrom}
type="date"
name={i}
></input>
<label className="form__label">To</label>
<input
disabled={isDisabled}
value={convertUtcDateToInput(timeToArray[i])}
required
className="form__input"
onChange={handleChangeTimeTo}
type="date"
name={i}
></input>
{i > 0 ? (
<button
name={i}
onClick={handleDeleteTimeRange}
className="secondary-button secondary-button--cancel"
>
Delete Timerange
</button>
) : null}
{i < timerangeLength - 1 ? <hr className="u-margin-bottom-tiny u-margin-top-tiny"></hr> : null}
</div>,
);
}
return jsxResult;
};
const canAddTimeRange = () => {
return (
timeFromArray.length < datafusionSources.length &&
timeToArray.length < datafusionSources.length &&
multipleTimeRangeIsValid(mode, datasource)
);
};
const handleChangeTimeFrom = (e) => {
let d = returnValidatedTimeFrom(e.target.value);
store.dispatch(
requestSlice.actions.setTimeFrom({
idx: e.target.name,
timeFrom: d.format(),
}),
);
};
const handleChangeTimeTo = (e) => {
let d = returnValidatedTimeTo(e.target.value);
store.dispatch(
requestSlice.actions.setTimeTo({
timeTo: d.format(),
idx: e.target.name,
}),
);
};
const handleDeleteTimeRange = (e) => {
store.dispatch(requestSlice.actions.deleteTimerange(e.target.name));
};
return (
<>
<div className="heading-with-button">
<h2 className="heading-secondary">Time Range</h2>
</div>
<div
className="form"
style={{
overflowY: 'scroll',
maxHeight: `${multipleTimeRangeIsValid(mode, datasource) ? '224px' : ''}`,
}}
>
<div className="toggle-with-label">
<label htmlFor="toggle-timerange" className="form__label">
{isDisabled ? 'Enable timerange' : 'Disable timerange'}
</label>
<Toggle
id="toggle-timerange"
onChange={() => store.dispatch(requestSlice.actions.disableTimerange(!isDisabled))}
defaultChecked={true}
/>
</div>
{generateTimeRanges()}
{canAddTimeRange() ? (
<button
className="secondary-button"
onClick={() => store.dispatch(requestSlice.actions.addTimeRange())}
>
Add Timerange
</button>
) : null}
{canAddTimeRange() ? (
<p className="text u-margin-top-small">
<i>Note: Datasources that don't have a timerange defined will use the first one</i>
</p>
) : null}
</div>
</>
);
};
const mapStateToProps = (store) => ({
timeToArray: store.request.timeTo,
timeFromArray: store.request.timeFrom,
isDisabled: store.request.isTimeRangeDisabled,
datasource: store.request.datasource,
mode: store.request.mode,
datafusionSources: store.request.datafusionSources,
});
export default connect(mapStateToProps)(TimeRangeSelect);
<file_sep>/src/components/CancelablePopUpRequestButton.js
import React, { useRef, useEffect } from 'react';
import { createFileReader } from './SendRequest';
import RequestButton from './RequestButton';
import { calculatePixelSize } from '../utils/bboxRatio';
import store, { responsesSlice } from '../store';
//Abstraction of Request Button.
const CancelablePopUpRequestButton = ({
buttonText,
request,
args,
validation,
className,
requestState,
useShortcut,
}) => {
const readerRef = useRef();
useEffect(() => {
readerRef.current = createFileReader();
}, []);
const responseHandler = (response) => {
const responseUrl = URL.createObjectURL(response);
let dimensions;
if (requestState && requestState.heightOrRes === 'HEIGHT') {
dimensions = calculatePixelSize(requestState.geometry, [requestState.width, requestState.height]);
}
store.dispatch(
responsesSlice.actions.setResponse({
src: responseUrl,
dimensions: dimensions,
isTar: !response.type.includes('image'),
}),
);
};
const errorHandler = (err) => {
if (err.response) {
readerRef.current.readAsText(err.response.data);
} else {
console.error('Something went wrong.', err);
}
};
return (
<RequestButton
className={className}
buttonText={buttonText}
request={request}
args={args}
validation={validation}
responseHandler={responseHandler}
errorHandler={errorHandler}
useShortcut={true}
/>
);
};
export default CancelablePopUpRequestButton;
<file_sep>/src/components/tpdi/generateTPDIRequests.js
import axios from 'axios';
import { generateBounds } from '../../utils/generateRequest';
const BASE_TPDI_URL = 'https://services.sentinel-hub.com/api/v1/dataimport';
//helpers
const getReqConfig = (token, reqConfig) => {
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
...reqConfig,
};
return config;
};
const getAirbusDataFilterOptions = (dataFitlerOptions) => {
let options = {};
for (let key in dataFitlerOptions) {
if (dataFitlerOptions[key] !== 'DEFAULT') {
options[key] = dataFitlerOptions[key];
}
}
return options;
};
const getTimeRange = (requestState) => {
if (requestState.isTimeRangeDisabled) {
return {};
}
return {
timeRange: {
from: requestState.timeFrom[0],
to: requestState.timeTo[0],
},
};
};
const getAirbusSearchRequestBody = (state) => {
const request = {
provider: state.tpdi.provider,
bounds: {
...generateBounds(state.request),
},
data: [
{
constellation: state.airbus.constellation,
dataFilter: {
...getAirbusDataFilterOptions(state.airbus.dataFilterOptions),
...getTimeRange(state.request),
},
},
],
};
return request;
};
const getPlanetSearchRequestBody = (state) => {
const request = {
provider: state.tpdi.provider,
planetApiKey: state.planet.planetApiKey,
bounds: {
...generateBounds(state.request),
},
data: [
{
itemType: 'PSScene4Band',
dataFilter: {
...getTimeRange(state.request),
},
},
],
};
return request;
};
const getAirbusOrderBody = (state) => {
const requestBody = {};
requestBody.input = getAirbusSearchRequestBody(state);
requestBody.name = state.tpdi.name;
requestBody.collectionId = state.tpdi.collectionId;
delete requestBody.input.data[0].dataFilter;
requestBody.input.data[0].products = state.tpdi.products.map((product) => ({
id: product.id,
}));
return requestBody;
};
const getPlanetOrderBody = (state) => {
const requestBody = {};
requestBody.input = getPlanetSearchRequestBody(state);
requestBody.name = state.tpdi.name;
requestBody.collectionId = state.tpdi.collectionId;
delete requestBody.input.data[0].dataFilter;
requestBody.input.data[0].productBundle = 'analytic'; //listofstrings
requestBody.input.data[0].itemIds = state.tpdi.products.map((product) => product.id);
return requestBody;
};
//SEARCH
const getSearchTpdiBody = (state) => {
let requestBody;
if (state.tpdi.provider === 'AIRBUS') {
requestBody = getAirbusSearchRequestBody(state);
} else if (state.tpdi.provider === 'PLANET') {
requestBody = getPlanetSearchRequestBody(state);
}
return requestBody;
};
export const getTPDISearchRequest = (state, token, reqConfig) => {
const requestBody = getSearchTpdiBody(state);
const url = BASE_TPDI_URL + '/search';
const config = getReqConfig(token, reqConfig);
return axios.post(url, JSON.stringify(requestBody), config);
};
//ORDER
export const tpdiCreateOrderBodyViaProducts = (state) => {
let requestBody;
if (state.tpdi.provider === 'AIRBUS') {
requestBody = getAirbusOrderBody(state);
} else if (state.tpdi.provider === 'PLANET') {
requestBody = getPlanetOrderBody(state);
}
return requestBody;
};
export const createTPDIOrder = (state, token, reqConfig) => {
const requestBody = tpdiCreateOrderBodyViaProducts(state);
const url = BASE_TPDI_URL + '/orders';
const config = getReqConfig(token, reqConfig);
return axios.post(url, JSON.stringify(requestBody), config);
};
export const tpdiCreateOrderBodyViaDataFilter = (state) => {
let requestBody = {};
if (state.tpdi.provider === 'AIRBUS') {
requestBody.input = getAirbusSearchRequestBody(state);
} else if (state.tpdi.provider === 'PLANET') {
requestBody.input = getPlanetSearchRequestBody(state);
}
requestBody.name = state.tpdi.name;
requestBody.collectionId = state.tpdi.collectionId;
return requestBody;
};
export const createTPDIDataFilterOrder = (state, token, reqConfig) => {
const requestBody = tpdiCreateOrderBodyViaDataFilter(state);
const url = BASE_TPDI_URL + '/orders';
const config = getReqConfig(token, reqConfig);
return axios.post(url, JSON.stringify(requestBody), config);
};
export const deleteTPDIOrder = (token, orderId) => {
const url = BASE_TPDI_URL + '/orders/' + orderId;
const config = getReqConfig(token);
return axios.delete(url, config);
};
export const confirmTPDIOrder = (token, orderId, reqConfig) => {
const url = BASE_TPDI_URL + '/orders/' + orderId + '/confirm';
const config = getReqConfig(token, reqConfig);
return axios.post(url, null, config);
};
export const getAllTPDIOrders = (token, reqConfig) => {
const url = BASE_TPDI_URL + '/orders';
const config = getReqConfig(token, reqConfig);
return axios.get(url, config);
};
export const getSingleTpdiOrder = (state, orderId) => {
const url = BASE_TPDI_URL + '/orders/' + orderId;
const config = getReqConfig(state);
return axios.get(url, config);
};
// Get quota
export const getTPDIQuota = (token, reqConfig) => {
const url = BASE_TPDI_URL + '/quotas';
const config = getReqConfig(token, reqConfig);
return axios.get(url, config);
};
//Deliveries
export const getAllDeliveries = (token, orderId, reqConfig) => {
const url = BASE_TPDI_URL + '/orders/' + orderId + '/deliveries';
const config = getReqConfig(token, reqConfig);
return axios.get(url, config);
};
// curl commands
export const getCreateViaProductsTpdiCurlCommand = (state) => {
const body = JSON.stringify(tpdiCreateOrderBodyViaProducts(state), null, 2);
const token = state.auth.user.access_token;
const url = BASE_TPDI_URL + '/orders';
const curlCommand = `curl -X POST ${url} \n -H 'Content-Type: application/json' \n -H 'Authorization: Bearer ${
token ? token : '<your token here>'
}' \n -d '${body}'`;
return curlCommand;
};
export const getCreateViaDataFilterTpdiCurlCommand = (state) => {
const body = JSON.stringify(tpdiCreateOrderBodyViaDataFilter(state), null, 2);
const token = state.auth.user.access_token;
const url = BASE_TPDI_URL + '/orders';
const curlCommand = `curl -X POST ${url} \n -H 'Content-Type: application/json' \n -H 'Authorization: Bearer ${
token ? token : '<your token here>'
}' \n -d '${body}'`;
return curlCommand;
};
export const getSearchTpdiCurlCommand = (state) => {
const body = JSON.stringify(getSearchTpdiBody(state), null, 2);
const token = state.auth.user.access_token;
const url = BASE_TPDI_URL + '/search';
const curlCommand = `curl -X POST ${url} \n -H 'Content-Type: application/json' \n -H 'Authorization: Bearer ${
token ? token : '<your token here>'
}' \n -d '${body}'`;
return curlCommand;
};
export const getAllOrdersTpdiCurlCommand = (state) => {
const url = BASE_TPDI_URL + '/orders';
const token = state.auth.user.access_token;
const curlCommand = `curl -X GET ${url} \n -H 'Content-Type: application/json' \n -H 'Authorization: Bearer ${
token ? token : '<your token here>'
}' \n`;
return curlCommand;
};
export const getConfirmOrderTpdiCurlCommand = (state) => {
const url = BASE_TPDI_URL + '/orders/<your orderId>/confirm';
const token = state.auth.user.access_token;
const curlCommand = `curl -X POST ${url} \n -H 'Content-Type: application/json' \n -H 'Authorization: Bearer ${
token ? token : '<your token here>'
}' \n`;
return curlCommand;
};
export const getDeleteOrderTpdiCurlCommand = (state) => {
const url = BASE_TPDI_URL + '/orders/<your orderId>/';
const token = state.auth.user.access_token;
const curlCommand = `curl -X DELETE ${url} \n -H 'Content-Type: application/json' \n -H 'Authorization: Bearer ${
token ? token : '<your token here>'
}' \n`;
return curlCommand;
};
<file_sep>/src/utils/const.js
import proj4 from 'proj4';
export const S2L1C = 'S2L1C';
export const S2L2A = 'S2L2A';
export const L8L1C = 'L8L1C';
export const MODIS = 'MODIS';
export const DEM = 'DEM';
export const S1GRD = 'S1GRD';
export const S3OLCI = 'S3OLCI';
export const S3SLSTR = 'S3SLSTR';
export const S5PL2 = 'S5PL2';
export const CUSTOM = 'CUSTOM';
export const DATAFUSION = 'DATAFUSION';
export const DATASOURCES_NAMES = [
S2L1C,
S2L2A,
L8L1C,
MODIS,
DEM,
S1GRD,
S3OLCI,
S3SLSTR,
S5PL2,
CUSTOM,
DATAFUSION,
];
export const DATASOURCES = {
S2L1C: {
url: 'https://services.sentinel-hub.com/api/v1/process',
ogcUrl: 'https://services.sentinel-hub.com/ogc/',
},
S2L2A: {
url: 'https://services.sentinel-hub.com/api/v1/process',
ogcUrl: 'https://services.sentinel-hub.com/ogc/',
},
L8L1C: {
url: 'https://services-uswest2.sentinel-hub.com/api/v1/process',
ogcUrl: 'https://services-uswest2.sentinel-hub.com/ogc/',
},
MODIS: {
url: 'https://services-uswest2.sentinel-hub.com/api/v1/process',
ogcUrl: 'https://services-uswest2.sentinel-hub.com/ogc/',
},
DEM: {
url: 'https://services.sentinel-hub.com/api/v1/process',
ogcUrl: 'https://services.sentinel-hub.com/ogc/',
},
S1GRD: {
url: 'https://services.sentinel-hub.com/api/v1/process',
ogcUrl: 'https://services.sentinel-hub.com/ogc/',
},
S3OLCI: {
url: 'https://creodias.sentinel-hub.com/api/v1/process',
ogcUrl: 'https://creodias.sentinel-hub.com/ogc/',
},
S3SLSTR: {
url: 'https://creodias.sentinel-hub.com/api/v1/process',
ogcUrl: 'https://creodias.sentinel-hub.com/ogc/',
},
S5PL2: {
url: 'https://creodias.sentinel-hub.com/api/v1/process',
ogcUrl: 'https://creodias.sentinel-hub.com/ogc/',
},
CUSTOM: {
url: 'https://services.sentinel-hub.com/api/v1/process',
},
DATAFUSION: {
url: 'https://services.sentinel-hub.com/api/v1/process',
},
};
export const LOCATIONS = {
'https://services.sentinel-hub.com/api/v1/process': 'AWS:eu-central-1',
'https://services-uswest2.sentinel-hub.com/api/v1/process': 'AWS:eu-west-2',
'https://creodias.sentinel-hub.com/api/v1/process': 'NOT-SUPPORTED',
};
export const OUTPUT_FORMATS = [
{
name: 'TIFF',
value: 'image/tiff',
},
{
name: 'PNG',
value: 'image/png',
},
{
name: 'JPEG',
value: 'image/jpeg',
},
{
name: 'APP/JSON',
value: 'application/json',
},
];
export const DEFAULT_EVALSCRIPTS = {
S2L2A: `//VERSION=3
function setup() {
return {
input: ["B02", "B03", "B04"],
output: { bands: 3 }
};
}
function evaluatePixel(sample) {
return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
}`,
S2L1C: `//VERSION=3
function setup() {
return {
input: ["B02", "B03", "B04"],
output: { bands: 3 }
};
}
function evaluatePixel(sample) {
return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
}`,
L8L1C: `//VERSION=3 (auto-converted from 1)
let minVal = 0.0;
let maxVal = 0.4;
let viz = new HighlightCompressVisualizer(minVal, maxVal);
function setup() {
return {
input: [{
bands: [
"B03",
"B04",
"B05"
]
}],
output: {
bands: 3
}
};
}
function evaluatePixel(samples) {
let val = [samples.B05, samples.B04, samples.B03];
return viz.processList(val);
}
`,
MODIS: `//VERSION=3 (auto-converted from 1)
let minVal = 0.0;
let maxVal = 0.4;
let viz = new HighlightCompressVisualizer(minVal, maxVal);
function setup() {
return {
input: [{
bands: [
"B01",
"B03",
"B04"
]
}],
output: {
bands: 3
}
};
}
function evaluatePixel(samples) {
let val = [samples.B01, samples.B04, samples.B03];
return val.map((v,i) => viz.process(v,i));
}
`,
DEM: `return [DEM];`,
S1GRD: `return [VH*2];`,
S3OLCI: `//VERSION=3 (auto-converted from 1)
let minVal = 0.0;
let maxVal = 0.4;
let viz = new HighlightCompressVisualizer(minVal, maxVal);
function setup() {
return {
input: [{
bands: [
"B08",
"B06",
"B04"
]
}],
output: {
bands: 3
}
};
}
function evaluatePixel(samples) {
let val = [samples.B08, samples.B06, samples.B04];
return viz.processList(val);
}
`,
S3SLSTR: `//VERSION=3 (auto-converted from 1)
let minVal = 0.0;
let maxVal = 0.8;
let viz = new HighlightCompressVisualizer(minVal, maxVal);
function setup() {
return {
input: [{
bands: [
"S3",
"S2",
"S1"
]
}],
output: {
bands: 3
}
};
}
function evaluatePixel(samples) {
let val = [samples.S3, samples.S2, samples.S1];
return viz.processList(val);
}
`,
S5PL2: `return [O3];`,
CUSTOM: `//Write here your evalscript`,
DATAFUSION: `//VERSION=3
function setup (){
return {
input: [
{datasource: "s1", bands:["VV"]},
{datasource: "l2a", bands:["B02", "B03", "B04", "SCL"], units:"REFLECTANCE"}],
output: [
{id: "default", bands: 3, sampleType: SampleType.AUTO}
]
};
}
function evaluatePixel(samples, inputData, inputMetadata, customData, outputMetadata) {
var sample = samples.s1[0];
var sample2 = samples.l2a[0];
if ([7, 8, 9, 10].includes(sample2.SCL)) {
return {
default: [sample.VV, sample.VV, sample.VV]
};
} else {
return {
default: [sample2.B04*2.5, sample2.B03*2.5, sample2.B02*2.5]
};
}
}`,
};
// internal prevents its use on the Map container.
export const CRS = {
'EPSG:3857': {
url: 'http://www.opengis.net/def/crs/EPSG/0/3857',
projection: proj4('EPSG:3857'),
internal: false,
},
'EPSG:4326': {
url: 'http://www.opengis.net/def/crs/EPSG/0/4326',
projection: proj4('EPSG:4326'),
internal: false,
},
'EPSG:32633': {
url: 'http://www.opengis.net/def/crs/EPSG/0/32633',
projection: '+proj=utm +zone=33 +ellps=WGS84 +datum=WGS84 +units=m +no_defs',
internal: true,
},
'EPSG:32645': {
url: 'http://www.opengis.net/def/crs/EPSG/0/32645',
projection: '+proj=utm +zone=45 +ellps=WGS84 +datum=WGS84 +units=m +no_defs',
internal: true,
},
};
export const isEmpty = (obj) => Object.keys(obj).length === 0;
// Check if an object is empty or only contains keys with value 'DEFAULT'
export const isEmptyDefault = (obj) => {
let keys = Object.keys(obj);
if (keys.length === 0) {
return true;
}
for (let key of keys) {
if (obj[key] && obj[key] !== 'DEFAULT') {
return false;
}
}
return true;
};
<file_sep>/src/utils/hooks.js
import { useEffect, useState, useRef } from 'react';
// Hook
export function useDebounce(value, delay) {
// State and setters for debounced value
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(
() => {
// Update debounced value after delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Cancel the timeout if value changes (also on delay change or unmount)
// This is how we prevent debounced value from updating if value is changed ...
// .. within the delay period. Timeout gets cleared and restarted.
return () => {
clearTimeout(handler);
};
},
[value, delay], // Only re-call effect if value or delay changes
);
return debouncedValue;
}
export function useWhyDidYouUpdate(name, props) {
// Get a mutable ref object where we can store props ...
// ... for comparison next time this hook runs.
const previousProps = useRef();
useEffect(() => {
if (previousProps.current) {
// Get all keys from previous and current props
const allKeys = Object.keys({ ...previousProps.current, ...props });
// Use this object to keep track of changed props
const changesObj = {};
// Iterate through keys
allKeys.forEach((key) => {
// If previous is different from current
if (previousProps.current[key] !== props[key]) {
// Add to changesObj
changesObj[key] = {
from: previousProps.current[key],
to: props[key],
};
}
});
// If changesObj not empty then output to console
if (Object.keys(changesObj).length) {
console.log('[why-did-you-update]', name, changesObj);
}
}
// Finally update previousProps with current props for next hook call
previousProps.current = props;
});
}
export function useOnClickOutside(ref, handler) {
useEffect(() => {
const listener = (event) => {
// Do nothing if clicking ref's element or descendent elements
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
};
}, [ref, handler]);
}
<file_sep>/src/components/forms/BatchRequestForm.js
import React, { useState } from 'react';
import BatchRequestPreview from '../output/BatchRequestPreview';
import DataSourceSelect from '../input/DataSourceSelect';
import TimeRangeSelect from '../input/TimeRangeSelect';
import Output from '../output/Output';
import EvalscriptEditor from '../Evalscript/EvalscriptEditor';
import BatchOptions from '../batch/BatchOptions';
import BatchActions from '../batch/BatchActions';
import MapContainer from '../input/MapContainer';
import BatchInformation from '../batch/BatchInformation';
const BatchRequestForm = () => {
const [fetchedRequests, setFetchedRequests] = useState([]);
return (
<div>
<div className="process-first-row">
<div className="process-first-row-first-item">
<DataSourceSelect />
</div>
<div className="process-first-row-second-item">
<TimeRangeSelect />
<div className="output u-margin-top-small">
<Output />
</div>
</div>
<div className="process-first-row-third-item">
<MapContainer />
</div>
</div>
<div className="process-second-row u-margin-bottom-medium">
<div className="process-second-row-first-item">
<EvalscriptEditor />
</div>
<div className="process-second-row-second-item">
<BatchRequestPreview />
</div>
</div>
<div className="batch-third-row">
<div className="batch-third-row-first-item">
<BatchOptions setFetchedRequests={setFetchedRequests} />
<BatchActions setFetchedRequests={setFetchedRequests} />
</div>
<div className="batch-third-row-second-item">
<BatchInformation setFetchedRequests={setFetchedRequests} fetchedRequests={fetchedRequests} />
</div>
</div>
</div>
);
};
export default BatchRequestForm;
<file_sep>/src/components/catalog/CatalogTimeRange.js
import React from 'react';
import {
convertUtcDateToInput,
returnValidatedTimeTo,
returnValidatedTimeFrom,
} from '../input/TimeRangeSelect';
import { connect } from 'react-redux';
import store, { catalogSlice } from '../../store';
import Toggle from '../Toggle';
const CatalogTimeRange = ({ timeFrom, timeTo }) => {
const handleChangeTimeFrom = (e) => {
let d = returnValidatedTimeFrom(e.target.value);
store.dispatch(catalogSlice.actions.setTimeFrom(d.format()));
};
const handleChangeTimeTo = (e) => {
let d = returnValidatedTimeTo(e.target.value);
store.dispatch(catalogSlice.actions.setTimeTo(d.format()));
};
const handleOpenTimeTo = () => {
// if one is already open it cannot be opened.
if (timeFrom.isOpen && !timeTo.isOpen) {
return;
}
store.dispatch(catalogSlice.actions.openTimeTo(!timeTo.isOpen));
};
const handleOpenTimeFrom = () => {
// if one is already open it cannot be opened.
if (timeTo.isOpen && !timeFrom.isOpen) {
return;
}
store.dispatch(catalogSlice.actions.openTimeFrom(!timeFrom.isOpen));
};
return (
<>
<h2 className="heading-secondary">Time Range</h2>
<div className="form">
<div className="timerange">
<div className="toggle-with-label">
<label className="form__label">From</label>
<Toggle checked={timeFrom.isOpen} onChange={handleOpenTimeFrom} />
</div>
<input
disabled={timeFrom.isOpen}
value={convertUtcDateToInput(timeFrom.time)}
required
className="form__input"
onChange={handleChangeTimeFrom}
type="date"
></input>
<div className="toggle-with-label">
<label className="form__label">To</label>
<Toggle checked={timeTo.isOpen} onChange={handleOpenTimeTo} />
</div>
<input
disabled={timeTo.isOpen}
value={convertUtcDateToInput(timeTo.time)}
required
className="form__input"
onChange={handleChangeTimeTo}
type="date"
/>
</div>
</div>
</>
);
};
const mapStateToProps = (state) => ({
timeFrom: state.catalog.timeFrom,
timeTo: state.catalog.timeTo,
});
export default connect(mapStateToProps)(CatalogTimeRange);
<file_sep>/src/components/tpdi/AirbusOptions.js
import React, { useState } from 'react';
import store, { airbusSlice } from '../../store';
import { connect } from 'react-redux';
import AirbusAdvancedOptions from './AirbusAdvancedOptions';
import Toggle from '../Toggle';
const AirbusOptions = ({ constellation }) => {
const [showAdvanced, setShowAdvanced] = useState(false);
const handleShowAdvancedChange = () => {
setShowAdvanced(!showAdvanced);
};
const handleConstellationChange = (e) => {
store.dispatch(airbusSlice.actions.setConstellation(e.target.value));
};
return (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<label className="form__label">Constellation</label>
<select className="form__input" value={constellation} onChange={handleConstellationChange}>
<option value="PHR">PHR (Pleiades)</option>
<option value="SPOT">SPOT</option>
</select>
<div className="toggle-with-label">
<label htmlFor="adv-options" className="form__label">
Advanced Options
</label>
<Toggle id="adv-options" checked={showAdvanced} onChange={handleShowAdvancedChange} />
</div>
{showAdvanced ? <AirbusAdvancedOptions /> : null}
</div>
);
};
const mapStateToProps = (state) => ({
constellation: state.airbus.constellation,
});
export default connect(mapStateToProps)(AirbusOptions);
<file_sep>/src/components/wms/WMSRequestForm.js
import React from 'react';
import InstanceSelector from './InstanceSelector';
import LayerSelector from './LayerSelector';
import WmsRequestPreview from './WmsRequestPreview';
import TimeRangeSelect from '../input/TimeRangeSelect';
import MapContainer from '../input/MapContainer';
import Output from '../output/Output';
import WmsModeSelector from './WmsModeSelector';
import OGCAdvancedOptions from './OGCAdvancedOptions';
const WMSRequestForm = () => {
return (
<div className="wms-request-form">
<div>
<WmsModeSelector />
</div>
<div className="wms-request-form-first-row">
<div className="wms-request-form-first-row-first-item">
<h2 className="heading-secondary">Instance Options</h2>
<div className="form">
<InstanceSelector />
<LayerSelector />
<OGCAdvancedOptions />
</div>
</div>
<div className="wms-request-form-first-row-second-item">
<TimeRangeSelect />
<div className="output u-margin-top-small">
<Output />
</div>
</div>
<div className="wms-request-form-first-row-third-item">
<MapContainer />
</div>
</div>
<div className="wms-request-form-second-row">
<div className="wms-request-form-second-row-first-item">
<WmsRequestPreview />
</div>
</div>
</div>
);
};
export default WMSRequestForm;
<file_sep>/src/components/tpdi/TPDIOrdersContainer.js
import React, { useState } from 'react';
import RequestButton from '../RequestButton';
import { getAllTPDIOrders } from './generateTPDIRequests';
import { errorHandlerTPDI } from './TPDIOrderOptions';
import OrderInfo from './OrderInfo';
import { connect } from 'react-redux';
const TPDIOrdersContainer = ({ token }) => {
const [orders, setOrders] = useState([]);
const handleGetOrders = (response) => {
setOrders(response.data.sort((a, b) => new Date(b.created) - new Date(a.created)));
};
const handleDeleteOrder = (orderId) => {
const newOrders = orders.filter((order) => order.id !== orderId);
setOrders(newOrders);
};
const handleUpdateOrder = (newOrder) => {
const index = orders.findIndex((order) => order.id === newOrder.id);
const newOrders = orders
.slice(0, index)
.concat(newOrder)
.concat(orders.slice(index + 1));
setOrders(newOrders);
};
return (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2 className="heading-secondary">Orders</h2>
<div className="form" style={{ overflowY: 'scroll', maxHeight: '450px' }}>
<div className="u-margin-bottom-small">
<RequestButton
request={getAllTPDIOrders}
args={[token]}
buttonText={orders.length > 0 ? 'Refresh your orders' : 'Get your orders'}
validation={Boolean(token)}
className={'secondary-button'}
responseHandler={handleGetOrders}
disabledTitle="Log in to use this"
errorHandler={errorHandlerTPDI}
/>
</div>
{orders.length > 0
? orders.map((order) => (
<OrderInfo
handleDeleteOrder={handleDeleteOrder}
handleUpdateOrder={handleUpdateOrder}
token={token}
key={order.id}
order={order}
/>
))
: null}
</div>
</div>
);
};
const mapStateToProps = (state) => ({
token: state.auth.user.access_token,
});
export default connect(mapStateToProps)(TPDIOrdersContainer);
<file_sep>/src/components/input/MapContainer.js
import React, { useState, useEffect, useRef, useCallback } from 'react';
import Map from '../Map';
import { connect } from 'react-redux';
import { CRS } from '../../utils/const';
import store, { requestSlice, tpdiSlice } from '../../store';
import { transformGeometryToNewCrs } from '../../utils/crsTransform';
import L from 'leaflet';
import bboxPolygon from '@turf/bbox-polygon';
import bbox from '@turf/bbox';
import area from '@turf/area';
import { kml } from '@tmcw/togeojson';
//Helper functions.
// Parsed Geo in whatever CRS -> Parsed Geo in WGS84
export const transformGeometryToWGS84IfNeeded = (selectedCRS, geometry) => {
//transform if not in WGS84
if (selectedCRS !== 'EPSG:4326') {
try {
const newGeo = transformGeometryToNewCrs(geometry, 'EPSG:4326', selectedCRS);
return newGeo;
} catch (err) {
return geometry;
}
}
return geometry;
};
export const getAreaFromGeometry = (geometry) => {
if (geometry.length === 4) {
return area(bboxPolygon(geometry));
} else {
return area(geometry);
}
};
//from parsed geometry to leaflet polygon / layer.
const getLayer = (parsedGeometry, layerConfig, currentLayers, mapRef) => {
const addEditEventListener = (layer, layerConfig) => {
if (layerConfig) {
return;
}
layer.on('pm:edit', (e) => {
const layer = e.layer;
const type = currentLayers[0].type;
if (type === 'rectangle') {
store.dispatch(requestSlice.actions.setGeometry(bbox(layer.toGeoJSON())));
} else if (type === 'polygon') {
store.dispatch(requestSlice.actions.setGeometry(layer.toGeoJSON().geometry));
}
});
layer.on('pm:cut', (e) => {
e.layer.removeFrom(mapRef);
e.originalLayer.removeFrom(mapRef);
let geo = e.layer.toGeoJSON().geometry;
geo.type = 'MultiPolygon';
geo.coordinates = [geo.coordinates];
store.dispatch(requestSlice.actions.setGeometry(geo));
});
};
try {
if (parsedGeometry.type === 'Polygon') {
const coords = parsedGeometry.coordinates[0].map((c) => [c[1], c[0]]);
const polygon = L.polygon(coords, layerConfig);
addEditEventListener(polygon, layerConfig);
return {
layer: polygon,
type: 'polygon',
};
} else if (parsedGeometry.type === 'MultiPolygon') {
const coords = parsedGeometry.coordinates.map((a) =>
a.map((coords) => coords).map((b) => b.map((c) => [c[1], c[0]])),
);
const layer = L.polygon(coords, layerConfig);
addEditEventListener(layer, layerConfig);
return {
layer: layer,
type: 'polygon',
};
} else {
const coords = bboxPolygon(parsedGeometry).geometry.coordinates[0].map((c) => [c[1], c[0]]);
const polygon = L.rectangle(coords, layerConfig);
addEditEventListener(polygon, layerConfig);
return {
layer: polygon,
type: 'rectangle',
};
}
} catch (err) {
console.error('error while creating the layer on GetLayer\n', err);
return false;
}
};
const generateCRSOptions = (crs) =>
Object.keys(crs)
.map((key) =>
!crs[key].internal ? (
<option key={key} value={key}>
{key}
</option>
) : undefined,
)
.filter((o) => o);
const convertToCRS84AndDispatch = (parsedGeo, selectedCrs) => {
const transformedGeo = transformGeometryToWGS84IfNeeded(selectedCrs, parsedGeo);
store.dispatch(requestSlice.actions.setGeometry(transformedGeo));
};
export const focusMap = () => {
document.getElementById('map').focus();
};
//Component
const MapContainer = ({ geometry, selectedCrs, extraMapGeometry }) => {
//functions for leaflet map.
const deleteLayerIfPossible = () => {
if (layersRef.current.length > 0) {
const layerToBeRemoved = layersRef.current.pop().layer;
drawnItemsRef.current.removeLayer(layerToBeRemoved);
mapRef.current.removeLayer(layerToBeRemoved);
}
};
const addDrawLayer = (layerWithType) => {
const { layer, type } = layerWithType;
if (layer && type) {
drawnItemsRef.current.addLayer(layer);
layersRef.current.push(layerWithType);
} else {
throw Error('Adding invalid layer');
}
};
// Helpers for TPDI layers
const deleteExtraLayerIfPossible = () => {
if (extraLayersRef.current.length > 0) {
const layerToBeRemoved = extraLayersRef.current.pop().layer;
drawnItemsRef.current.removeLayer(layerToBeRemoved);
mapRef.current.removeLayer(layerToBeRemoved);
}
};
const addExtraDrawLayer = (layerWithType) => {
const { layer, type } = layerWithType;
if (layer && type) {
drawnItemsRef.current.addLayer(layer);
extraLayersRef.current.push(layerWithType);
} else {
throw Error('Adding invalid layer');
}
};
const [geometryText, setGeometryText] = useState('');
const layersRef = useRef([]);
//reference to layers no-related to redux geometry (tpdi)
const extraLayersRef = useRef([]);
const drawnItemsRef = useRef();
const mapRef = useRef();
const handleCRSChange = (e) => {
store.dispatch(requestSlice.actions.setCRS(e.target.value));
};
const handleGeometryTextChange = (e) => {
setGeometryText(e.target.value);
};
// Parses geometry on textarea to layers on leaflet.
// 1. Create leaflet layer based on geo 2. add it to drawn items 3. Fit Bounds to the new layer.
const parseProperGeometryToMap = useCallback((parsedGeometry) => {
try {
const leafletLayer = getLayer(parsedGeometry, undefined, layersRef.current, mapRef.current);
deleteLayerIfPossible();
addDrawLayer(leafletLayer);
mapRef.current.fitBounds(leafletLayer.layer.getBounds());
} catch (err) {
console.error('Parsing geometry failed', err);
}
}, []);
const parseExtraGeometryToMap = useCallback((parsedGeometry) => {
try {
const leafletLayer = getLayer(
parsedGeometry,
{ color: 'green' },
extraLayersRef.current,
mapRef.current,
);
deleteExtraLayerIfPossible();
addExtraDrawLayer(leafletLayer);
mapRef.current.fitBounds(leafletLayer.layer.getBounds());
} catch (err) {
console.error('Parsing extra geometry failed', err);
}
}, []);
const fitToMainBounds = useCallback(() => {
if (layersRef.current.length > 0) {
mapRef.current.fitBounds(layersRef.current[0].layer.getBounds());
}
}, []);
const handleParseGeometry = (text = geometryText) => {
try {
let parsedGeo = JSON.parse(text);
// Geojson
if (parsedGeo.type === 'FeatureCollection') {
parsedGeo = parsedGeo.features[0].geometry;
}
convertToCRS84AndDispatch(parsedGeo, selectedCrs);
} catch (err) {
console.error('Error Parsing Geometry', err);
}
};
//Effect that handles transforming into the selected CRS the internal geometry and keeping the textarea updated.
useEffect(() => {
if (selectedCrs !== 'EPSG:4326') {
const transformedGeo = transformGeometryToNewCrs(geometry, selectedCrs);
setGeometryText(JSON.stringify(transformedGeo, null, 2));
} else {
setGeometryText(JSON.stringify(geometry, null, 2));
}
}, [geometry, selectedCrs]);
// Effect that converts internal geometry to Leaflet Layers visible on the Map.
useEffect(() => {
parseProperGeometryToMap(geometry);
}, [geometry, parseProperGeometryToMap]);
// Effect that shows extra geometry layers (for tpdi)
useEffect(() => {
if (extraMapGeometry) {
parseExtraGeometryToMap(extraMapGeometry);
} else {
deleteExtraLayerIfPossible();
}
}, [extraMapGeometry, parseExtraGeometryToMap]);
const handleUploadFileButtonClick = () => {
let fileElement = document.getElementById('file-input');
fileElement.click();
};
const handleFileUpload = async () => {
try {
let fileElement = document.getElementById('file-input');
let file = fileElement.files[0];
let text = await file.text();
let ext = file.name.split('.').pop();
if (file.type.includes('kml') || ext === 'kml') {
let parser = new DOMParser();
let doc = parser.parseFromString(text, 'text/xml');
let converted = kml(doc);
convertToCRS84AndDispatch(converted.features[0].geometry, selectedCrs);
} else {
handleParseGeometry(text);
}
fileElement.value = '';
} catch (err) {
console.error('Error uploading file', err);
}
};
const handleClearExtraGeometry = () => {
store.dispatch(tpdiSlice.actions.setExtraMapGeometry(null));
fitToMainBounds();
};
return (
<div className="aoi-container">
<h2 className="heading-secondary">Area of interest</h2>
<div className="form">
<div className="form__item form__item--crs" style={{ display: 'flex', alignItems: 'center' }}>
<label className="form__label">CRS: </label>
<select
className="form__input"
style={{ transform: 'translateY(-5px)', marginLeft: '1rem' }}
onChange={handleCRSChange}
value={selectedCrs}
>
{generateCRSOptions(CRS)}
</select>
</div>
<div className="map-container">
<Map mapRef={mapRef} drawnItemsRef={drawnItemsRef} layersRef={layersRef} />
<div className="textarea-aoi-container">
<textarea
onChange={handleGeometryTextChange}
value={geometryText}
spellCheck="false"
className="textarea"
/>
<div className="map-buttons">
<button onClick={() => handleParseGeometry()} className="secondary-button">
Parse Geometry
</button>
<input onChange={handleFileUpload} id="file-input" type="file" style={{ display: 'none' }} />
<button
title="Upload a KML or GeoJSON file to parse the geometry."
onClick={handleUploadFileButtonClick}
className="secondary-button"
>
Upload KML/GeoJSON
</button>
<span
className="info"
title="Upload a KML or GeoJSON file to parse the geometry (Only first geometry on the file gets parsed)."
>
ℹ
</span>
{extraMapGeometry ? (
<button className="secondary-button" onClick={handleClearExtraGeometry}>
Clear Extra Geometry
</button>
) : null}
</div>
</div>
</div>
</div>
</div>
);
};
const mapStateToProps = (state) => ({
geometry: state.request.geometry,
selectedCrs: state.request.CRS,
extraMapGeometry: state.tpdi.extraMapGeometry,
});
export default connect(mapStateToProps)(MapContainer);
<file_sep>/src/components/batch/BatchRequestSummary.js
import React, { useState, useEffect, useCallback } from 'react';
import store, { batchSlice, tpdiSlice, requestSlice, alertSlice } from '../../store';
import { getTransformedGeometryFromBounds } from '../../utils/crsTransform';
import { dispatchChanges } from '../../utils/parseRequest';
import { fetchTilesBatchRequest } from '../../utils/batchActions';
import { focusMap } from '../input/MapContainer';
const tillingGridIdToName = (id) => {
return ['S2GM Grid', '10km Grid', '100,08km Grid'][id];
};
const validStatus = (status) => {
return Boolean(status !== 'CREATED' && status !== 'CANCELED' && status !== 'ANALYSING');
};
const getBucketName = (member) => {
if (member.bucketName) {
return member.bucketName;
}
//tilepath
else {
return member.output.defaultTilePath.split('/')[2];
}
};
const updateTileInfo = (tiles) => {
let initial = {
processedTiles: 0,
processingTiles: 0,
scheduledTiles: 0,
consumedPu: 0,
totalTiles: 0,
pendingTiles: 0,
failedTiles: 0,
};
return tiles.reduce((acc, tile) => {
if (tile.status === 'PROCESSED') {
acc['processedTiles']++;
acc['consumedPu'] += tile.cost / 3;
}
if (tile.status === 'PENDING') {
acc['pendingTiles']++;
}
if (tile.status === 'SCHEDULED') {
acc['scheduledTiles']++;
}
if (tile.status === 'PROCESSING') {
acc['processingTiles']++;
}
if (tile.status === 'FAILED') {
acc['failedTiles']++;
}
acc['totalTiles']++;
return acc;
}, initial);
};
const BatchRequestSummary = ({ props, token }) => {
const {
id,
status,
description,
tileCount,
valueEstimate,
created,
processRequest,
tilingGridId,
resolution,
} = props;
const bucketName = getBucketName(props);
const [showAllInfo, setShowAllInfo] = useState(false);
const [isFetchingTiles, setIsFetchingTiles] = useState(false);
const [fetchedTiles, setFetchedTiles] = useState({
processedTiles: 0,
processingTiles: 0,
scheduledTiles: 0,
consumedPu: 0,
totalTiles: 0,
pendingTiles: 0,
failedTiles: 0,
});
const fetchTiles = useCallback(async () => {
setIsFetchingTiles(true);
const res = await fetchTilesBatchRequest(id, token);
setFetchedTiles(updateTileInfo(res));
setIsFetchingTiles(false);
}, [id, token]);
useEffect(() => {
if (showAllInfo && validStatus(status)) {
fetchTiles();
}
}, [fetchTiles, showAllInfo, status]);
const generateCopyCommand = useCallback(() => {
//if tilePath
if (props.output && props.output.defaultTilePath) {
let path = props.output.defaultTilePath.split('<')[0];
return `aws s3 sync ${path} ./`;
}
return `aws s3 sync s3://${bucketName}/${id}/ ./`;
}, [bucketName, props.output, id]);
const handleSelectId = () => {
store.dispatch(batchSlice.actions.setSelectedBatchId(id));
};
const handleShowInfoClick = () => {
if (!props.singleBatch) {
setShowAllInfo(!showAllInfo);
}
};
const handleSeeGeometry = () => {
const transformedGeo = getTransformedGeometryFromBounds(props.processRequest.input.bounds);
store.dispatch(tpdiSlice.actions.setExtraMapGeometry(transformedGeo));
focusMap();
};
const handleSetGeometry = () => {
const transformedGeo = getTransformedGeometryFromBounds(props.processRequest.input.bounds);
store.dispatch(requestSlice.actions.setGeometry(transformedGeo));
focusMap();
};
const handleParseBatch = () => {
try {
dispatchChanges(processRequest);
store.dispatch(batchSlice.actions.setBucketName(bucketName));
store.dispatch(batchSlice.actions.setDescription(description));
store.dispatch(batchSlice.actions.setTillingGrid(tilingGridId));
store.dispatch(batchSlice.actions.setResolution(resolution));
// check if tile path or cogOutput and dispatch.
if (props.output) {
if (props.output.cogOutput) {
store.dispatch(batchSlice.actions.setCogOutput(true));
}
if (props.output.defaultTilePath) {
store.dispatch(batchSlice.actions.setSpecifyingBucketName(false));
store.dispatch(
batchSlice.actions.setDefaultTilePath(props.output.defaultTilePath.split(bucketName + '/')[1]),
);
}
}
store.dispatch(alertSlice.actions.addAlert({ type: 'SUCCESS', text: 'Request successfully parsed' }));
} catch (err) {
console.error(err);
store.dispatch(alertSlice.actions.addAlert({ type: 'WARNING', text: 'Something went wrong' }));
}
};
const handleRefreshTiles = () => {
fetchTiles();
};
return (
<div className="u-margin-bottom-small">
<div className="batch-request-summary">
<div
title="Click to show information about the request"
onClick={handleShowInfoClick}
className="batch-request-summary-header"
>
<p className="text" style={{ display: 'inline-block' }}>
{id}
</p>
<p className="text">{status}</p>
</div>
<div className="batch-request-summary-button">
<button onClick={handleSelectId} className="secondary-button">
Select Request
</button>
</div>
</div>
<div className="batch-request-summary-info">
{showAllInfo ? (
<>
<p className="text">
<span>Status:</span> {status}
</p>
{description ? (
<p className="text">
<span>Description:</span> {description}
</p>
) : null}
<p className="text">
<span>Created At:</span> {created}
</p>
<p className="text">
<span>Number of tiles:</span> {tileCount}
</p>
<p className="text">
<span>Bucket Name:</span> {bucketName}
</p>
{valueEstimate ? (
<p className="text">
<span>Estimated Value (in PU):</span> {Math.round(valueEstimate)}
</p>
) : null}
{/* {fetchedTiles.consumedPu ? (
<p className="text">
<span>Consumed PU:</span> {Math.round(fetchedTiles.consumedPu)}
</p>
) : null} */}
<p className="text">
<span>Tilling Grid:</span> {tillingGridIdToName(props.tilingGridId)}
</p>
<p className="text">
<span>Resolution:</span> {props.resolution}
</p>
<p className="text">
<span>Last user Action:</span> {props.userAction}
</p>
</>
) : null}
</div>
{showAllInfo ? (
<>
{!validStatus(status) ? null : isFetchingTiles ? (
<p className="text u-margin-bottom-small">Loading...</p>
) : (
<table summary="Tile Information" className="table">
<caption>
Tile Information
<button onClick={handleRefreshTiles} className="secondary-button u-margin-left-small">
Refresh Tiles
</button>
</caption>
<thead>
<tr>
<th scope="col">Processed</th>
<th scope="col">Processing</th>
<th scope="col">Scheduled</th>
<th scope="col">Failed</th>
<th scope="col">Pending</th>
<th scope="col">Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>{fetchedTiles.processedTiles}</td>
<td>{fetchedTiles.processingTiles}</td>
<td>{fetchedTiles.scheduledTiles}</td>
<td>{fetchedTiles.failedTiles}</td>
<td>{fetchedTiles.pendingTiles}</td>
<td>{fetchedTiles.totalTiles}</td>
</tr>
</tbody>
</table>
)}
<>
<p className="text">
<i>Note: To copy produced data to your location, you can use the following command:</i>
</p>
<p className="text u-margin-top-tiny u-margin-left-tiny u-margin-bottom-small">
> {generateCopyCommand()}
</p>
</>
</>
) : null}
{showAllInfo ? (
<div>
<button
onClick={handleSeeGeometry}
style={{ width: 'fit-content', marginRight: '1rem' }}
className="secondary-button u-margin-bottom-small"
>
See geometry on map
</button>
<button
onClick={handleSetGeometry}
style={{ width: 'fit-content', marginRight: '1rem' }}
className="secondary-button u-margin-bottom-small"
>
Set geometry on map
</button>
<button onClick={handleParseBatch} className="secondary-button">
Parse Batch Request
</button>
</div>
) : null}
<hr></hr>
</div>
);
};
export default BatchRequestSummary;
<file_sep>/src/utils/generateShjsRequest.js
import bbox from '@turf/bbox';
import {
isEmpty,
S2L2A,
S2L1C,
L8L1C,
S1GRD,
S3OLCI,
S3SLSTR,
S5PL2,
MODIS,
DEM,
CUSTOM,
DATAFUSION,
} from '../utils/const';
import { transformGeometryToNewCrs } from './crsTransform';
const datasourceToSHJSLayer = {
[S2L2A]: 'S2L2ALayer',
[S2L1C]: 'S2L1CLayer',
[L8L1C]: 'Landsat8AWSLayer',
[S1GRD]: 'S1GRDAWSEULayer',
[S3OLCI]: 'S3OLCILayer',
[S3SLSTR]: 'S3SLSTRLayer',
[S5PL2]: 'S5PL2Layer',
[MODIS]: 'MODISLayer',
[DEM]: 'DEMLayer',
[CUSTOM]: 'BYOCLayer',
[DATAFUSION]: 'ProcessingDataFusionLayer',
};
const crsToSHJSCrs = {
'EPSG:4326': 'CRS_EPSG4326',
'EPSG:3857': 'CRS_EPSG3857',
};
const formatToSHJS = {
'image/jpeg': 'MimeTypes.JPEG',
'image/png': 'MimeTypes.PNG',
//tiff supported?
'image/tiff': 'MimeTypes.PNG',
};
const locationToSHJSLocation = {
'EU-CENTRAL-1': 'awsEuCentral1',
'US-WEST-2': 'awsUsWest2',
};
const getSHJSImports = (reqState) => {
const layer = datasourceToSHJSLayer[reqState.datasource];
let imports = layer + `, setAuthToken, ApiType, MimeTypes, ${crsToSHJSCrs[reqState.CRS]}, BBox`;
//If Byoc, location is needed
if (reqState.datasource === 'CUSTOM') {
imports += ', LocationIdSHv3';
}
//If datafusion, need to import other layers too.
if (reqState.datasource === 'DATAFUSION') {
imports += `, ${datasourceToSHJSLayer[reqState.datafusionSources[0].datasource]}, ${
datasourceToSHJSLayer[reqState.datafusionSources[1].datasource]
}`;
}
return imports;
};
// [[],[],[]] -> 'num,num,num,num'
export const generateSHBbox = (geometry, selectedCrs) => {
if (!geometry) {
return null;
}
let geo = geometry;
if (selectedCrs !== 'EPSG:4326') {
geo = transformGeometryToNewCrs(geometry, selectedCrs);
}
if (geo.length === 4) {
const b = `${geo[0]}, ${geo[1]}, ${geo[2]}, ${geo[3]}`;
return b;
} else {
const b = bbox(geo);
return `${b[0]}, ${b[1]}, ${b[2]}, ${b[3]}`;
}
};
const addDefaultOptionsS1IfNeeded = (dataFilterOptions) => {
if (!dataFilterOptions.acquisitionMode || dataFilterOptions.acquisitionMode === 'DEFAULT') {
dataFilterOptions.acquisitionMode = 'IW';
}
if (!dataFilterOptions.resolution || dataFilterOptions.resolution === 'DEFAULT') {
dataFilterOptions.resolution = 'HIGH';
}
if (!dataFilterOptions.polarization || dataFilterOptions.polarization === 'DEFAULT') {
dataFilterOptions.polarization = 'DV';
}
};
const getSHJSOptions = (reqState, idx = 0) => {
let shjsOptions = '';
// Iterate through the different options and write non DEFAULT ones.
const dataFilterOptions = reqState.dataFilterOptions[idx].options;
const processingOptions = reqState.processingOptions[idx].options;
// If S1, add default options since shjs always need the options
if (reqState.datasource === S1GRD) {
addDefaultOptionsS1IfNeeded(dataFilterOptions);
}
if (!isEmpty(dataFilterOptions)) {
Object.keys(dataFilterOptions).forEach((key) => {
if (dataFilterOptions[key] !== 'DEFAULT') {
shjsOptions = shjsOptions + `\n ${key}:'${dataFilterOptions[key]}',`;
}
});
}
if (!isEmpty(processingOptions)) {
Object.keys(processingOptions).forEach((key) => {
if (processingOptions[key] !== 'DEFAULT') {
shjsOptions = shjsOptions + `\n ${key}:'${processingOptions[key]}',`;
}
});
}
// If byoc, need to specify location
if (reqState.datasource === CUSTOM) {
shjsOptions =
shjsOptions + `\n locationId: LocationIdSHv3.${locationToSHJSLocation[reqState.byocLocation]}`;
}
return shjsOptions;
};
const getShJSLayers = (reqState) => {
let stringLayer = '';
//if datafusion need to create previous layers and layers array.
if (reqState.datasource === 'DATAFUSION') {
reqState.datafusionSources.forEach((source, idx) => {
const datafusionLayer = datasourceToSHJSLayer[source.datasource];
stringLayer =
stringLayer +
`const layer${idx} = new ${datafusionLayer}({
evalscript: evalscript,\
${getSHJSOptions(reqState, idx)}
});\n`;
});
stringLayer =
stringLayer +
`
const layers = [
{
layer: layer0,
id: '${reqState.datafusionSources[0].id}',
timeFrom: new Date('${reqState.timeFrom[0]}'),
timeTo: new Date('${reqState.timeTo[0]}')
},
{
layer: layer1,
id: '${reqState.datafusionSources[1].id}',
timeFrom: new Date('${reqState.timeFrom[1] ? reqState.timeFrom[1] : reqState.timeFrom[0]}'),
timeTo: new Date('${reqState.timeTo[1] ? reqState.timeTo[1] : reqState.timeTo[0]}')
}
]
`;
const layer = datasourceToSHJSLayer[reqState.datasource];
stringLayer =
stringLayer +
`const layer = new ${layer}({
evalscript: evalscript,
layers: layers
});`;
} else {
const layer = datasourceToSHJSLayer[reqState.datasource];
stringLayer =
stringLayer +
`const layer = new ${layer}({
evalscript: evalscript,\
${getSHJSOptions(reqState)}
});`;
}
return stringLayer;
};
// If there's more than one date, return the earliest
const getTimeFromHelper = (requestState) => {
if (requestState.timeFrom.length > 1) {
let firstDate = requestState.timeFrom[0];
let secondDate = requestState.timeFrom[1];
if (new Date(firstDate) < new Date(secondDate)) {
return firstDate;
}
return secondDate;
}
return requestState.timeFrom[0];
};
// If there's more than one date, return the latest
const getTimeToHelper = (requestState) => {
if (requestState.timeTo.length > 1) {
let firstDate = requestState.timeTo[0];
let secondDate = requestState.timeTo[1];
if (new Date(firstDate) > new Date(secondDate)) {
return firstDate;
}
return secondDate;
}
return requestState.timeTo[0];
};
const generateGetMapParams = (requestState) => {
return `const getMapParams = {
bbox: new BBox(${crsToSHJSCrs[requestState.CRS]}, ${generateSHBbox(
requestState.geometry,
requestState.CRS,
)}),
fromTime: new Date('${getTimeFromHelper(requestState)}'),
toTime: new Date('${getTimeToHelper(requestState)}'),
width: ${requestState.width},
height: ${requestState.height},
format: ${formatToSHJS[requestState.responses[0].format]},\
${
requestState.geometry.type === 'Polygon'
? `\n geometry: ${JSON.stringify(
transformGeometryToNewCrs(requestState.geometry, requestState.CRS),
)}`
: ''
}
}`;
};
export const getSHJSCode = (requestState, token) => {
//Multiresponse not supported.
if (requestState.responses.length > 1) {
return '// Multi-part response is not supported. See curl mode';
}
const evalscript = requestState.evalscript;
let shjsCode = `import { ${getSHJSImports(requestState)} } from '@sentinel-hub/sentinelhub-js';\n\n`;
shjsCode += `${token ? `setAuthToken('${token}');\n\n` : ''}`;
shjsCode += `const evalscript = \`${evalscript}\`;\n\n`;
shjsCode += `${getShJSLayers(requestState)}\n\n`;
shjsCode += generateGetMapParams(requestState);
shjsCode += `\n\nlayer.getMap(getMapParams, ApiType.PROCESSING).then(response => {
//
});`;
return shjsCode;
};
<file_sep>/src/components/catalog/requests/index.js
import Axios from 'axios';
import bbox from '@turf/bbox';
const getConfigHelper = (token, reqConfig) => {
return {
headers: {
Authorization: `Bearer ${token}`,
},
...reqConfig,
};
};
const CATALOG_BASE_URL = 'https://services.sentinel-hub.com/api/v1/catalog/';
export const getCatalogCollections = (token, reqConfig) => {
const config = getConfigHelper(token, reqConfig);
const url = CATALOG_BASE_URL + 'collections';
return Axios.get(url, config);
};
const getBbox = (geometry) => {
if (geometry.length === 4) {
return geometry;
}
return bbox(geometry);
};
const shouldIntersect = (geometry) => {
if (geometry.length === 4) {
return false;
}
return true;
};
const getDateTime = (catalogState) => {
if (catalogState.timeFrom.isOpen) {
return `../${catalogState.timeFrom.time}`;
} else if (catalogState.timeTo.isOpen) {
return `${catalogState.timeTo.time}/..`;
}
return catalogState.timeFrom.time + '/' + catalogState.timeTo.time;
};
const getCatalogQueries = (catalogState) => {
let queryObj = {};
for (let query of catalogState.queryProperties) {
queryObj[query.propertyName] = {
[query.operator]: query.propertyValue,
};
}
return queryObj;
};
const getCatalogFields = (catalogState) => {
const fields = {};
if (!catalogState.disableInclude) {
fields.include = catalogState.includeFields;
}
if (!catalogState.disableExclude) {
fields.exclude = catalogState.excludeFields;
}
return fields;
};
export const getCatalogRequestBody = (catalogState, geometry) => {
const body = {};
body.collections = [catalogState.selectedCollection];
body.datetime = getDateTime(catalogState);
if (shouldIntersect(geometry)) {
body.intersects = geometry;
} else {
body.bbox = getBbox(geometry);
}
body.limit = catalogState.limit;
if (catalogState.distinct) {
body.distinct = catalogState.distinct;
}
if (catalogState.queryProperties.length > 0) {
body.query = {
...getCatalogQueries(catalogState),
};
}
if (!catalogState.disableInclude || !catalogState.disableExclude) {
body.fields = {
...getCatalogFields(catalogState),
};
}
return body;
};
export const generateCatalogRequest = (catalogState, geometry, token, next = 0, reqConfig) => {
const body = getCatalogRequestBody(catalogState, geometry);
const config = getConfigHelper(token, reqConfig);
const url = CATALOG_BASE_URL + 'search';
if (next) {
body.next = next;
}
return Axios.post(url, body, config);
};
export const generateCatalogCurlCommand = (catalogState, geometry, token) => {
const url = CATALOG_BASE_URL + 'search';
const body = JSON.stringify(getCatalogRequestBody(catalogState, geometry), null, 2);
const curlCommand = `curl -X POST ${url} \n -H 'Content-Type: application/json' \n -H 'Authorization: Bearer ${
token ? token : '<your token here>'
}' \n -d '${body}'`;
return curlCommand;
};
<file_sep>/src/components/tpdi/TPDIRequestPreview.js
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Controlled as CodeMirror } from 'react-codemirror2';
import {
getDeleteOrderTpdiCurlCommand,
getCreateViaProductsTpdiCurlCommand,
getCreateViaDataFilterTpdiCurlCommand,
getSearchTpdiCurlCommand,
getAllOrdersTpdiCurlCommand,
getConfirmOrderTpdiCurlCommand,
} from './generateTPDIRequests';
import debounceRender from 'react-debounce-render';
require('codemirror/lib/codemirror.css');
require('codemirror/theme/eclipse.css');
require('codemirror/mode/powershell/powershell.js');
require('codemirror/addon/edit/matchbrackets.js');
const getRequestPreview = (request, state) => {
if (request === 'PRODUCTS') {
return getCreateViaProductsTpdiCurlCommand(state);
}
if (request === 'DATAFILTER') {
return getCreateViaDataFilterTpdiCurlCommand(state);
}
if (request === 'SEARCH') {
return getSearchTpdiCurlCommand(state);
}
if (request === 'GET') {
return getAllOrdersTpdiCurlCommand(state);
}
if (request === 'CONFIRM') {
return getConfirmOrderTpdiCurlCommand(state);
}
if (request === 'DELETE') {
return getDeleteOrderTpdiCurlCommand(state);
}
};
const TPDIRequestPreview = ({ state }) => {
const [text, setText] = useState('');
const [request, setRequest] = useState('PRODUCTS');
useEffect(() => {
setText(getRequestPreview(request, state));
}, [state, request]);
const handleCopy = () => {
navigator.clipboard.writeText(text.replace(/(\r\n|\n|\r)/gm, ''));
};
return (
<>
<h2 className="heading-secondary">Request Preview</h2>
<div className="form">
<div className="tpdi-request-preview-select-request">
<label className="form__label">Request</label>
<select value={request} onChange={(e) => setRequest(e.target.value)} className="form__input">
<option value="DATAFILTER">create with datafilter</option>
<option value="PRODUCTS">create with product id</option>
<option value="SEARCH">search</option>
<option value="GET">get all orders</option>
<option value="CONFIRM">confirm order</option>
<option value="DELETE">delete order</option>
</select>
</div>
<CodeMirror
value={text}
options={{
mode: 'powershell',
theme: 'eclipse',
matchBrackets: true,
}}
onBeforeChange={(editor, data, value) => setText(value)}
className="process-editor"
/>
<div className="tpdi-request-preview-buttons">
<button className="secondary-button" onClick={handleCopy}>
Copy
</button>
</div>
</div>
</>
);
};
const mapStateToProps = (state) => ({
state,
});
const debouncedComponent = debounceRender(TPDIRequestPreview, 500);
export default connect(mapStateToProps)(debouncedComponent);
<file_sep>/src/utils/generateRequest.js
import Axios from 'axios';
import { CRS, DATASOURCES, LOCATIONS, isEmpty } from '../utils/const';
import { transformGeometryToNewCrs } from './crsTransform';
const byocLocationToBaseUrl = (location) => {
if (location === 'EU-CENTRAL-1') {
return 'https://services.sentinel-hub.com/';
} else if (location === 'US-WEST-2') {
return 'https://services-uswest2.sentinel-hub.com/';
}
};
export const getUrl = (requestState) => {
if (requestState.datasource === 'CUSTOM') {
return byocLocationToBaseUrl(requestState.byocLocation) + 'api/v1/process';
} else {
return DATASOURCES[requestState.datasource].url;
}
};
export const getJSONRequestBody = (reqState, formated = true) => {
const requestBody = getRequestObject(reqState);
if (formated) {
return JSON.stringify(requestBody, null, 2);
}
return JSON.stringify(requestBody);
};
export const getRequestObject = (reqState) => {
const requestBody = {
input: {
bounds: {
...generateBounds(reqState),
},
data: getRequestData(reqState),
},
output: {
...generateOutput(reqState),
responses: generateResponses(reqState),
},
evalscript: getEvalscriptDebuggerHelper(reqState.evalscript),
};
return requestBody;
};
const getConsoleLogContents = (evalscript) => {
let startIdx = evalscript.indexOf('console.log(') + 11;
let idx = startIdx;
while (evalscript[idx] !== ';' && idx < evalscript.length) {
idx++;
}
let endIdx = idx;
let contents = evalscript.substring(startIdx, endIdx);
return { contents: contents, newEvalscript: evalscript.replace(contents, '') };
};
const processConsoleLogContents = (contents) => {
//customSplit splits each comma that is not inside an array [].
const customSplit = (str, separator) => {
let list = [''];
let i = 0;
let skip = false;
for (let char of str) {
if (char === '[') {
skip = true;
}
if (char === ']') {
skip = false;
}
if (char === separator && !skip) {
i++;
list.push('');
} else {
list[i] += char;
}
}
return list;
};
return customSplit(contents, ',').join('+ "," + ');
};
//looks for console.log and changes it with throw new Error() for debug purposes.
const getEvalscriptDebuggerHelper = (evalscript) => {
if (!evalscript.includes('console.log(')) {
return evalscript;
} else {
const { contents, newEvalscript } = getConsoleLogContents(evalscript);
const consoleLogContents = processConsoleLogContents(contents);
let returnVal = newEvalscript.replace('console.log', 'throw new Error' + consoleLogContents);
return returnVal;
}
};
export const getLocationByDatasource = (datasource) => LOCATIONS[DATASOURCES[datasource].url];
const getRequestData = (reqState) => {
if (reqState.datasource === 'DATAFUSION') {
return reqState.datafusionSources.map((source, idx) => ({
type: source.datasource,
id: source.id,
location: getLocationByDatasource(source.datasource),
...getDataFilter(reqState, idx),
...getProcessingOptions(reqState, idx),
}));
} else {
return [
{
type: reqState.datasource,
...getDataFilter(reqState),
...getProcessingOptions(reqState),
},
];
}
};
const getDataFilter = (requestState, idx) => {
const dataFilter = {
dataFilter: {
...getTimeRange(requestState, idx),
...getDataFilterOptions(requestState, idx),
},
};
if (isEmpty(dataFilter.dataFilter)) {
return {};
}
return dataFilter;
};
const getTimeRange = (requestState, idx = 0) => {
if (requestState.isTimeRangeDisabled) {
return {};
}
return {
timeRange: {
from: requestState.timeFrom[idx] ? requestState.timeFrom[idx] : requestState.timeFrom[0],
to: requestState.timeTo[idx] ? requestState.timeTo[idx] : requestState.timeTo[0],
},
};
};
export const generateBounds = (requestState) => {
if (requestState.geometryType === 'BBOX') {
return {
bbox: transformGeometryToNewCrs(requestState.geometry, requestState.CRS),
properties: {
crs: CRS[requestState.CRS].url,
},
};
} else if (requestState.geometryType === 'POLYGON') {
return {
geometry: transformGeometryToNewCrs(requestState.geometry, requestState.CRS),
properties: {
crs: CRS[requestState.CRS].url,
},
};
}
};
const generateOutput = (state) => {
//HEIGHT or RES
if (state.mode === 'PROCESS') {
if (state.heightOrRes === 'HEIGHT') {
return {
width: state.width,
height: state.height,
};
} else if (state.heightOrRes === 'RES') {
return {
resx: state.width,
resy: state.height,
};
}
} else if (state.mode === 'BATCH') {
return {};
}
};
const generateResponses = (reqState) =>
reqState.responses.map((resp) => ({ identifier: resp.identifier, format: { type: resp.format } }));
const getProcessingOptions = (reqState, idx = 0) => {
const resObject = {
processing: {},
};
//Iterate through the keys, omit DEFAULT ones.
if (reqState.processingOptions[idx].options) {
Object.keys(reqState.processingOptions[idx].options).forEach((key) => {
const value = reqState.processingOptions[idx].options[key];
if (value !== 'DEFAULT' && value !== undefined) {
resObject.processing[key] = value;
}
});
}
return Object.entries(resObject.processing).length !== 0 ? resObject : {};
};
const getDataFilterOptions = (reqState, idx = 0) => {
const resObject = {};
//Iterate through the keys, omit DEFAULT ones.
if (reqState.dataFilterOptions[idx].options) {
Object.keys(reqState.dataFilterOptions[idx].options).forEach((key) => {
const value = reqState.dataFilterOptions[idx].options[key];
if (value !== 'DEFAULT' && value !== undefined) {
resObject[key] = value;
}
});
}
return resObject;
};
const getToken = (token) => {
if (token) {
return token;
} else {
return '<YOU NEED TO LOGIN TO GET A TOKEN>';
}
};
export const generateProcessCurlCommand = (reqState, token) => {
const body = getJSONRequestBody(reqState);
const curlCommand = `curl -X POST ${getUrl(
reqState,
)} \n -H 'Content-Type: application/json' \n -H 'Authorization: Bearer ${getToken(token)}' \n -d '${body}'`;
return curlCommand;
};
export const generateAxiosRequest = (requestState, token, reqConfig) => {
try {
const body = getJSONRequestBody(requestState);
const config = getProcessRequestConfig(token, reqConfig, requestState);
const url = getUrl(requestState);
return Axios.post(url, body, config);
} catch (err) {
return null;
}
};
export const getProcessRequestConfig = (token, reqConfig, reqState) => {
const shouldAcceptTar = Boolean(reqState.responses.length > 1);
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
responseType: 'blob',
...reqConfig,
};
if (shouldAcceptTar) {
config.headers.Accept = 'application/tar';
}
return config;
};
export const getCustomCollections = (token, location) => {
const url = byocLocationToBaseUrl(location) + 'api/v1/byoc/collections';
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
};
return Axios.get(url, config);
};
<file_sep>/src/components/batch/GetSingleRequestButton.js
import React from 'react';
import RequestButton from '../RequestButton';
import { connect } from 'react-redux';
import { addAlertOnError, batchIdValidation } from './BatchActions';
import { getSingleBatchRequest } from '../../utils/batchActions';
import store, { batchSlice } from '../../store';
const GetSingleRequestButton = ({ token, selectedBatchId, setFetchedRequests }) => {
const getSingleBatchHandler = (response) => {
store.dispatch(batchSlice.actions.setExtraInfo(''));
setFetchedRequests([response]);
};
return (
<div>
<RequestButton
validation={batchIdValidation(token, selectedBatchId)}
disabledTitle="Log in and set a batch request to use this"
className="secondary-button"
buttonText="Get batch request by id"
responseHandler={getSingleBatchHandler}
errorHandler={addAlertOnError}
request={getSingleBatchRequest}
args={[token, selectedBatchId]}
/>
</div>
);
};
const mapStateToProps = (state) => ({
token: state.auth.user.access_token,
selectedBatchId: state.batch.selectedBatchId,
});
export default connect(mapStateToProps)(GetSingleRequestButton);
<file_sep>/src/components/DataSourceSpecificOptions/S2L1COptions.js
import React from 'react';
import BasicOptions from './BasicOptions';
import store, { requestSlice } from '../../store';
import { connect } from 'react-redux';
const S2L1COptions = ({ reduxPreviewMode, idx }) => {
const handlePreviewChange = (e) => {
store.dispatch(requestSlice.actions.setDataFilterOptions({ previewMode: e.target.value, idx: idx }));
};
return (
<div>
<BasicOptions idx={idx} />
<label className="form__label u-margin-top-tiny">Preview Mode</label>
<select className="form__input" value={reduxPreviewMode} onChange={handlePreviewChange}>
<option value="DEFAULT">Default</option>
<option value="DETAIL">Detail</option>
<option value="PREVIEW">Preview</option>
<option value="EXTENDED_PREVIEW">Extended preview</option>
</select>
</div>
);
};
const mapStateToProps = (store, ownProps) => ({
reduxPreviewMode: store.request.dataFilterOptions[ownProps.idx].options.previewMode,
});
export default connect(mapStateToProps)(S2L1COptions);
<file_sep>/src/components/forms/RequestForm.js
import React from 'react';
import DataSourceSelect from '../input/DataSourceSelect';
import TimeRangeSelect from '../input/TimeRangeSelect';
import Output from '../output/Output';
import EvalscriptEditor from '../Evalscript/EvalscriptEditor';
import RequestPreview from '../output/RequestPreview';
import MapContainer from '../input/MapContainer';
const RequestForm = () => {
return (
<div>
<div className="process-first-row">
<div className="process-first-row-first-item">
<DataSourceSelect />
</div>
<div className="process-first-row-second-item">
<TimeRangeSelect />
<div className="output u-margin-top-small">
<Output />
</div>
</div>
<div className="process-first-row-third-item">
<MapContainer />
</div>
</div>
<div className="process-second-row">
<div className="process-second-row-first-item">
<EvalscriptEditor />
</div>
<div className="process-second-row-second-item">
<RequestPreview />
</div>
</div>
</div>
);
};
export default RequestForm;
<file_sep>/src/components/Evalscript/utils/index.js
import { DATASOURCES } from '../../../utils/const';
import Axios from 'axios';
export const convertEvalscript = (evalscript, datasource, token, reqConfig) => {
const url = `${DATASOURCES[datasource].url}/convertscript?datasetType=${datasource}`;
const config = {
headers: {
'Content-Type': 'application/ecmascript',
Authorization: `Bearer ${token}`,
},
...reqConfig,
};
return Axios.post(url, evalscript, config);
};
const fetchDataProductsHelper = (token, datasource, viewtoken = 0, reqConfig) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
},
...reqConfig,
};
const url = `https://services.sentinel-hub.com/configuration/v1/datasets/${datasource}/dataproducts?viewtoken=${viewtoken}`;
return Axios.get(url, config);
};
export const fetchDataProducts = async (datasource, token, reqConfig) => {
let res = await fetchDataProductsHelper(token, datasource, 0, reqConfig);
let dataproducts = res.data.member;
while (res.data.view.nextToken) {
res = await fetchDataProductsHelper(token, datasource, res.data.view.nextToken, reqConfig);
dataproducts = dataproducts.concat(res.data.member);
}
return dataproducts;
};
<file_sep>/src/utils/generateShPyRequest.js
import {
S1GRD,
S2L1C,
S2L2A,
S3OLCI,
S3SLSTR,
S5PL2,
MODIS,
DEM,
L8L1C,
isEmpty,
CUSTOM,
DATAFUSION,
} from './const';
import { generateSHBbox } from './generateShjsRequest';
import { transformGeometryToNewCrs } from './crsTransform';
import { getLocationByDatasource } from './generateRequest';
const formatToSHPY = {
'image/jpeg': 'MimeType.JPG',
'image/png': 'MimeType.PNG',
'image/tiff': 'MimeType.TIFF',
};
const getSHPYImports = () => {
return `import matplotlib.pyplot as plt \n
from sentinelhub import SentinelHubRequest, SentinelHubDownloadClient, DataSource, \
MimeType, DownloadRequest, CRS, BBox, SHConfig, Geometry\n`;
};
const getSHPYS1Datasource = (reqState) => {
const isDefault = (option) => {
return Boolean(!option || option === 'DEFAULT');
};
//Sh-py options.
let possibleOptions = [
'SENTINEL1_EW',
'SENTINEL1_EW_ASC',
'SENTINEL1_EW_DES',
'SENTINEL1_EW_SH',
'SENTINEL1_EW_SH_ASC',
'SENTINEL1_EW_SH_DES',
'SENTINEL1_IW',
'SENTINEL1_IW_ASC',
'SENTINEL1_IW_DES',
];
const dataFilterOptions = reqState.dataFilterOptions[0].options;
const { acquisitionMode, polarization, orbitDirection } = dataFilterOptions;
// Default
if (isDefault(acquisitionMode) && isDefault(polarization) && isDefault(orbitDirection)) {
return 'SENTINEL1_IW';
}
if (orbitDirection === 'ASCENDING' || isDefault(orbitDirection)) {
possibleOptions = possibleOptions.filter((opt) => opt.includes('ASC'));
}
if (orbitDirection === 'DESCENDING') {
possibleOptions = possibleOptions.filter((opt) => opt.includes('DES'));
}
if (acquisitionMode === 'IW' || isDefault(acquisitionMode)) {
possibleOptions = possibleOptions.filter((opt) => opt.includes('IW'));
}
if (acquisitionMode === 'EW') {
possibleOptions = possibleOptions.filter((opt) => opt.includes('EW'));
}
if (polarization === 'SH') {
possibleOptions = possibleOptions.filter((opt) => opt.includes('SH'));
}
return possibleOptions.length > 0 ? possibleOptions[0] : 'SENTINEL1_IW';
};
const datasourceToSHPYDatasource = (datasource, requestState) => {
switch (datasource) {
case S1GRD:
return `DataSource.${getSHPYS1Datasource(requestState)}`;
case S2L2A:
return 'DataSource.SENTINEL2_L2A';
case S2L1C:
return 'DataSource.SENTINEL2_L1C';
case S3OLCI:
case S3SLSTR:
return 'DataSource.SENTINEL3';
case MODIS:
return 'DataSource.MODIS';
case DEM:
return 'DataSource.DEM';
case L8L1C:
return 'DataSource.LANDSAT8_L1C';
case S5PL2:
return 'DataSource.SENTINEL5P';
case CUSTOM:
return `DataSource('${
requestState.dataFilterOptions[0].options.collectionId
? requestState.dataFilterOptions[0].options.collectionId
: ''
}')`;
default:
return '';
}
};
const getDimensionsSHPY = (requestState) => {
if (requestState.heightOrRes === 'HEIGHT') {
return `size=[${requestState.width}, ${requestState.height}],`;
} else {
return `resolution=(${requestState.width}, ${requestState.height}),`;
}
};
const crsToSHPYCrs = {
'EPSG:4326': 'CRS.WGS84',
'EPSG:3857': 'CRS.POP_WEB',
};
const getSHPYCredentials = () => {
return `
#Credentials
CLIENT_ID = '<your client id here>'
CLIENT_SECRET = '<your client secret here>'
config = SHConfig()
if CLIENT_ID and CLIENT_SECRET:
config.sh_client_id = CLIENT_ID
config.sh_client_secret = CLIENT_SECRET
else:
config = None
`;
};
const getSHPYBounds = (reqState) => {
let boundsString = '';
const bbox = generateSHBbox(reqState.geometry, reqState.CRS);
boundsString += `bbox = BBox(bbox=[${bbox}], crs=${crsToSHPYCrs[reqState.CRS]})\n`;
if (reqState.geometry.type === 'Polygon') {
const transformedGeo = transformGeometryToNewCrs(reqState.geometry, reqState.CRS);
boundsString += `geometry = Geometry(geometry=${JSON.stringify(transformedGeo)}, crs=${
crsToSHPYCrs[reqState.CRS]
})\n`;
}
return boundsString;
};
const generateSHPYInputs = (reqState) => {
// Datafusion
if (reqState.datasource === 'DATAFUSION') {
let datafusionString = '';
reqState.datafusionSources.forEach((source, idx) => {
datafusionString += `SentinelHubRequest.input_data(
data_source=${datasourceToSHPYDatasource(source.datasource, reqState)},
${getSHPYTimerange(reqState, idx)}\
${getSHPYAdvancedOptions(reqState, idx)}
),\n `;
});
return datafusionString;
}
// No datafusion
return `SentinelHubRequest.input_data(
data_source=${datasourceToSHPYDatasource(reqState.datasource, reqState)},
${getSHPYTimerange(reqState)}\
${getSHPYAdvancedOptions(reqState)}
)`;
};
const getSHPYTimerange = (reqState, idx = 0) => {
if (reqState.isTimeRangeDisabled) {
return '';
}
let timeFrom = reqState.timeFrom[idx] ? reqState.timeFrom[idx] : reqState.timeFrom[0];
let timeTo = reqState.timeTo[idx] ? reqState.timeTo[idx] : reqState.timeTo[0];
return `time_interval=('${timeFrom.split('T')[0]}', '${timeTo.split('T')[0]}'),`;
};
const getSHPYAdvancedOptions = (reqState, idx = 0) => {
const initialDataFilterOptions = reqState.dataFilterOptions[idx].options;
const initialProcessingOptions = reqState.processingOptions[idx].options;
const dataFilterOptions = {};
const processing = {};
// Iterate through the options and add non default to datafilterOptions/processing
if (!isEmpty(initialDataFilterOptions)) {
Object.keys(initialDataFilterOptions).forEach((key) => {
let value = initialDataFilterOptions[key];
if (value !== 'DEFAULT' && key !== 'collectionId') {
dataFilterOptions[key] = value;
}
});
}
if (!isEmpty(initialProcessingOptions)) {
Object.keys(initialProcessingOptions).forEach((key) => {
let value = initialProcessingOptions[key];
if (value !== 'DEFAULT') {
processing[key] = value;
}
});
}
//If S1, delete acqMode, polarization and orbitDir since they're specified via Datasource.
if (reqState.datasource === 'S1GRD') {
delete dataFilterOptions['acquisitionMode'];
delete dataFilterOptions['polarization'];
delete dataFilterOptions['orbitDirection'];
}
const dataFilterIsEmpty = isEmpty(dataFilterOptions);
const processingIsEmpty = isEmpty(processing);
let resultObject = {};
if (!dataFilterIsEmpty) {
resultObject.dataFilter = dataFilterOptions;
}
if (!processingIsEmpty) {
resultObject.processing = processing;
}
// If datafusion, add location, and id to other args.
if (reqState.datasource === DATAFUSION) {
resultObject.id = reqState.datafusionSources[idx].id;
resultObject.location = getLocationByDatasource(reqState.datafusionSources[idx].datasource);
}
let resultString =
!dataFilterIsEmpty || !processingIsEmpty ? `\n other_args = ${JSON.stringify(resultObject)}` : '';
return resultString;
};
const getSHPYResponses = (reqState) => {
let responsesString = '';
reqState.responses.forEach((resp) => {
responsesString =
responsesString +
`SentinelHubRequest.output_response('${resp.identifier}', ${formatToSHPY[resp.format]}),\n `;
});
return responsesString;
};
export const getSHPYCode = (requestState) => {
//add imports
let shpyCode = `${getSHPYImports()}`;
//Credentials
shpyCode += getSHPYCredentials();
// add evalscript
shpyCode += `\nevalscript = """\n${requestState.evalscript}\n"""\n`;
//add geometry/bounds
shpyCode += getSHPYBounds(requestState);
shpyCode += `\nrequest = SentinelHubRequest(
evalscript=evalscript,
input_data=[
${generateSHPYInputs(requestState)}
],
responses=[
${getSHPYResponses(requestState)}
],
bbox=bbox,\
${requestState.geometry.type === 'Polygon' ? '\n geometry=geometry,' : ''}
${getDimensionsSHPY(requestState)}
config=config
)`;
shpyCode += `\nresponse = request.get_data() `;
return shpyCode;
};
<file_sep>/src/utils/validator.js
import { getLocationByDatasource } from './generateRequest';
const validateDatasource = (requestState) => {
if (requestState.datasource) {
if (requestState.datasource === 'CUSTOM' && requestState.dataFilterOptions[0].options.collectionId) {
return true;
}
if (requestState.datasource === 'DATAFUSION') {
return (
getLocationByDatasource(requestState.datafusionSources[0].datasource) ===
getLocationByDatasource(requestState.datafusionSources[1].datasource)
);
}
if (requestState.datasource !== 'CUSTOM') {
return true;
}
}
return false;
};
export const validateRequestState = (requestState) => {
try {
const { width, height, evalscript, CRS, geometry } = requestState;
const isDatasourceValid = validateDatasource(requestState);
return !!(isDatasourceValid && width && height && evalscript && CRS && geometry);
} catch (err) {
return false;
}
};
<file_sep>/src/components/Evalscript/DataProductSelection.js
import React, { useState, useEffect } from 'react';
import store, { requestSlice } from '../../store';
// Search by id, name, description.
const filterDataProducts = (dataproducts, filterText) => {
if (!filterText) {
return dataproducts;
} else {
return dataproducts.filter((dp) => {
return (
dp.name.toLowerCase().includes(filterText) ||
dp.description.toLowerCase().includes(filterText) ||
dp.id + '' === filterText
);
});
}
};
const DataProductSelection = ({ dataproducts }) => {
const [selectedDataProduct, setSelectedDataProduct] = useState({
id: '',
});
const [filterText, setFilterText] = useState('');
const filteredDataProducts = filterDataProducts(dataproducts, filterText);
const handleChangeFilterText = (e) => {
setFilterText(e.target.value);
};
const handleSelectedDataProductChange = (e) => {
if (e.target.value) {
setSelectedDataProduct(dataproducts.find((dp) => dp.id === parseInt(e.target.value)));
} else {
setSelectedDataProduct({ id: '' });
}
};
// Reset to default on search.
useEffect(() => {
setSelectedDataProduct({ id: '' });
}, [filterText]);
// set evalscript auto
useEffect(() => {
if (selectedDataProduct.id) {
store.dispatch(requestSlice.actions.setEvalscript(selectedDataProduct.evalScript));
}
}, [selectedDataProduct]);
return (
<>
{dataproducts.length > 0 ? (
<>
<select
value={selectedDataProduct.id}
onChange={handleSelectedDataProductChange}
className="form__input"
>
<option value="">Select a Dataproduct</option>
{filteredDataProducts.map((dp) => (
<option value={dp.id} key={dp.id} className="text">
{dp.name}
</option>
))}
</select>
<input
className="form__input"
value={filterText}
onChange={handleChangeFilterText}
type="text"
placeholder="Search for Data Products"
/>
{selectedDataProduct.id ? (
<>
<p className="text u-margin-bottom-tiny">
<span>Description:</span>
{dataproducts.find((dp) => dp.id === parseInt(selectedDataProduct.id)).description}
</p>
</>
) : null}
</>
) : null}
</>
);
};
export default DataProductSelection;
<file_sep>/src/components/catalog/CatalogSendRequestButton.js
import React from 'react';
import RequestButton from '../RequestButton';
import { connect } from 'react-redux';
import { generateCatalogRequest } from './requests';
import store, { catalogSlice, alertSlice } from '../../store';
export const catalogErrorHandler = (error) => {
if (error.response && error.response.data) {
store.dispatch(
alertSlice.actions.addAlert({
type: 'WARNING',
text: 'Error: ' + error.response.data.code + ' - ' + error.response.data.description,
}),
);
} else {
store.dispatch(alertSlice.actions.addAlert({ type: 'WARNING', text: 'Something went wrong' }));
}
console.error(error);
};
const CatalogSendRequestButton = ({ catalogState, geometry, token, setResults }) => {
let type = catalogState.selectedCollection;
const responseHandler = (response) => {
if (response.context.next) {
store.dispatch(catalogSlice.actions.setNext(response.context.next));
}
setResults((res) => ({
results: response.features,
type: type,
}));
};
return (
<>
<RequestButton
request={generateCatalogRequest}
args={[catalogState, geometry, token, undefined]}
validation={Boolean(token)}
className="secondary-button"
disabledTitle="Log in to use this"
buttonText="Send Request"
responseHandler={responseHandler}
errorHandler={catalogErrorHandler}
useShortcut={catalogState.next ? false : true}
/>
</>
);
};
const mapStateToProps = (state) => ({
catalogState: state.catalog,
geometry: state.request.geometry,
token: state.auth.user.access_token,
});
export default connect(mapStateToProps)(CatalogSendRequestButton);
<file_sep>/src/components/catalog/CatalogSentinel2Options.js
import React from 'react';
import store, { catalogSlice } from '../../store';
import { connect } from 'react-redux';
const CatalogSentinel2Options = ({ queryProperties, idx }) => {
const handlePropertyChange = (e) => {
store.dispatch(catalogSlice.actions.setQueryProperty({ idx: idx, propertyName: e.target.value }));
};
const handlePropertyValueChange = (e) => {
store.dispatch(catalogSlice.actions.setQueryProperty({ idx: idx, propertyValue: e.target.value }));
};
const handleOperatorChange = (e) => {
store.dispatch(catalogSlice.actions.setQueryProperty({ idx: idx, operator: e.target.value }));
};
return (
<>
<select
onChange={handlePropertyChange}
value={queryProperties[idx].propertyName}
className="form__input"
>
<option value="">Select A Property</option>
<option value="eo:cloud_cover">Cloud Coverage</option>
</select>
{queryProperties[idx].propertyName ? (
<select value={queryProperties[idx].operator} onChange={handleOperatorChange} className="form__input">
<option value="">Select an operator</option>
<option value="eq">eq</option>
<option value="gt">gt</option>
<option value="lt">lt</option>
<option value="gte">gte</option>
<option value="lte">lte</option>
</select>
) : null}
{queryProperties[idx].propertyName ? (
<input
value={queryProperties[idx].propertyValue}
onChange={handlePropertyValueChange}
className="form__input"
type="number"
/>
) : null}
</>
);
};
const mapStateToProps = (state) => ({
queryProperties: state.catalog.queryProperties,
});
export default connect(mapStateToProps)(CatalogSentinel2Options);
<file_sep>/src/components/batch/CreateBatchRequestButton.js
import React from 'react';
import { connect } from 'react-redux';
import RequestButton from '../RequestButton';
import { createBatchRequest } from '../../utils/batchActions';
import store, { batchSlice } from '../../store';
import { addAlertOnError } from './BatchActions';
import { validateRequestState } from '../../utils/validator';
const isCreatePossible = (batchState, requestState, token) => {
const { tillingGrid, resolution, bucketName } = batchState;
const isValid = validateRequestState(requestState);
return resolution && bucketName && isValid && tillingGrid !== undefined && token;
};
const CreateBatchRequestButton = ({ batchState, requestState, token, setFetchedRequests }) => {
const createResponseHandler = (response) => {
setFetchedRequests([response]);
store.dispatch(batchSlice.actions.setSelectedBatchId(response['id']));
};
return (
<div>
<RequestButton
validation={isCreatePossible(batchState, requestState, token)}
className="secondary-button"
buttonText="Create"
request={createBatchRequest}
args={[requestState, batchState, token]}
responseHandler={createResponseHandler}
errorHandler={addAlertOnError}
/>
</div>
);
};
const mapStateToProps = (state) => ({
batchState: state.batch,
requestState: state.request,
token: state.auth.user.access_token,
});
export default connect(mapStateToProps)(CreateBatchRequestButton);
<file_sep>/src/components/catalog/const.js
export const S2L1C_CATALOG_ID = 'sentinel-2-l1c';
export const S2L2A_CATALOG_ID = 'sentinel-2-l2a';
export const S1GRD_CATALOG_ID = 'sentinel-1-grd';
export const S1OPTIONS = [
{
propertyName: 'sar:instrument_mode',
possibleValues: ['SM', 'IW', 'EW', 'WV'],
operators: ['eq'],
},
{
propertyName: 'sat:orbit_state',
possibleValues: ['ASCENDING', 'DESCENDING'],
operators: ['eq'],
},
{
propertyName: 'resolution',
possibleValues: ['HIGH', 'MEDIUM'],
operators: ['eq'],
},
{
propertyName: 'polarization',
possibleValues: ['SH', 'SV', 'DH', 'DV', 'HH', 'HV', 'VV', 'VH'],
operators: ['eq'],
},
{
propertyName: 'timeliness',
possibleValues: ['NRT10m', 'NRT1h', 'NRT3h', 'Fast24h', 'Offline', 'Reprocessing', 'ArchNormal'],
operators: ['eq'],
},
];
<file_sep>/src/components/input/DataSourceSelect.js
import React, { useState } from 'react';
import { connect } from 'react-redux';
import store, { requestSlice } from '../../store';
import {
DATASOURCES,
S2L2A,
S2L1C,
L8L1C,
MODIS,
S3OLCI,
S3SLSTR,
S5PL2,
S1GRD,
DEM,
CUSTOM,
DATAFUSION,
} from '../../utils/const';
import BasicOptions from '../DataSourceSpecificOptions/BasicOptions';
import S2L1COptions from '../DataSourceSpecificOptions/S2L1COptions';
import S3SLSTROptions from '../DataSourceSpecificOptions/S3SLSTROptions';
import S5PL2Options from '../DataSourceSpecificOptions/S5PL2Options';
import S1GRDOptions from '../DataSourceSpecificOptions/S1GRDOptions';
import BaseOptionsNoCC from '../DataSourceSpecificOptions/BaseOptionsNoCC';
import DEMOptions from '../DataSourceSpecificOptions/DEMOptions';
import BYOCOptions from '../DataSourceSpecificOptions/BYOCOptions';
import DataFusionOptions from '../DataSourceSpecificOptions/DataFusionOptions';
import Toggle from '../Toggle';
export const generateDatasourcesOptions = () =>
Object.keys(DATASOURCES).map((key) => (
<option key={key} value={key}>
{key}
</option>
));
//idx is to reference different datasource options (in case of datafusion)
export const generateDataSourceRelatedOptions = (datasource, idx = 0) => {
switch (datasource) {
case S2L2A:
return <BasicOptions idx={idx} />;
case S2L1C:
return <S2L1COptions idx={idx} />;
case L8L1C:
return <BasicOptions idx={idx} />;
case MODIS:
return <BaseOptionsNoCC idx={idx} />;
case S3OLCI:
return <BaseOptionsNoCC idx={idx} />;
case S3SLSTR:
return <S3SLSTROptions idx={idx} />;
case S5PL2:
return <S5PL2Options idx={idx} />;
case S1GRD:
return <S1GRDOptions idx={idx} />;
case DEM:
return <DEMOptions idx={idx} />;
case CUSTOM:
return <BYOCOptions idx={idx} />;
case DATAFUSION:
return <DataFusionOptions idx={idx} />;
default:
return '';
}
};
const DataSourceSelect = ({ datasource }) => {
const [showAdvanced, setShowAdvanced] = useState(false);
const handleChange = (e) => {
store.dispatch(requestSlice.actions.setDatasourceAndEvalscript(e.target.value));
};
const handleShowAdvanced = () => {
setShowAdvanced(!showAdvanced);
};
const handleReset = () => {
store.dispatch(requestSlice.actions.resetAdvancedOptions());
setShowAdvanced(false);
};
return (
<>
<h2 className="heading-secondary">Data source</h2>
<div className="form">
<label className="form__label">Datasource</label>
<select value={datasource} required className="form__input" onChange={(e) => handleChange(e)}>
{generateDatasourcesOptions()}
</select>
{datasource !== 'CUSTOM' && datasource !== 'DATAFUSION' ? (
<div style={{ whiteSpace: 'nowrap' }}>
<div className="toggle-with-label">
<label className="form__label" htmlFor="advanced-options">
{showAdvanced ? 'Hide advanced options' : 'Show advanced options'}
</label>
<Toggle id="advanced-options" onChange={handleShowAdvanced} checked={showAdvanced} />
</div>
</div>
) : null}
{datasource === 'CUSTOM' || datasource === 'DATAFUSION' ? (
generateDataSourceRelatedOptions(datasource)
) : showAdvanced ? (
<>
{generateDataSourceRelatedOptions(datasource)}
<button
onClick={handleReset}
className="secondary-button secondary-button--fit u-margin-right-small"
>
Reset to default
</button>
</>
) : null}
</div>
</>
);
};
const mapStateToProps = (store) => ({
datasource: store.request.datasource,
});
export default connect(mapStateToProps, null)(DataSourceSelect);
<file_sep>/src/components/output/Output.js
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import store, { requestSlice } from '../../store';
import { OUTPUT_FORMATS } from '../../utils/const';
import { calculateDimensionsLowResPreview, calculateAutoDimensions } from '../../utils/bboxRatio';
import Toggle from '../Toggle';
const generatePlaceholder = (heightOrRes, input) => {
if (heightOrRes === 'HEIGHT') {
if (input === 'x') {
return 'width in px';
}
if (input === 'y') {
return 'height in px';
}
} else if (heightOrRes === 'RES') {
if (input === 'x') {
return 'x resolution in meters';
}
if (input === 'y') {
return 'y resolution in meters';
}
}
};
const generateResponses = (responses, mode) => {
const handleIdentifierChange = (e) => {
store.dispatch(
requestSlice.actions.setResponse({ idx: parseInt(e.target.name), identifier: e.target.value }),
);
};
const handleImageFormatChange = (e) => {
store.dispatch(
requestSlice.actions.setResponse({ idx: parseInt(e.target.name), format: e.target.value }),
);
};
const handleDeleteResponse = (e) => {
store.dispatch(requestSlice.actions.deleteResponse(parseInt(e.target.getAttribute('name'))));
};
if (mode === 'WMS') {
return (
<div className="response">
<label className="form__label">Image Format</label>
<select
onChange={handleImageFormatChange}
value={responses[0].format}
name={responses[0].idx}
className="form__input"
>
{OUTPUT_FORMATS.map((format) => (
<option key={format.name} value={format.value}>
{format.name}
</option>
))}
</select>
</div>
);
}
return responses.map((resp, idx) => (
<div className="response" key={resp.idx}>
<label className="form__label">Image Format</label>
<select onChange={handleImageFormatChange} value={resp.format} name={resp.idx} className="form__input">
{OUTPUT_FORMATS.map((format) => (
<option key={format.name} value={format.value}>
{format.name}
</option>
))}
</select>
<label className="form__label">Identifier</label>
<input
value={resp.identifier}
onChange={handleIdentifierChange}
name={resp.idx}
type="text"
className="form__input"
/>
{resp.idx !== 0 ? (
<button
name={resp.idx}
className="secondary-button secondary-button--cancel"
onClick={handleDeleteResponse}
>
Remove Response
</button>
) : null}
{responses.length - 1 !== idx ? <hr className="u-margin-top-tiny"></hr> : null}
</div>
));
};
const Output = ({ heightOrRes, height, width, geometry, mode, responses }) => {
const [isAuto, setIsAuto] = useState(true);
const handleRadioChange = (e) => {
store.dispatch(requestSlice.actions.setHeightOrRes(e.target.value));
if (e.target.value === 'RES') {
store.dispatch(requestSlice.actions.setWidthOrHeight({ x: 100, y: 100 }));
}
};
const handleTextChange = (e) => {
if (isAuto && e.target.value !== '') {
if (e.target.name === 'x') {
const newDimensions = calculateAutoDimensions(geometry, parseInt(e.target.value), undefined);
dispatchNewDimensions(newDimensions);
} else if (e.target.name === 'y') {
const newDimensions = calculateAutoDimensions(geometry, undefined, parseInt(e.target.value));
dispatchNewDimensions(newDimensions);
}
} else {
store.dispatch(requestSlice.actions.setWidthOrHeight({ [e.target.name]: e.target.value }));
}
};
const dispatchNewDimensions = (newDimensions) => {
if (newDimensions) {
const newWidth = newDimensions[0];
const newHeight = newDimensions[1];
store.dispatch(requestSlice.actions.setWidthOrHeight({ x: newWidth, y: newHeight }));
}
};
const handleAddResponse = () => {
store.dispatch(requestSlice.actions.addResponse());
};
// Update output width/height when geometry is updated. Keeps bbox ratio (only when selecting height or res)
useEffect(() => {
if (isAuto && geometry && heightOrRes === 'HEIGHT') {
const newDimensions = calculateDimensionsLowResPreview(geometry);
dispatchNewDimensions(newDimensions);
}
}, [geometry, isAuto, heightOrRes]);
return (
<>
<h2 className="heading-secondary">{mode === 'PROCESS' ? 'Output' : 'Output - Low res preview'}</h2>
<div className="form">
<div className="width-or-res">
<input
className="form__input u-margin-right-tiny"
onChange={handleRadioChange}
checked={heightOrRes === 'HEIGHT'}
type="radio"
id="height"
value="HEIGHT"
name="format"
style={{ cursor: 'pointer' }}
/>
<label style={{ cursor: 'pointer' }} className="form__label u-margin-right-small" htmlFor="height">
Height and width
</label>
<input
className="form__input u-margin-right-tiny"
onChange={handleRadioChange}
checked={heightOrRes === 'RES'}
type="radio"
id="res"
value="RES"
name="format"
style={{ cursor: 'pointer' }}
/>
<label style={{ cursor: 'pointer' }} className="form__label" htmlFor="res">
Resolution
</label>
</div>
<label className="form__label">{heightOrRes === 'HEIGHT' ? 'Width' : 'Res X (in CRS units)'}</label>
<input
required
className="form__input"
type="text"
name="x"
value={width}
onChange={handleTextChange}
placeholder={generatePlaceholder(heightOrRes, 'x')}
/>
<label className="form__label">{heightOrRes === 'HEIGHT' ? 'Height' : 'Res Y (in CRS units)'}</label>
<input
required
className="form__input"
type="text"
name="y"
value={height}
onChange={handleTextChange}
placeholder={generatePlaceholder(heightOrRes, 'y')}
/>
{heightOrRes === 'HEIGHT' ? (
<div className="toggle-with-label">
<label htmlFor="auto" className="form__label">
Keep ratio automatically
</label>
<Toggle id="auto" checked={isAuto} onChange={() => setIsAuto(!isAuto)} />
</div>
) : null}
{generateResponses(responses, mode)}
{mode !== 'WMS' ? (
<button className="secondary-button" onClick={handleAddResponse}>
Add Response
</button>
) : null}
</div>
</>
);
};
const mapStateToProps = (store) => ({
heightOrRes: store.request.heightOrRes,
responses: store.request.responses,
height: store.request.height,
width: store.request.width,
geometry: store.request.geometry,
mode: store.request.mode,
});
export default connect(mapStateToProps, null)(Output);
<file_sep>/src/components/catalog/CatalogCollectionSelection.js
import React, { useState, useEffect } from 'react';
import { getCatalogCollections } from './requests';
import { connect } from 'react-redux';
import store, { catalogSlice } from '../../store';
import Axios from 'axios';
const generateCollectionsOptions = (collections) =>
collections.map((collection) => (
<option key={collection.id} value={collection.id}>
{collection.title}
</option>
));
const CatalogCollectionSelection = ({ token, selectedCollection }) => {
const [collections, setCollections] = useState([]);
const [isFetchingCollections, setIsFetchingCollections] = useState(false);
useEffect(() => {
let source = Axios.CancelToken.source();
const fetchCollections = async () => {
setIsFetchingCollections(true);
try {
const resp = await getCatalogCollections(token, {
cancelToken: source.token,
});
if (resp.data.collections) {
setCollections(
resp.data.collections.map((collection) => ({
id: collection.id,
title: collection.title,
})),
);
setIsFetchingCollections(false);
}
} catch (err) {
if (!Axios.isCancel(err)) {
console.error(err);
}
}
};
if (token) {
fetchCollections();
}
return () => {
if (source) {
source.cancel();
}
};
}, [token]);
const handleSelectedCollectionChange = (e) => {
store.dispatch(catalogSlice.actions.setSelectedCollection(e.target.value));
};
return (
<>
<h2 className="heading-secondary">Collection</h2>
<div className="form">
{!token ? (
<p className="text">Log in to use this</p>
) : isFetchingCollections ? (
<p className="text">Loading...</p>
) : (
<>
<label className="form__label">Selected Collection</label>
<select
value={selectedCollection}
onChange={handleSelectedCollectionChange}
className="form__input"
>
<option value="">Select a Collection</option>
{generateCollectionsOptions(collections)}
</select>
</>
)}
</div>
</>
);
};
const mapStateToProps = (state) => ({
token: state.auth.user.access_token,
selectedCollection: state.catalog.selectedCollection,
});
export default connect(mapStateToProps)(CatalogCollectionSelection);
<file_sep>/src/components/DataSourceSpecificOptions/S1GRDOptions.js
import React from 'react';
import store, { requestSlice } from '../../store';
import BaseOptionsNoCC from './BaseOptionsNoCC';
import { connect } from 'react-redux';
const S1GRDOptions = ({
reduxResolution,
reduxAcquisitionMode,
reduxPolarization,
reduxOrbitDirection,
reduxBackCoeff,
reduxOrthorectify,
idx,
}) => {
const handleResolutionChange = (e) => {
store.dispatch(requestSlice.actions.setDataFilterOptions({ resolution: e.target.value, idx: idx }));
};
const handleAqcuisitionModeChange = (e) => {
store.dispatch(requestSlice.actions.setDataFilterOptions({ acquisitionMode: e.target.value, idx: idx }));
};
const handlePolarizationChange = (e) => {
store.dispatch(requestSlice.actions.setDataFilterOptions({ polarization: e.target.value, idx: idx }));
};
const handleOrbitDirectionChange = (e) => {
store.dispatch(requestSlice.actions.setDataFilterOptions({ orbitDirection: e.target.value, idx: idx }));
};
const handleBackCoeffChange = (e) => {
store.dispatch(requestSlice.actions.setProcessingOptions({ backCoeff: e.target.value, idx: idx }));
};
const handleOrthorectifyChange = () => {
store.dispatch(requestSlice.actions.setProcessingOptions({ orthorectify: !reduxOrthorectify, idx: idx }));
};
return (
<div>
<BaseOptionsNoCC idx={idx} />
<label className="form__label u-margin-top-tiny">Resolution</label>
<select onChange={handleResolutionChange} value={reduxResolution} className="form__input">
<option value="DEFAULT">Default</option>
<option value="HIGH">High</option>
<option value="MEDIUM">Medium</option>
</select>
<label className="form__label">Acquisition Mode</label>
<select onChange={handleAqcuisitionModeChange} value={reduxAcquisitionMode} className="form__input">
<option value="DEFAULT">Default (any)</option>
<option value="SM">SM</option>
<option value="IW">IW</option>
<option value="EW">EW</option>
<option value="WV">WV</option>
</select>
<label className="form__label">Polarization</label>
<select onChange={handlePolarizationChange} value={reduxPolarization} className="form__input">
<option value="DEFAULT">Default (any)</option>
<option value="SH">SH</option>
<option value="SV">SV</option>
<option value="DH">DH</option>
<option value="DV">DV</option>
<option value="HH">HH</option>
<option value="HV">HV</option>
<option value="VV">VV</option>
<option value="VH">VH</option>
</select>
<label className="form__label">Orbit Direction</label>
<select onChange={handleOrbitDirectionChange} value={reduxOrbitDirection} className="form__input">
<option value="DEFAULT">Default (any)</option>
<option value="ASCENDING">Ascending</option>
<option value="DESCENDING">Descending</option>
</select>
<label className="form__label">Backscatter coefficient</label>
<select onChange={handleBackCoeffChange} value={reduxBackCoeff} className="form__input">
<option value="DEFAULT">Default (gamma0)</option>
<option value="BETA0">beta0</option>
<option value="SIGMA0_ELLIPSOID">sigma0</option>
<option value="GAMMA0_ELLIPSOID">gamma0</option>
</select>
<div>
<label style={{ display: 'inline-block' }} className="form__label">
Orthorectify
</label>
<input
style={{ display: 'inline-block', marginLeft: '1rem' }}
type="checkbox"
className="form__input"
checked={Boolean(reduxOrthorectify)}
onChange={handleOrthorectifyChange}
/>
</div>
</div>
);
};
const mapStateToProps = (store, ownProps) => ({
reduxResolution: store.request.dataFilterOptions[ownProps.idx].options.resolution,
reduxAcquisitionMode: store.request.dataFilterOptions[ownProps.idx].options.acquisitionMode,
reduxPolarization: store.request.dataFilterOptions[ownProps.idx].options.polarization,
reduxOrbitDirection: store.request.dataFilterOptions[ownProps.idx].options.orbitDirection,
reduxBackCoeff: store.request.processingOptions[ownProps.idx].options.backCoeff,
reduxOrthorectify: store.request.processingOptions[ownProps.idx].options.orthorectify,
});
export default connect(mapStateToProps)(S1GRDOptions);
<file_sep>/src/components/tpdi/CreateOrderButtonsContainer.js
import React from 'react';
import { createTPDIOrder, createTPDIDataFilterOrder } from './generateTPDIRequests';
import { connect } from 'react-redux';
import store, { alertSlice } from '../../store';
import RequestButton from '../RequestButton';
import { errorHandlerTPDI } from './TPDIOrderOptions';
const validateCreateOrderWithProducts = (products) => {
for (let prod of products) {
if (prod.id && prod.id !== '') {
return true;
}
}
return false;
};
const CreateOrderButtonsContainer = ({
areaSelected,
limit,
request,
airbus,
planet,
tpdi,
token,
collectionId,
}) => {
const products = tpdi.products;
const state = {
request,
airbus,
planet,
tpdi,
};
const handleCreateOrderSuccess = () => {
store.dispatch(alertSlice.actions.addAlert({ type: 'SUCCESS', text: 'Order successfully created' }));
};
const shouldConfirm = !Boolean(collectionId);
return (
<>
<RequestButton
request={createTPDIOrder}
args={[state, token]}
buttonText={products.length > 1 ? 'Order Products' : 'Order Product'}
validation={validateCreateOrderWithProducts(products) && areaSelected <= limit}
className="secondary-button"
responseHandler={handleCreateOrderSuccess}
errorHandler={errorHandlerTPDI}
disabledTitle="Add products and check the limit"
useConfirmation={shouldConfirm}
dialogText="Are you sure you want to create an order without a Collection ID?"
/>
<hr className="u-margin-top-tiny"></hr>
<RequestButton
request={createTPDIDataFilterOrder}
args={[state, token]}
buttonText="Order using DataFilter"
validation={Boolean(token) && areaSelected <= limit}
className="secondary-button"
responseHandler={handleCreateOrderSuccess}
errorHandler={errorHandlerTPDI}
disabledTitle={Boolean(token) ? 'Check the limit' : 'Log in'}
useConfirmation={shouldConfirm}
dialogText="Are you sure you want to create an order without a Collection ID?"
/>
</>
);
};
const mapStateToProps = (state) => ({
tpdi: state.tpdi,
request: state.request,
airbus: state.airbus,
planet: state.planet,
token: state.auth.user.access_token,
collectionId: state.tpdi.collectionId,
});
export default connect(mapStateToProps)(CreateOrderButtonsContainer);
<file_sep>/src/components/SendRequest.js
import React from 'react';
import { connect } from 'react-redux';
import { generateAxiosRequest } from '../utils/generateRequest';
import CancelablePopUpRequestButton from './CancelablePopUpRequestButton';
import store, { requestSlice, responsesSlice } from '../store';
import { validateRequestState } from '../utils/validator';
const debugError = (responseString) => {
return responseString.includes('Failed to evaluate script!') && responseString.includes(' Error: ');
};
const getDebugError = (responseString) => {
const startIndex = responseString.indexOf(' Error: ') + 7;
const endIndex = responseString.indexOf('throw new Error');
let debugMessage = responseString.substring(startIndex, endIndex);
return debugMessage.trim();
};
export const createFileReader = () => {
const fr = new FileReader();
fr.onload = function () {
const resultString = fr.result;
const parsed = JSON.parse(resultString);
if (debugError(resultString)) {
store.dispatch(requestSlice.actions.setConsoleValue(getDebugError(resultString)));
} else {
store.dispatch(responsesSlice.actions.setError(parsed.error.message));
store.dispatch(responsesSlice.actions.setShow(true));
}
};
return fr;
};
const SendRequest = ({ token, requestState }) => {
const isValid = validateRequestState(requestState);
return (
<div>
<CancelablePopUpRequestButton
className={`button`}
buttonText="Send Request"
request={generateAxiosRequest}
args={[requestState, token]}
validation={Boolean(isValid && token)}
requestState={requestState}
useShortcut={true}
/>
</div>
);
};
const mapStateToProps = (store) => ({
token: store.auth.user.access_token,
requestState: store.request,
});
export default connect(mapStateToProps)(SendRequest);
<file_sep>/src/components/Alert.js
import React from 'react';
import { connect } from 'react-redux';
import store, { alertSlice } from '../store';
const generateAlertClass = (type) => {
if (type === 'SUCCESS') {
return 'alert--success';
} else if (type === 'WARNING') {
return 'alert--warning';
} else {
return '';
}
};
const generateEmoji = (type) => {
if (type === 'SUCCESS') {
return '✅';
} else if (type === 'WARNING') {
return '⚠️';
} else {
return '';
}
};
const Alert = ({ alert }) => {
const { type, text } = alert;
return (
<>
{alert.id ? (
<div
onClick={() => store.dispatch(alertSlice.actions.removeAlert(alert.id))}
className={`alert ${generateAlertClass(type)}`}
>
<div className="alert-first-item">
<span>{generateEmoji(type)}</span>
</div>
<div className="alert-second-item">
<span>{text}</span>
</div>
<div className="alert-third-item">
<span>✕</span>
</div>
</div>
) : null}
</>
);
};
const mapStateToProps = (state) => ({
alert: state.alert,
});
export default connect(mapStateToProps)(Alert);
<file_sep>/src/components/RequestButton.js
import React, { useRef, useEffect, useState, useCallback } from 'react';
import Axios from 'axios';
import Mousetrap from 'mousetrap';
import ConfirmDialog from './ConfirmDialog';
//Abstraction of button that sends a request.
const RequestButton = ({
buttonText,
request,
args,
validation,
className,
responseHandler,
errorHandler,
disabledTitle,
//allow shortcut (ctr+enter)
useShortcut,
// params to use ConfirmDialog.
useConfirmation,
dialogText,
}) => {
const [isFetching, setIsFetching] = useState(false);
const [openedConfirmDialog, setOpenedConfirmDialog] = useState(false);
const sourceRef = useRef();
useEffect(() => {
return () => {
Mousetrap.reset();
if (sourceRef.current) {
sourceRef.current.cancel();
}
};
}, []);
const handleSendRequest = useCallback(async () => {
if (isFetching) {
sourceRef.current.cancel();
setIsFetching(false);
} else if (useConfirmation && !openedConfirmDialog) {
setOpenedConfirmDialog(true);
} else {
try {
if (useConfirmation && openedConfirmDialog) {
setOpenedConfirmDialog(false);
}
setIsFetching(true);
sourceRef.current = Axios.CancelToken.source();
const reqConfig = {
cancelToken: sourceRef.current.token,
};
const res = await request(...args, reqConfig);
if (res.data || res.status === 204) {
setIsFetching(false);
responseHandler(res.data);
}
} catch (err) {
if (!Axios.isCancel(err)) {
setIsFetching(false);
if (errorHandler) {
errorHandler(err);
} else {
console.error(err);
}
}
}
}
}, [isFetching, args, request, errorHandler, responseHandler, openedConfirmDialog, useConfirmation]);
//Mousetrap effect, binds
useEffect(() => {
if (useShortcut) {
Mousetrap.bind('ctrl+enter', () => {
if (validation) {
handleSendRequest();
}
});
//Prevent default behaviour allowing using shortcuts in forms, textareas, etc.
Mousetrap.prototype.stopCallback = () => false;
}
}, [useShortcut, handleSendRequest, validation]);
const generateClassName = () => {
if (!validation) {
return className + '--disabled';
} else if (validation && isFetching) {
return className + '--cancel';
} else if (validation && !isFetching) {
return className + '--active';
}
};
return (
<>
<button
className={`${className} ${generateClassName()}`}
disabled={!validation}
onClick={handleSendRequest}
title={!validation ? disabledTitle : null}
>
{isFetching ? 'Cancel Request' : buttonText}
</button>
{useConfirmation && openedConfirmDialog ? (
<ConfirmDialog
onConfirm={handleSendRequest}
onDecline={() => setOpenedConfirmDialog(false)}
dialogText={dialogText}
/>
) : null}
</>
);
};
export default RequestButton;
<file_sep>/src/components/wms/LayerSelector.js
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { getLayersByInstanceId } from './wmsRequests';
import store, { wmsSlice } from '../../store';
const generateLayersOptions = (layers) => {
return layers.map((lay) => (
<option key={lay.id} value={lay.id}>
{lay.title}
</option>
));
};
const LayerSelector = ({ layerId, instanceId, token }) => {
const [layers, setLayers] = useState([]);
useEffect(() => {
const loadLayers = async () => {
if (!token || !instanceId) {
return;
}
try {
const res = await getLayersByInstanceId(token, instanceId);
if (res.data) {
setLayers(
res.data.map((lay) => ({
id: lay.id,
description: lay.description,
title: lay.title,
datasource: lay.datasourceDefaults.type,
otherDefaults: lay.datasourceDefaults,
})),
);
}
} catch (err) {
console.error('Something went wrong loading layers', err);
}
};
loadLayers();
}, [instanceId, token]);
const handleLayerIdChange = (e) => {
store.dispatch(wmsSlice.actions.setLayerId(e.target.value));
};
const handleSelectLayerChange = (e) => {
store.dispatch(wmsSlice.actions.setLayerId(e.target.value));
store.dispatch(
wmsSlice.actions.setDatasource(layers.find((lay) => lay.id === e.target.value).datasource),
);
};
return (
<>
<label className="form__label">Layer</label>
<input
type="text"
className="form__input"
placeholder="Layer id"
value={layerId}
onChange={handleLayerIdChange}
/>
{layers.length > 0 ? (
<>
<label className="form__label">Instance Layers</label>
<select className="form__input" onChange={handleSelectLayerChange}>
<option value="">Select an instance layer</option>
{generateLayersOptions(layers)}
</select>
</>
) : null}
</>
);
};
const mapStateToProps = (state) => ({
instanceId: state.wms.instanceId,
token: state.auth.user.access_token,
layerId: state.wms.layerId,
});
export default connect(mapStateToProps)(LayerSelector);
<file_sep>/src/utils/parseRequest.js
import store, { requestSlice } from '../store';
import { DATASOURCES_NAMES, CRS, OUTPUT_FORMATS } from './const';
import { transformGeometryToNewCrs } from './crsTransform';
const dispatchEvalscript = (parsedBody) => {
try {
const { evalscript } = parsedBody;
if (evalscript) {
store.dispatch(requestSlice.actions.setEvalscript(evalscript));
}
} catch (err) {}
};
const dispatchBounds = (parsedBody) => {
try {
let bounds = parsedBody.input.bounds;
//crs
const crs = bounds.properties.crs;
const selectedCrs = Object.keys(CRS).find((key) => CRS[key].url === crs);
if (selectedCrs) {
store.dispatch(requestSlice.actions.setCRS(selectedCrs));
}
//is bbox
if (bounds.bbox) {
let geometry = bounds.bbox;
// if not wgs84 -> transform to it
if (selectedCrs !== 'EPSG:4326') {
geometry = transformGeometryToNewCrs(bounds.bbox, 'EPSG:4326', selectedCrs);
}
store.dispatch(requestSlice.actions.setGeometry(geometry));
}
//polygon
else if (bounds.geometry) {
let geometry = bounds.geometry;
if (selectedCrs !== 'EPSG:4326') {
geometry = transformGeometryToNewCrs(geometry, 'EPSG:4326', selectedCrs);
}
store.dispatch(requestSlice.actions.setGeometry(geometry));
}
} catch (err) {}
};
const dispatchTimeRange = (parsedBody) => {
try {
const validTimeRanges = parsedBody.input.data.map((bodyInputData) => {
let timeRange = bodyInputData.dataFilter.timeRange;
let timeTo = timeRange.to;
let timeFrom = timeRange.from;
return { timeTo, timeFrom };
});
store.dispatch(requestSlice.actions.setTimeRanges(validTimeRanges));
} catch (err) {}
};
const dispatchDatasource = (parsedBody) => {
try {
//Datafusion
if (parsedBody.input.data.length > 1) {
store.dispatch(requestSlice.actions.setDatasource('DATAFUSION'));
let dataFusionSources = [];
parsedBody.input.data.forEach((data) => {
dataFusionSources.push({ datasource: data.type, id: data.id ? data.id : '' });
});
store.dispatch(requestSlice.actions.setDatafusionSourcesAbs(dataFusionSources));
} else {
const datasource = parsedBody.input.data[0].type;
const validDatasource = DATASOURCES_NAMES.find((d) => d === datasource);
if (validDatasource) {
store.dispatch(requestSlice.actions.setDatasource(validDatasource));
}
}
} catch (err) {}
};
const dispatchDimensions = (parsedBody) => {
try {
const { output } = parsedBody;
const width = output.width;
const height = output.height;
if (height && width) {
store.dispatch(requestSlice.actions.setHeightOrRes('HEIGHT'));
store.dispatch(requestSlice.actions.setWidth(width));
store.dispatch(requestSlice.actions.setHeight(height));
}
const resx = output.resx;
const resy = output.resy;
if (resx && resy) {
store.dispatch(requestSlice.actions.setHeightOrRes('RES'));
store.dispatch(requestSlice.actions.setWidth(resx));
store.dispatch(requestSlice.actions.setHeight(resy));
}
} catch (err) {}
};
const dispatchResponses = (parsedBody) => {
//Helper function to check format of response.
const validFormat = (formatString) => {
return Boolean(OUTPUT_FORMATS.find((format) => format.value === formatString));
};
try {
const responses = parsedBody.output.responses;
const validResponses = responses
.map((resp, idx) => {
if (resp.identifier && validFormat(resp.format.type)) {
return { identifier: resp.identifier, format: resp.format.type, idx: idx };
} else {
return undefined;
}
})
.filter((n) => n);
store.dispatch(requestSlice.actions.setResponses(validResponses));
} catch (err) {}
};
const dispatchAdvancedOptions = (parsedBody) => {
try {
if (parsedBody.input.data.length > 0) {
parsedBody.input.data.forEach((data, idx) => {
const dataFilterOptions = data.dataFilter;
delete dataFilterOptions.timeRange;
if (dataFilterOptions && Object.keys(dataFilterOptions).length > 0) {
dataFilterOptions.idx = idx;
store.dispatch(requestSlice.actions.setDataFilterOptions(dataFilterOptions));
}
const processingOptions = data.processing;
if (processingOptions) {
processingOptions.idx = idx;
store.dispatch(requestSlice.actions.setProcessingOptions(processingOptions));
}
});
}
} catch (err) {}
};
export const dispatchChanges = (parsedBody) => {
store.dispatch(requestSlice.actions.resetAdvancedOptions());
dispatchEvalscript(parsedBody);
dispatchBounds(parsedBody);
dispatchTimeRange(parsedBody);
dispatchDatasource(parsedBody);
dispatchDimensions(parsedBody);
dispatchResponses(parsedBody);
dispatchAdvancedOptions(parsedBody);
};
// Return the json body of a curl command.
export const getRequestBody = (curlString) => {
const bodyCharList = [];
let firstCurlyEncountered = false;
for (let char of curlString) {
if (char === '{' && !firstCurlyEncountered) {
firstCurlyEncountered = true;
}
if (firstCurlyEncountered) {
bodyCharList.push(char);
}
}
while (bodyCharList[bodyCharList.length - 1] !== '}' && bodyCharList.length > 0) {
bodyCharList.pop();
}
return bodyCharList.join('');
};
export const getEvalscript = (evalscriptString) => {
const evalscriptCharList = [];
let equalEncountered = false;
for (let char of evalscriptString) {
if (equalEncountered) {
evalscriptCharList.push(char);
}
if (char === '=' && !equalEncountered) {
equalEncountered = true;
}
}
while (evalscriptCharList[evalscriptCharList.length - 1] !== "'" && evalscriptCharList.length > 0) {
evalscriptCharList.pop();
}
return evalscriptCharList.join('');
};
<file_sep>/src/components/DataSourceSpecificOptions/BaseOptionsNoCC.js
//Common to all datasources
import React from 'react';
import store, { requestSlice } from '../../store';
import { connect } from 'react-redux';
//Contains MosaickingOrder, Upsampling, Downsampling.
const BaseOptionsNoCC = ({ processingOptions, dataFilterOptions, withCC = false, idx }) => {
const mosaickingOrder = dataFilterOptions.mosaickingOrder;
const upsampling = processingOptions.upsampling;
const downsampling = processingOptions.downsampling;
const handleMosaickingChange = (e) => {
store.dispatch(requestSlice.actions.setDataFilterOptions({ mosaickingOrder: e.target.value, idx }));
};
const handleUpsamplingChange = (e) => {
store.dispatch(requestSlice.actions.setProcessingOptions({ upsampling: e.target.value, idx }));
};
const handleDownsamplingChange = (e) => {
store.dispatch(requestSlice.actions.setProcessingOptions({ downsampling: e.target.value, idx }));
};
return (
<div>
<label className="form__label">Mosaicking Order</label>
<select value={mosaickingOrder} className="form__input" onChange={handleMosaickingChange}>
<option value="DEFAULT">Default</option>
<option value="mostRecent">Most recent</option>
<option value="leastRecent">Least recent</option>
{withCC ? <option value="leastCC">Least CC</option> : ''}
</select>
<label className="form__label">Upsampling</label>
<select value={upsampling} onChange={handleUpsamplingChange} className="form__input">
<option value="DEFAULT">Default (Nearest)</option>
<option value="NEAREST">Nearest</option>
<option value="BILINEAR">Bilinear</option>
<option value="BICUBIC">Bicubic</option>
</select>
<label className="form__label">Downsampling</label>
<select value={downsampling} onChange={handleDownsamplingChange} className="form__input">
<option value="DEFAULT">Default (Nearest)</option>
<option value="NEAREST">Nearest</option>
<option value="BILINEAR">Bilinear</option>
<option value="BICUBIC">Bicubic</option>
</select>
</div>
);
};
const mapStateToProps = (store, ownProps) => ({
processingOptions: store.request.processingOptions[ownProps.idx].options,
dataFilterOptions: store.request.dataFilterOptions[ownProps.idx].options,
});
export default connect(mapStateToProps)(BaseOptionsNoCC);
<file_sep>/src/components/Map.js
import React, { useEffect } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import '@geoman-io/leaflet-geoman-free';
import '@geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css';
import bbox from '@turf/bbox';
import store, { requestSlice } from '../store';
//Get as props the reference to the map, the created layers and the drawn items.
const Map = ({ mapRef, layersRef, drawnItemsRef }) => {
//equivalent to ComponentDidMount
//Creates a map and adds neccesary configuration
useEffect(() => {
mapRef.current = L.map('map').setView([41.8952044, 12.4353407], 11);
L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Tiles style by <a href="https://www.hotosm.org/" target="_blank">Humanitarian OpenStreetMap Team</a> hosted by <a href="https://openstreetmap.fr/" target="_blank">OpenStreetMap France</a>',
}).addTo(mapRef.current);
// FeatureGroup is to store editable layers
var drawnItems = new L.FeatureGroup();
drawnItemsRef.current = drawnItems;
mapRef.current.addLayer(drawnItems);
mapRef.current.pm.addControls({
position: 'topleft',
drawCircle: false,
drawCircleMarker: false,
drawMarker: false,
drawPolyline: false,
removalMode: false,
});
mapRef.current.on('pm:create', (e) => {
const layer = e.layer;
layer.removeFrom(mapRef.current);
const shape = e.shape;
const geoJSONFeature = layer.toGeoJSON();
if (shape === 'Rectangle') {
store.dispatch(requestSlice.actions.setGeometry(bbox(geoJSONFeature)));
} else if (shape === 'Polygon') {
store.dispatch(requestSlice.actions.setGeometry(geoJSONFeature.geometry));
}
});
}, [drawnItemsRef, layersRef, mapRef]);
return <div className="map" id="map"></div>;
};
export default Map;
<file_sep>/src/components/wms/wmsRequests.js
import axios from 'axios';
import { transformGeometryToNewCrs } from '../../utils/crsTransform';
import BBox from '@turf/bbox';
import { DATASOURCES } from '../../utils/const';
const getConfigHelper = (token, reqConfig) => {
return {
headers: {
Authorization: `Bearer ${token}`,
},
...reqConfig,
};
};
const BASE_WMS_URL = 'https://services.sentinel-hub.com/configuration/v1/wms/instances/';
export const getAllInstances = (token, reqConfig) => {
const url = BASE_WMS_URL;
const config = getConfigHelper(token, reqConfig);
return axios.get(url, config);
};
export const getLayersByInstanceId = (token, instanceId) => {
const url = `${BASE_WMS_URL}${instanceId}/layers`;
const config = getConfigHelper(token);
return axios.get(url, config);
};
const getPolygonWKT = (geoJsonPolygon) => {
if (geoJsonPolygon.type === 'MultiPolygon') {
return `POLYGON (${geoJsonPolygon.coordinates[0].map((listOfCoords) => {
return (
'(' +
listOfCoords.map((pair) => {
return `${pair[0]} ${pair[1]}`;
}) +
')'
);
})})`;
} else {
return `POLYGON ((${geoJsonPolygon.coordinates[0].map((pair) => {
return `${pair[0]} ${pair[1]}`;
})}))`;
}
};
const crsToWMSCrs = {
'EPSG:3857': 'EPSG:3857',
'EPSG:4326': 'CRS:84',
};
const getWMSBbox = (requestState, mode = 'WMS') => {
const geometry = requestState.geometry;
let geoString = '';
const transformedGeo = transformGeometryToNewCrs(geometry, requestState.CRS);
if (geometry.length === 4) {
geoString = `BBOX=${transformedGeo[0]},${transformedGeo[1]},${transformedGeo[2]},${transformedGeo[3]}`;
} else if (geometry.type === 'Polygon' || geometry.type === 'MultiPolygon') {
// create bbox
const bbox = BBox(transformedGeo);
const stringBbox = `BBOX=${bbox[0]},${bbox[1]},${bbox[2]},${bbox[3]}&`;
if (mode === 'WMS') {
geoString += stringBbox;
}
//add geometry
geoString += `GEOMETRY=${getPolygonWKT(transformedGeo)}`;
}
return geoString;
};
const getWidthOrResWms = (requestState) => {
if (requestState.heightOrRes === 'HEIGHT') {
return `WIDTH=${requestState.width}&HEIGHT=${requestState.height}`;
}
return `RESX=${requestState.width}&RESY=${requestState.height}`;
};
const getWmsTime = (requestState) => {
if (requestState.isTimeRangeDisabled) {
return '';
}
const { timeTo, timeFrom } = requestState;
if (timeTo[0] && timeFrom[0]) {
return '&TIME=' + timeFrom[0].split('T')[0] + '/' + timeTo[0].split('T')[0];
}
};
const getOGCAdvancedOptions = (wmsState) => {
let advancedOptionsString = '';
Object.keys(wmsState.advancedOptions).forEach((key) => {
if (wmsState.advancedOptions[key]) {
advancedOptionsString += `&${key}=${wmsState.advancedOptions[key]}`;
}
});
return advancedOptionsString;
};
const getMapWmsParams = (requestState, wmsState) => {
let params = '';
params += 'REQUEST=GetMap&';
params += `CRS=${crsToWMSCrs[requestState.CRS]}&`;
params += `${getWMSBbox(requestState)}&`;
params += `LAYERS=${wmsState.layerId}&`;
params += `${getWidthOrResWms(requestState)}&`;
params += `FORMAT=${requestState.responses[0].format}`;
params += `${getWmsTime(requestState)}`;
return params;
};
const getFisParams = (requestState, wmsState) => {
let params = '';
params += `LAYER=${wmsState.layerId}&`;
params += `CRS=${crsToWMSCrs[requestState.CRS]}&`;
params += `${getWMSBbox(requestState, 'FIS')}&`;
params += `${getWidthOrResWms(requestState)}`;
params += `${getWmsTime(requestState)}`;
params += getOGCAdvancedOptions(wmsState);
return params;
};
const getServicesEndpoint = (datasource) => {
return DATASOURCES[datasource] ? DATASOURCES[datasource].ogcUrl : 'https://services.sentinel-hub.com/ogc/';
};
export const getWmsUrl = (wmsState, requestState) => {
return `${getServicesEndpoint(wmsState.datasource)}wms/${
wmsState.instanceId ? wmsState.instanceId : '<your instance id>'
}?${getMapWmsParams(requestState, wmsState)}`;
};
export const getFisUrl = (wmsState, requestState) => {
return `${getServicesEndpoint(wmsState.datasource)}fis/${
wmsState.instanceId ? wmsState.instanceId : '<your instance id>'
}?${getFisParams(requestState, wmsState)}`;
};
export const getMapWms = (wmsState, requestState, token, reqConfig) => {
const url = getWmsUrl(wmsState, requestState);
const config = getConfigHelper(token, reqConfig);
config.responseType = 'blob';
return axios.get(url, config);
};
export const getFisStats = (wmsState, requestState, token, reqConfig) => {
const url = getFisUrl(wmsState, requestState);
const config = getConfigHelper(token, reqConfig);
return axios.get(url, config);
};
<file_sep>/src/components/batch/BatchHeaderButtons.js
import React from 'react';
import AuthHeader from '../AuthHeader';
const BatchHeaderButtons = () => {
return (
<div className="header_buttons">
<AuthHeader />
</div>
);
};
export default BatchHeaderButtons;
<file_sep>/src/components/tpdi/QuotaContainer.js
import React, { useState } from 'react';
import { errorHandlerTPDI } from './TPDIOrderOptions';
import RequestButton from '../RequestButton';
import { getTPDIQuota } from './generateTPDIRequests';
import { connect } from 'react-redux';
const QuotaContainer = ({ token }) => {
const [quotas, setQuotas] = useState([]);
const handleGetQuota = (response) => {
setQuotas(response.data);
};
return (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2 className="heading-secondary">Quota</h2>
<div className="form">
<div className="u-margin-bottom-small">
<RequestButton
request={getTPDIQuota}
args={[token]}
buttonText={quotas.length > 0 ? 'Refresh Quotas' : 'Get Quotas'}
validation={Boolean(token)}
className="secondary-button"
responseHandler={handleGetQuota}
disabledTitle="Log in to use this"
errorHandler={errorHandlerTPDI}
/>
</div>
{quotas.map((quota) => (
<div className="u-margin-bottom-small" key={quota.id}>
<p className="text u-margin-bottom-tiny">
<span>{quota.datasetId.replace('_', ' ')}</span>
</p>
<div style={{ marginLeft: '0.5rem' }}>
<p className="text">
<span>Quota Remaining: </span>
{(quota.quotaSqkm - quota.quotaUsed).toPrecision(3)} sqKm
</p>
<p className="text">
<span>Total: </span>
{quota.quotaSqkm.toPrecision(3)} sqKm
</p>
<p className="text">
<span>Quota used: </span>
{quota.quotaUsed.toPrecision(3)} sqKm
</p>
</div>
</div>
))}
</div>
</div>
);
};
const mapStateToProps = (state) => ({
token: state.auth.user.access_token,
});
export default connect(mapStateToProps)(QuotaContainer);
<file_sep>/src/components/forms/CatalogRequestForm.js
import React, { useState } from 'react';
import CatalogCollectionSelection from '../catalog/CatalogCollectionSelection';
import CatalogQueryOptions from '../catalog/CatalogQueryOptions';
import MapContainer from '../input/MapContainer';
import CatalogRequestPreview from '../catalog/CatalogRequestPreview';
import CatalogTimeRange from '../catalog/CatalogTimeRange';
import CatalogSendRequest from '../catalog/CatalogSendRequest';
import CatalogResults from '../catalog/CatalogResults';
// import CatalogDistinctSelection from '../catalog/CatalogDistinctSelection';
import CatalogFields from '../catalog/CatalogFields';
const CatalogRequestForm = () => {
// type is needed to render the results.
const [results, setResults] = useState({
type: '',
results: [],
});
return (
<div>
<div className="catalog-first-row">
<div className="catalog-first-row-first-item">
<CatalogCollectionSelection />
<CatalogQueryOptions />
</div>
<div className="catalog-first-row-second-item">
<CatalogTimeRange />
{/* <CatalogDistinctSelection /> */}
</div>
<div className="catalog-first-row-third-item">
<MapContainer />
</div>
</div>
<div className="catalog-second-row">
<div className="catalog-second-row-first-item">
<CatalogFields />
<CatalogSendRequest setResults={setResults} />
</div>
<div className="catalog-second-row-second-item">
<CatalogRequestPreview />
</div>
<div className="catalog-second-row-third-item">
<CatalogResults results={results} />
</div>
</div>
</div>
);
};
export default CatalogRequestForm;
<file_sep>/src/components/batch/StartBatchRequestButton.js
import React from 'react';
import RequestButton from '../RequestButton';
import { addAlertOnError, batchIdValidation } from './BatchActions';
import { startBatchRequest } from '../../utils/batchActions';
import { connect } from 'react-redux';
import store, { batchSlice } from '../../store';
const StartBatchRequestButton = ({ selectedBatchId, token }) => {
const startResponseHandler = () => {
store.dispatch(
batchSlice.actions.setExtraInfo('Successfully Started request with Id: ' + selectedBatchId),
);
};
return (
<div>
<RequestButton
validation={batchIdValidation(token, selectedBatchId)}
disabledTitle="Log in and set a batch request to use this"
className="secondary-button"
buttonText="Start"
responseHandler={startResponseHandler}
errorHandler={addAlertOnError}
request={startBatchRequest}
args={[token, selectedBatchId]}
/>
</div>
);
};
const mapStateToProps = (state) => ({
selectedBatchId: state.batch.selectedBatchId,
token: state.auth.user.access_token,
});
export default connect(mapStateToProps)(StartBatchRequestButton);
<file_sep>/.env.example
REACT_APP_CLIENTID=
REACT_APP_AUTH_BASEURL=
REACT_APP_ROOT_URL=<file_sep>/src/components/catalog/CatalogDistinctSelection.js
import React from 'react';
import { connect } from 'react-redux';
import store, { catalogSlice } from '../../store';
import { S1GRD_CATALOG_ID, S2L1C_CATALOG_ID, S2L2A_CATALOG_ID } from './const';
import { hasProperties } from './CatalogQueryOptions';
const BaseDistinctOptions = () => {
return <option value="date">Date</option>;
};
const S1DistinctOptions = () => {
return (
<>
<BaseDistinctOptions />
<option value="sar:instrument_mode">Instrument Mode</option>
<option value="sat:orbit_state">Orbit State</option>
<option value="polarization">Polarization</option>
</>
);
};
const generateDistinctOptions = (collectionId) => {
switch (collectionId) {
case S2L2A_CATALOG_ID:
case S2L1C_CATALOG_ID:
return <BaseDistinctOptions />;
case S1GRD_CATALOG_ID:
return <S1DistinctOptions />;
default:
return null;
}
};
const CatalogDistinctSelection = ({ distinct, selectedCollection }) => {
const handleDistinctChange = (e) => {
store.dispatch(catalogSlice.actions.setDistinct(e.target.value));
};
return (
<>
{hasProperties(selectedCollection) ? (
<>
<h2 className="heading-secondary u-margin-top-small">Distinct</h2>
<div className="form">
<select value={distinct} onChange={handleDistinctChange} className="form__input">
<option value="">Non Distinct</option>
{generateDistinctOptions(selectedCollection)}
</select>
</div>
</>
) : null}
</>
);
};
const mapStateToProps = (state) => ({
distinct: state.catalog.distinct,
selectedCollection: state.catalog.selectedCollection,
});
export default connect(mapStateToProps)(CatalogDistinctSelection);
<file_sep>/src/components/batch/GetLowResPreviewButton.js
import React from 'react';
import CancelablePopUpRequestButton from '../CancelablePopUpRequestButton';
import { connect } from 'react-redux';
import { createLowResPreviewRequest } from '../../utils/batchActions';
import { validateRequestState } from '../../utils/validator';
const GetLowResPreviewButton = ({ requestState, token }) => {
const isValid = validateRequestState(requestState);
return (
<div>
<CancelablePopUpRequestButton
className="secondary-button"
validation={Boolean(isValid && token)}
buttonText={'Get Low Res Preview'}
request={createLowResPreviewRequest}
args={[requestState, token]}
requestState={requestState}
useShortcut={true}
/>
</div>
);
};
const mapStateToProps = (state) => ({
requestState: state.request,
token: state.auth.user.access_token,
});
export default connect(mapStateToProps)(GetLowResPreviewButton);
<file_sep>/src/components/output/RequestPreview.js
import React, { useState, useEffect } from 'react';
import { generateProcessCurlCommand, getJSONRequestBody } from '../../utils/generateRequest';
import { connect } from 'react-redux';
import debounceRender from 'react-debounce-render';
import { dispatchChanges, getRequestBody, getEvalscript } from '../../utils/parseRequest';
import store, { requestSlice } from '../../store';
import { getSHJSCode } from '../../utils/generateShjsRequest';
import { getSHPYCode } from '../../utils/generateShPyRequest';
import { Controlled as CodeMirror } from 'react-codemirror2';
require('codemirror/lib/codemirror.css');
require('codemirror/theme/eclipse.css');
require('codemirror/theme/neat.css');
require('codemirror/mode/xml/xml.js');
require('codemirror/mode/javascript/javascript.js');
require('codemirror/mode/powershell/powershell.js');
require('codemirror/mode/python/python.js');
require('codemirror/addon/edit/matchbrackets.js');
const generateRequestByMode = (mode, requestState, token) => {
switch (mode) {
case 'CURL':
return generateProcessCurlCommand(requestState, token);
case 'BODY':
return getJSONRequestBody(requestState);
case 'SHJS':
return getSHJSCode(requestState, token);
case 'SHPY':
return getSHPYCode(requestState);
default:
return generateProcessCurlCommand(requestState, token);
}
};
const getCodeMirrorMode = (mode) => {
switch (mode) {
case 'CURL':
return 'powershell';
case 'SHPY':
return 'python';
case 'SHJS':
return 'javascript';
default:
return 'javascript';
}
};
const RequestPreview = ({ requestState, token }) => {
const [text, setText] = useState();
const [codeMode, setCodeMode] = useState('CURL');
useEffect(() => {
//set textarea based on state
setText(generateRequestByMode(codeMode, requestState, token));
}, [requestState, token, codeMode]);
const handleTextChange = (value) => {
setText(value);
};
const handleCopy = () => {
if (codeMode === 'CURL') {
navigator.clipboard.writeText(text.replace(/(\r\n|\n|\r)/gm, ''));
} else {
navigator.clipboard.writeText(text);
}
};
const handleParseRequest = () => {
try {
// Form data
if (text.includes('-F')) {
const splitted = text.split('-F');
const request = splitted.find((el) => el.includes('request='));
const evalscript = splitted.find((el) => el.includes('evalscript='));
if (request) {
const requestBody = getRequestBody(request);
dispatchChanges(JSON.parse(requestBody));
}
if (evalscript) {
const evalBody = getEvalscript(evalscript);
store.dispatch(requestSlice.actions.setEvalscript(evalBody));
}
} else {
const body = getRequestBody(text);
const parsed = JSON.parse(body);
dispatchChanges(parsed);
}
} catch (err) {}
};
return (
<>
<h2 className="heading-secondary" style={{ marginBottom: '1.3rem' }}>
Request Preview
</h2>
<div className="form">
<div className="request-preview-buttons">
<button className="secondary-button" onClick={handleCopy}>
Copy
</button>
<select value={codeMode} className="form__input" onChange={(e) => setCodeMode(e.target.value)}>
<option value="CURL">curl</option>
<option value="BODY">body</option>
<option value="SHJS">sh-js</option>
<option value="SHPY">sh-py</option>
</select>
{codeMode === 'CURL' || codeMode === 'BODY' ? (
<button onClick={handleParseRequest} style={{ marginLeft: '1rem' }} className="secondary-button">
Parse request
</button>
) : null}
</div>
<CodeMirror
value={text}
options={{
mode: getCodeMirrorMode(codeMode),
theme: 'eclipse',
matchBrackets: true,
}}
onBeforeChange={(editor, data, value) => handleTextChange(value)}
className="process-editor"
/>
</div>
</>
);
};
const mapStateToProps = (store) => ({
requestState: store.request,
token: store.auth.user.access_token,
});
const debouncedComponent = debounceRender(RequestPreview, 1000);
export default connect(mapStateToProps, null)(debouncedComponent);
<file_sep>/src/components/catalog/CatalogQueryOptions.js
import React from 'react';
import { connect } from 'react-redux';
import CatalogSentinel1Options from './CatalogSentinel1Options';
import store, { catalogSlice } from '../../store';
import CatalogSentinel2Options from './CatalogSentinel2Options';
import { S2L2A_CATALOG_ID, S2L1C_CATALOG_ID, S1GRD_CATALOG_ID, S1OPTIONS } from './const';
const generateOptionsByCollectionId = (collectionId, idx) => {
switch (collectionId) {
case S2L2A_CATALOG_ID:
case S2L1C_CATALOG_ID:
return <CatalogSentinel2Options idx={idx} />;
case S1GRD_CATALOG_ID:
return <CatalogSentinel1Options idx={idx} />;
default:
return null;
}
};
const areQueriesLeft = (selectedCollection, selectedQueriesLength) => {
if (selectedCollection === S1GRD_CATALOG_ID && selectedQueriesLength < S1OPTIONS.length) {
return true;
} else if (
(selectedCollection === S2L1C_CATALOG_ID || selectedCollection === S2L2A_CATALOG_ID) &&
selectedQueriesLength < 1
) {
return true;
}
return false;
};
export const hasProperties = (collectionId) =>
collectionId === S2L2A_CATALOG_ID || collectionId === S2L1C_CATALOG_ID || collectionId === S1GRD_CATALOG_ID;
const CatalogQueryOptions = ({ selectedCollection, queryProperties }) => {
const generateQueryOptions = () => {
return queryProperties.map((property, idx) => (
<div key={'property' + idx} className="u-margin-bottom-small">
<label className="form__label">Property</label>
{generateOptionsByCollectionId(selectedCollection, idx)}
<button
onClick={handleRemoveProperty}
name={idx}
className="secondary-button secondary-button--cancel secondary-button--fit"
>
Remove Property
</button>
</div>
));
};
const handleAddQueryProperty = () => {
store.dispatch(catalogSlice.actions.addQueryProperty());
};
const handleRemoveProperty = (e) => {
store.dispatch(catalogSlice.actions.removeQueryProperty(parseInt(e.target.name)));
};
return (
<>
{hasProperties(selectedCollection) ? (
<>
<h2 className="heading-secondary u-margin-top-small">Query Options</h2>
<div className="form" style={{ maxHeight: '301px', overflowY: 'scroll' }}>
{generateQueryOptions()}
{areQueriesLeft(selectedCollection, queryProperties.length) ? (
<button onClick={handleAddQueryProperty} className="secondary-button secondary-button--fit">
Add Query
</button>
) : null}
</div>
</>
) : null}
</>
);
};
const mapStateToProps = (state) => ({
selectedCollection: state.catalog.selectedCollection,
queryProperties: state.catalog.queryProperties,
});
export default connect(mapStateToProps)(CatalogQueryOptions);
<file_sep>/src/components/wms/SendWmsRequest.js
import React from 'react';
import { connect } from 'react-redux';
import { getMapWms, getFisStats } from './wmsRequests';
import RequestButton from '../RequestButton';
import store, { responsesSlice } from '../../store';
const SendWmsRequest = ({ wmsState, requestState, token, mode }) => {
const validateWmsSendRequest = () => {
return Boolean(token && wmsState.instanceId && wmsState.layerId);
};
const responseHandler = (response) => {
const responseUrl = URL.createObjectURL(response);
store.dispatch(
responsesSlice.actions.setResponse({
src: responseUrl,
}),
);
};
const responseHandlerFis = (response) => {
const s = JSON.stringify(response, null, 2);
store.dispatch(responsesSlice.actions.setFisResponse(s));
store.dispatch(responsesSlice.actions.setShow(true));
};
const errorHandler = (err) => {
store.dispatch(responsesSlice.actions.setError('Something went wrong'));
store.dispatch(responsesSlice.actions.setShow(true));
console.error('Something went wrong', err);
};
return (
<div>
<RequestButton
buttonText="Send Request"
className="button"
request={mode === 'WMS' ? getMapWms : getFisStats}
args={[wmsState, requestState, token]}
validation={validateWmsSendRequest()}
responseHandler={mode === 'WMS' ? responseHandler : responseHandlerFis}
errorHandler={errorHandler}
useShortcut={true}
/>
</div>
);
};
const mapStateToProps = (state) => ({
wmsState: state.wms,
requestState: state.request,
token: state.auth.user.access_token,
mode: state.wms.mode,
});
export default connect(mapStateToProps)(SendWmsRequest);
<file_sep>/src/components/tpdi/OrderInfo.js
import React, { useState } from 'react';
import store, { tpdiSlice, requestSlice } from '../../store';
import RequestButton from '../RequestButton';
import { deleteTPDIOrder, confirmTPDIOrder, getAllDeliveries } from './generateTPDIRequests';
import { getTransformedGeometryFromBounds } from '../../utils/crsTransform';
import { focusMap } from '../input/MapContainer';
const OrderInfo = ({ token, order, handleDeleteOrder, handleUpdateOrder }) => {
const [expandOrder, setExpandOrder] = useState(false);
const [deliveries, setDeliveries] = useState([]);
const handleSeeGeometry = () => {
const transformedGeo = getTransformedGeometryFromBounds(order.input.bounds);
store.dispatch(tpdiSlice.actions.setExtraMapGeometry(transformedGeo));
focusMap();
};
const handleSetGeometry = () => {
const transformedGeo = getTransformedGeometryFromBounds(order.input.bounds);
store.dispatch(requestSlice.actions.setGeometry(transformedGeo));
focusMap();
};
const handleConfirm = (response) => {
handleUpdateOrder(response);
};
const handleDeleteClick = async () => {
try {
const res = await deleteTPDIOrder(token, order.id);
if (res.status === 204) {
handleDeleteOrder(order.id);
}
} catch (err) {
console.error('Cannot delete order', err);
}
};
const handleGetDeliveries = (response) => {
setDeliveries(response.data);
};
return (
<div className="order-info">
<label onClick={() => setExpandOrder(!expandOrder)} className="form__label">
{order.id} - {order.name ? order.name + ' -' : null}{' '}
{order.created ? order.created.replace('T', ' ').slice(0, -8) : null} -{' '}
{expandOrder ? String.fromCharCode(0x25b2) : String.fromCharCode(0x25bc)}
</label>
{expandOrder ? (
<div className="u-margin-bottom-small">
{order.name ? (
<p className="text">
<span>Name: </span>
{order.name}
</p>
) : null}
<p className="text">
<span>Provider: </span>
{order.provider}
</p>
<p className="text">
<span>Status: </span>
{order.status}
</p>
<p className="text">
<span>SqKm: </span>
{order.sqkm}
</p>
{order.collectionId ? (
<p className="text">
<span>Collection Id: </span>
{order.collectionId}
</p>
) : null}
<p className="text">
<span>Created at: </span>
{order.created}
</p>
{deliveries.length > 0 ? (
<>
<p className="text">
<span>Deliveries: </span>
{deliveries.map((del, idx) => {
if (idx === deliveries.length - 1) {
return del.status;
}
return del.status + ', ';
})}
</p>
</>
) : null}
<button className="secondary-button" onClick={handleSeeGeometry}>
See on map
</button>
<button className="secondary-button" onClick={handleSetGeometry}>
Set geometry on map
</button>
{order.status !== 'DONE' && order.status !== 'RUNNING' ? (
<RequestButton
request={confirmTPDIOrder}
args={[token, order.id]}
buttonText="Confirm Order"
className="secondary-button"
validation={Boolean(token)}
responseHandler={handleConfirm}
/>
) : null}
<button className="secondary-button secondary-button--cancel" onClick={handleDeleteClick}>
Delete Order
</button>
<RequestButton
request={getAllDeliveries}
args={[token, order.id]}
buttonText="Get deliveries"
validation={Boolean(token)}
className="secondary-button"
responseHandler={handleGetDeliveries}
/>
</div>
) : null}
</div>
);
};
export default OrderInfo;
<file_sep>/Dockerfile
from node:14.8.0-alpine as builder
WORKDIR /app
COPY package*.json /app/
RUN npm install
COPY ./ /app
RUN npm run build
FROM nginx:1.19.2-alpine
COPY --from=builder /app/build /usr/share/nginx/html
<file_sep>/src/components/ModeSelector.js
import React from 'react';
import { connect } from 'react-redux';
import store, { requestSlice } from '../store';
const ModeSelector = ({ mode }) => {
const handleModeChange = (e) => {
store.dispatch(requestSlice.actions.setMode(e.target.value));
};
return (
<div>
<h2 className="heading-secondary u-margin-bottom-small">Mode</h2>
<div className="mode-selector">
<input
className="mode-selector mode-selector--input"
checked={mode === 'PROCESS'}
onChange={handleModeChange}
type="radio"
id="process"
value="PROCESS"
/>
<label className="mode-selector mode-selector--label" htmlFor="process">
PROCESS
</label>
<input
className="mode-selector mode-selector--input"
checked={mode === 'BATCH'}
onChange={handleModeChange}
type="radio"
id="batch"
value="BATCH"
/>
<label className="mode-selector mode-selector--label" htmlFor="batch">
BATCH
</label>
<input
className="mode-selector mode-selector--input"
checked={mode === 'TPDI'}
onChange={handleModeChange}
type="radio"
id="tpdi"
value="TPDI"
/>
<label className="mode-selector mode-selector--label" htmlFor="tpdi">
3RD PARTY DATA
</label>
<input
className="mode-selector mode-selector--input"
checked={mode === 'CATALOG'}
onChange={handleModeChange}
type="radio"
id="catalog"
value="CATALOG"
/>
<label className="mode-selector mode-selector--label" htmlFor="catalog">
CATALOG
</label>
<input
className="mode-selector mode-selector--input"
checked={mode === 'WMS'}
onChange={handleModeChange}
type="radio"
id="wms"
value="WMS"
/>
<label className="mode-selector mode-selector--label" htmlFor="wms">
OGC
</label>
</div>
</div>
);
};
const mapStateToProps = (store) => ({
mode: store.request.mode,
});
export default connect(mapStateToProps)(ModeSelector);
<file_sep>/src/components/tpdi/AirbusFeatureInfo.js
import React, { useState } from 'react';
import store, { tpdiSlice } from '../../store';
import { focusMap } from '../input/MapContainer';
const AirbusFeatureInfo = ({ feature }) => {
const [expandedInfo, setExpandedInfo] = useState(false);
const handleParseGeometryToMap = () => {
store.dispatch(tpdiSlice.actions.setExtraMapGeometry(feature.geometry));
focusMap();
};
const handleAddToOrder = () => {
store.dispatch(tpdiSlice.actions.addProduct(feature.properties.id));
};
return (
<div className="tpdi-feature">
<div className="tpdi-feature-title">
<label onClick={() => setExpandedInfo(!expandedInfo)} className="form__label">
{feature.properties.id} {expandedInfo ? String.fromCharCode(0x25b2) : String.fromCharCode(0x25bc)}
</label>
<button className="secondary-button" onClick={handleParseGeometryToMap}>
See on Map
</button>
</div>
{expandedInfo ? (
<div className="tpdi-feature-extra-info u-margin-bottom-tiny">
<p className="text">
<span>Acquisition Date: </span>
{feature.properties.acquisitionDate}
</p>
<p className="text">
<span>Cloud Cover: </span>
{feature.properties.cloudCover}
</p>
<p className="text">
<span>Snow Cover: </span>
{feature.properties.snowCover}
</p>
<p className="text">
<span>Constellation: </span>
{feature.properties.constellation}
</p>
<p className="text">
<span>Resolution: </span>
{feature.properties.resolution}
</p>
<p className="text">
<span>Incidence Angle: </span>
{feature.properties.incidenceAngle.toFixed(3)}
</p>
<p className="text">
<span>Processing Level: </span>
{feature.properties.processingLevel}
</p>
<button className="secondary-button" onClick={handleAddToOrder}>
Add to orders
</button>
</div>
) : null}
</div>
);
};
export default AirbusFeatureInfo;
| 1c64bc86ac82583badb5ebe08a02a09c204eee09 | [
"JavaScript",
"Dockerfile",
"Shell"
] | 69 | JavaScript | totycro/requests-builder | a67d312f613f6c36ee36e358d11dbfc794bb6f6d | fbe7b31771443e0fe22a1805c49bfa82b762af65 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ShoppingCart.Application.Interfaces;
using ShoppingCart.Application.ViewModels;
using static System.Net.WebRequestMethods;
namespace WebApplication1.Controllers
{
public class ProductsController : Controller
{
private readonly IProductsService productsService;
private readonly IWebHostEnvironment _host;
public readonly IProductsService _prodService;
public ProductsController(IProductsService prodService)
{
_prodService = prodService;
}
public IActionResult Index()
{
var list = _prodService.GetProducts();
return View(list);
}
public IActionResult Create()
{ return View(); }
[HttpPost]
public IActionResult Create(IFormFile file, ProductViewModel data )
{
data.Description = HtmlEncoder.Default.Encode(data.Description);
if (ModelState.IsValid)
{
string uniqueFilename;
if (System.IO.Path.GetExtension(file.FileName) == ".jpg")
{
//FF D8 >>>>>> 255 216
byte[] whitelist = new byte[] { 255, 216 };
if (file != null)
{
using (var f = file.OpenReadStream())
{
/*int byte1 = f.ReadByte();
int byte2 = f.ReadByte();
*/
byte[] buffer = new byte[2]; //How to read an x amount of bytes at 1 go
f.Read(buffer, 0, 2);//offset - how many bytes you like the pointer to skip
for (int i = 0; i < whitelist.Length; i++)
{
if (whitelist[i] == buffer[i])
{
}
else
{
//this file is not acceptable
ModelState.AddModelError("file", "File is not valid and acceptable");
return View();
}
}
//...other reading of bytes happening
f.Position = 0;
//uploading the file
//correctness
uniqueFilename = Guid.NewGuid() + Path.GetExtension(file.FileName);
data.ImageUrl = uniqueFilename;
string absolutePath = _host.WebRootPath + @"\pictures\" + uniqueFilename;
using (FileStream fsOut = new FileStream(absolutePath, FileMode.CreateNew, FileAccess.Write))
{
f.CopyTo(fsOut);
}
f.Close();
}
}
}
if (data.Category.Id > 1 && data.Category.Id < 4)
{
ModelState.AddModelError("Category.Id", "Category is not valid");
return View(data);
}
//once the product has been inserted successfully in the db
_prodService.AddProduct(data);
TempData["message"] = "product inserted successfully";
return View();
}
else
{
return View(data);
}
}
}
}
| 6fc47b8598d1eeaa0fa8c4425af84135fd69131b | [
"C#"
] | 1 | C# | Neil-Mayo/SecuringApplications | 68c4331de21d9a4e872cf4534e3191177dc7c4c0 | e4fa286f3913bfd84fa0d5b42ef2a6f5d87705f5 |
refs/heads/master | <file_sep>from django.shortcuts import render,get_object_or_404
from .models import Post
from .models import Comment,Profile
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from .forms import EmailPostForm,CommentForm,SearchForm
from django.core.mail import send_mail
from taggit.models import Tag
from django.db.models import Count
from django.contrib.postgres.search import SearchVector
from django.contrib.auth.decorators import login_required
from .forms import UserRegistrationForm
from django.shortcuts import redirect
from django.utils import timezone
from django.urls import reverse
def register(request):
if request.method=='POST':
user_form=UserRegistrationForm(request.POST)
if user_form.is_valid():
new_user=user_form.save(commit=False)
new_user.set_password(user_form.cleaned_data['password'])
new_user.save()
# Create the user profile
return render(request,'registration/register_done.html',{'new_user':new_user})
else:
user_form=UserRegistrationForm()
return render(request,'registration/register.html',{'user_form':user_form})
@login_required
def post_list(request,tag_slug=None):
object_list = Post.published.all()
tag = None
if tag_slug:
tag=get_object_or_404(Tag,slug=tag_slug)
object_list=object_list.filter(tags__in=[tag])
paginator = Paginator(object_list, 3)
page = request.GET.get('page')
try:
posts=paginator.page(page)
except PageNotAnInteger:
posts=paginator.page(1)
except EmptyPage:
posts=paginator.page(paginator.num_pages)
return render(request,'blog/post/list.html',
{'page': page, 'posts': posts,'tag':tag})
@login_required
def post_detail(request, pk):
post = get_object_or_404(Post,pk=pk, status='published')
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment=comment_form.save(commit=False)
new_comment.post=post
new_comment.save()
else:
comment_form=CommentForm()
post_tags_ids=post.tags.values_list('id', flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
similar_posts=similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4]
return render(request,'blog/post/detail.html',{'post': post,
'comments':comments,
'new_comment':new_comment,
'comment_form':comment_form,
'similar_posts':similar_posts})
@login_required
def post_share(request,post_id):
post = get_object_or_404(Post, id=post_id, status='published')
sent = False
if request.method == 'POST':
form = EmailPostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
post_url = request.build_absolute_uri(post.get_absolute_url())
subject = '{} ({}) recommends you reading "{}"'.format(cd['name'],cd['email'],post.title)
message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])
send_mail(subject, message, '<EMAIL>', [cd['to']])
sent=True
else:
form = EmailPostForm()
return render(request, "blog/post/share.html",context={'post':post, 'form':form, 'sent': sent,})
@login_required
def post_search(request):
form = SearchForm()
query = None
results = []
if 'query' in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
results = Post.objects.annotate(
search=SearchVector('title', 'body'),).filter(search=query)
return render(request,'blog/post/search.html',{'form': form,'query': query,'results': results})
<file_sep>from django.contrib import admin
from .models import About
from .models import Profile1
admin.site.register(About)
admin.site.register(Profile1)
<file_sep>from django.urls import path
from . import views
from .feeds import LatestPostsFeed
app_name = 'blog'
urlpatterns = [
path('', views.post_list,name='post_list'),
path('<int:pk>/',views.post_detail,name='post_detail'),
path('<int:post_id>/share/', views.post_share, name='post_share'),
path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'),
path('feed/',LatestPostsFeed(), name='post_feed'),
path('search/', views.post_search, name='post_search'),
path('register/', views.register, name='register'),
]
<file_sep>from django.shortcuts import render
from .models import Profile1,About
from blog.models import Post
from django.contrib.auth.decorators import login_required
def about_view(request):
about=About.objects.all()
return render(request,'person/about.html',{'about':about})
@login_required
def profile_view(request):
profile=Profile1.objects.all()
num_post=Post.published.filter(author=request.user).count()
context = {
'profile': profile,
'num_post':num_post,
}
return render(request, "person/profile.html", context)
<file_sep>from django import forms
from .models import Comment
from django.contrib.auth.models import User
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label='Password',widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat Password', widget=forms.PasswordInput)
class Meta:
model=User
fields=('username','first_name','email')
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Passwords don\'t match.')
return cd['password2']
class EmailPostForm(forms.Form):
name = forms.CharField(max_length=25)
email = forms.EmailField()
to = forms.EmailField()
comments = forms.CharField(required=False, widget=forms.Textarea)
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name','comment')
class SearchForm(forms.Form):
query=forms.CharField()
<file_sep>amqp==2.2.1
asgiref==3.2.3
billiard==3.5.0.3
celery==4.1.0
Django==3.0.2
django-crispy-forms==1.8.1
django-taggit==1.1.0
django-tinymce4-lite==1.7.5
importlib-metadata==0.23
jsmin==2.2.2
kombu==4.1.0
Markdown==3.1.1
more-itertools==7.2.0
Pillow==7.0.0
psycopg2==2.8.3
pytz==2017.2
sqlparse==0.3.0
vine==1.1.4
virtualenv==16.7.6
zipp==0.6.0
<file_sep>from django.contrib import admin
from .models import Post
from .models import Comment
from tinymce.widgets import TinyMCE
from django.db import models
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'author', 'publish','status')
list_filter = ('status', 'created', 'publish', 'author')
search_fields =('title', 'body')
prepopulated_fields = {'slug':('title',)}
raw_id_fields = ('author',)
date_hierarchy = 'publish'
ordering = ('status', 'publish')
formfield_overrides = {models.TextField: {'widget': TinyMCE(attrs={'cols': 80, 'rows': 30})},}
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('post','created','active')
list_filter = ('active','created', 'updated')
search_fields = ('body',)<file_sep>{% extends "blog/base.html" %}
{% block title %}Add a blog post{% endblock %}
{% block content %}
<h1>ABOUT</h1>
<br>
{% for b in about %}
<p>{{ b.content }}</p>
{% endfor %}
{% endblock %}
<file_sep>from django.urls import path
from . import views
app_name = 'person'
urlpatterns = [
path('profile/',views.profile_view, name='profile'),
path('about/',views.about_view, name='about'),
]
<file_sep>"""mySite2 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSitemap
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
sitemaps={
'posts':PostSitemap,
}
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('tinymce/', include('tinymce.urls')),
path('person/',include('person.urls', namespace='person')),
path('sitemap.xml',sitemap,{'sitemaps':sitemaps},name='django.contrib.sitemaps.views.sitemap'),
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('password_change/',auth_views.PasswordChangeView.as_view(),name='password_change'),
path('password_change/done/',auth_views.PasswordChangeDoneView.as_view(),name='password_change_done'),
path('password_reset/',
auth_views.PasswordResetView.as_view(),
name='password_reset'),
path('password_reset/done/',
auth_views.PasswordResetDoneView.as_view(),
name='password_reset_done'),
path('reset/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
path('reset/done/',
auth_views.PasswordResetCompleteView.as_view(),
name='password_reset_complete'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)<file_sep># Generated by Django 3.0.2 on 2020-01-20 11:34
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='About',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', models.TextField()),
],
),
migrations.CreateModel(
name='Profile1',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=160)),
('last_name', models.CharField(max_length=160)),
('date_of_birth', models.DateField(blank=True, null=True)),
('email', models.EmailField(max_length=160)),
('phone', models.IntegerField(blank=True)),
('about_me', models.TextField()),
('photo', models.ImageField(blank=True, upload_to='users/%Y/%m/%d/')),
],
),
]
<file_sep>from django.db import models
# Create your models here.
class About(models.Model):
content=models.TextField()
def __str__(self):
return self.content
class Profile1(models.Model):
first_name=models.CharField(max_length=160)
last_name=models.CharField(max_length=160)
date_of_birth = models.DateField(blank=True, null=True)
email=models.EmailField(max_length=160)
phone=models.IntegerField(blank=True)
about_me=models.TextField()
photo = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True)
def __str__(self):
return self.first_name
| 701872a917e42a2258cb0b0469e973f5ffee3518 | [
"Python",
"Text",
"HTML"
] | 12 | Python | Emmanuel-code/mySite | 04b7513369eff8774139ffe192bd8a69361aa738 | 8aa70b090569c1904684bdc728664ce2356cc062 |
refs/heads/master | <file_sep>package poker;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Card {
private String hand;
private int value;
private char suite;
public Card(String hand, int value, char suite) {
super();
this.hand = hand;
this.value = value;
this.suite = suite;
}
public Card(String hand, char suite) {
this.hand = hand;
this.suite = suite;
}
public Card(int value, char suite) {
this.value = value;
this.suite = suite;
}
public Card(int value, String hand) {
this.value = value;
this.hand = hand;
}
public Card() {
// TODO Auto-generated constructor stub
}
public String getHand() {
return hand;
}
public void setHand(String hand) {
this.hand = hand;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public char getSuite() {
return suite;
}
public void setSuite(char suite) {
this.suite = suite;
}
/**
*
* @param userInput
*
*
* This is a method that takes a string from the user, in the
* specified format and generates an array holding 10 'card'
* objects. generated by parsing the string from the user.
*
*
*/
public ArrayList<Card> generateCards(String userInput) {
ArrayList<Card> ret = new ArrayList<Card>(); // The returned arraylist
for (int i = 7; i < userInput.length(); i++) { // start at the 7th character since that is the first card in our
// string
char currentChar = userInput.charAt(i); // grab the current character
char secondChar = userInput.charAt(i + 1); // grab the next character
if (!Character.isDigit(currentChar) && currentChar != 'A' && currentChar != 'J' && currentChar != 'Q'
&& currentChar != 'K') {
i = 29; // if it's not a number, jack, queen or king, then we skip to the next hand
} else if (Character.isDigit(currentChar) && Character.isDigit(secondChar)) {
Card c = new Card(10, userInput.charAt(i + 2)); // if the first two characters are integers it's a 10.
// the only double digit
ret.add(c);
i += 3; // adds 3 to move to the next card index in the string
} else if (Character.isDigit(currentChar)) { // adds cards that are a digit and a suite
Card c = new Card(Character.getNumericValue(currentChar), userInput.charAt(i + 1));
ret.add(c);
i += 2; // adds 2 to move to the next card index in the sting
} else { // If character is not a digit it is either Ace,Jack,Queen,King
if (currentChar == 'A') {
Card c = new Card(14, userInput.charAt(i + 1));
ret.add(c);
i += 2;
} else if (currentChar == 'J') {
Card c = new Card(11, userInput.charAt(i + 1));
ret.add(c);
i += 2;
} else if (currentChar == 'Q') {
Card c = new Card(12, userInput.charAt(i + 1));
ret.add(c);
i += 2;
} else if (currentChar == 'K') {
Card c = new Card(13, userInput.charAt(i + 1));
ret.add(c);
i += 2;
}
}
}
return ret;
}
}
| f596d90f8b81deec176944eff17d13acdaaede34 | [
"Java"
] | 1 | Java | EidAlrabadi/Kata-Poker-Eid-Alrabadi | a87221af5a24a72c54774e1aa09127f55ca7c044 | 5174b0b420b45137edbc0828d822e410b247824d |
refs/heads/master | <repo_name>dasnonap/Cars<file_sep>/src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CitiesModule } from './entities/cities/cities.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Cities } from './entities/cities/cities.entity';
import { ManufacturerModule } from './entities/manufacturer/manufacturer.module';
import { Manufacturer } from './entities/manufacturer/manufacturer.entity';
import { AdvertismentsModule } from './entities/advertisments/advertisments.module';
import { Advertisments } from './entities/advertisments/advertisments.entity';
import { Cars } from './entities/cars/cars.entity';
import { Type_of_car } from './entities/car-type/car-type.entity';
import { EngineType } from './entities/engine-type/engine-type.entity';
import { Models } from './entities/models/models.entity';
import { Transmission_Type } from './entities/trans-type/trans-type.entity';
import { Users } from './entities/users/users.entity';
import { Wheeldrive } from './entities/wheeldrive/wheeldrive.entity';
import { Liked_ads } from './entities/liked-ads/liked-ads.entity';
import { ModelsModule } from './entities/models/models.module';
import { UploadsModule } from './upload/uploads/uploads.module';
import { AccountServiceModule } from './account-service/account-service.module';
import { CarsModule } from './entities/cars/cars.module';
import { QueriesModule } from './queries/queries.module';
import { ImgModule } from './img/img.module';
@Module({
imports: [
CitiesModule,
ManufacturerModule,
AdvertismentsModule,
ModelsModule,
CarsModule,
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: '<PASSWORD>',
database: 'two',
synchronize: true,
keepConnectionAlive: true,
entities: [ Cities, Manufacturer, Advertisments, Cars,
Type_of_car, EngineType, Models, Transmission_Type,
Users, Wheeldrive, Liked_ads ]
}),
UploadsModule,
AccountServiceModule,
QueriesModule,
ImgModule,
],
controllers: [AppController],
providers: [AppService],
}
)
export class AppModule {
}
<file_sep>/src/img/img.module.ts
import { Module } from '@nestjs/common';
import { ImgController } from './img.controller';
@Module({
controllers: [ImgController]
})
export class ImgModule {}
<file_sep>/src/entities/manufacturer/manufacturer.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm";
import { Models } from "../models/models.entity";
@Entity()
export class Manufacturer{
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany( type => Models, model => model.manID)
models: Models[];
}<file_sep>/src/DTO/wheelDrive.model.ts
export class WheelDriveModel{
id: number;
wheelType: string;
constructor(id: number, type: string){
this.id = id;
this.wheelType = type;
}
getID(): number{
return this.id;
}
getWheelType(): string{
return this.wheelType
}
}<file_sep>/src/entities/cities/cities.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cities } from './cities.entity';
import { CitiesModel } from 'src/DTO/cities.model';
import { CitiesModule } from './cities.module';
@Injectable()
export class CitiesService {
constructor(
@InjectRepository(Cities)
private citiesRepo: Repository<Cities>,
){}
async findAll(): Promise<Cities[]>{
return this.citiesRepo.find();
}
async findOne(id: number): Promise<Cities>{
return this.citiesRepo.findOne(id);
}
async findByName(name: string): Promise<Cities>{
return this.citiesRepo.findOne({where: {cityName: name}});
}
insertOne(city: CitiesModel){
const row = new Cities();
row.cityName = city.getCity();//to do
this.citiesRepo.insert(row);
}
updateOne(city: CitiesModel){
const row = new Cities();
row.cityName = city.getCity();
this.citiesRepo.update(city.id, row);
}
deleteOne(city: CitiesModel){
this.citiesRepo.delete(city.id);
}
}
<file_sep>/src/entities/trans-type/trans-type.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Transmission_Type } from './trans-type.entity';
import { TransTypeService } from './trans-type.service';
import { TransTypeController } from './trans-type.controller';
@Module({
imports: [TypeOrmModule.forFeature([Transmission_Type])],
providers: [TransTypeService],
exports: [TypeOrmModule],
controllers: [TransTypeController]
})
export class TransTypeModule {}
<file_sep>/src/entities/users/users.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Users } from './users.entity';
import { Repository } from 'typeorm';
import { UsersModel } from 'src/DTO/users.model';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(Users)
private usersRepo: Repository<Users>
){}
async findAll(): Promise<Users[]>{
return this.usersRepo.find();
}
findOne(em: string): Promise<Users>{
return this.usersRepo.findOne({where: {email: em} });
}
findWithUsername(name: string): Promise<Users>{
return this.usersRepo.findOne({where: {username: name}});
}
findUser(user: UsersModel): Promise<Users>{
return this.usersRepo.findOne({where: {username: user.username, password: user.password}});
}
async insert(user: UsersModel){
const row = new Users();
row.name = user.name;
row.username = user.username;
row.password = <PASSWORD>;
row.email = user.email;
if(await this.exists(user.email) != 0){
return false;
}
this.usersRepo.insert(row);
return true;
}
private exists(em: string){
return this.usersRepo.count({where: {email: em}});
}
}
<file_sep>/src/entities/cities/cities.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm";
import { Advertisments } from "../advertisments/advertisments.entity";
@Entity()
export class Cities{
@PrimaryGeneratedColumn()
id: number;
@Column()
cityName: string;
@OneToMany(type => Advertisments, ad => ad.cityID)
ad: Advertisments[];
}<file_sep>/src/upload/uploads/uploads.module.ts
import { Module } from '@nestjs/common';
import { UploadsController } from './uploads.controller';
import { MulterModule } from '@nestjs/platform-express';
@Module({
imports:[MulterModule.register({
dest: './ads/photos/'
})],
controllers: [UploadsController]
})
export class UploadsModule {}
<file_sep>/src/entities/advertisments/advertisments.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne } from "typeorm";
import { Liked_ads } from "../liked-ads/liked-ads.entity";
import { Users } from "../users/users.entity";
import { Cars } from "../cars/cars.entity";
import { Cities } from "../cities/cities.entity";
@Entity()
export class Advertisments{
@PrimaryGeneratedColumn()
adID: number;
@ManyToOne(type => Cars, car => car.ad)
carID: Cars;
@ManyToOne(type => Cities, city => city.ad)
cityID: Cities;
@ManyToOne(type => Users, user => user.ad)
creatorID: Users;
@Column()
creatorPN: string;
@Column()
price: number;
@Column()
desc: string;
@Column()
photos: string;
@OneToMany(type => Liked_ads, liked => liked.ad)
likedAds: Liked_ads[];
}<file_sep>/src/account-service/account-service.controller.ts
import { Controller, Post, Body, Res, HttpStatus, Get, UseGuards, Req } from '@nestjs/common';
import { UsersModel } from 'src/DTO/users.model';
import { UsersService } from 'src/entities/users/users.service';
import { AccountServiceService } from './account-service.service';
import { JwtAuthGuard } from './jwt-auth.guard';
@Controller('account-service')
export class AccountServiceController {
constructor(
private readonly usersService: UsersService,
private authService: AccountServiceService,
){};
@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@Req() req){
return req.user;
}
@Post('register')
async regUser(@Body()usr: UsersModel, @Res() res){
if( await this.usersService.insert(usr) == false){
return res.status(409).send({error: 'already registered'});
}
return res.status(200).send();
}
@Post('login')
async logUser(@Res() res, @Body()user: UsersModel){
return res.send( await this.authService.login(user));
}
}
<file_sep>/src/entities/advertisments/advertisments.controller.ts
import { Controller, Get, Post, Body, UploadedFiles, UseInterceptors, Res } from '@nestjs/common';
import { AdvertismentsService } from './advertisments.service';
import { AdvertismentsModel } from 'src/DTO/advertisments.model';
import { FilesInterceptor } from '@nestjs/platform-express';
@Controller('advertisments')
export class AdvertismentsController {
constructor(protected readonly adsService: AdvertismentsService){}
@Get()
findAll(){
return this.adsService.findAll();
}
@Get('desc')
async findOne(@Body('id')id: number, @Res() res, @Body('number')number: number){
const row = await this.adsService.findWithID(id);
return res.sendFile(row.adID + '_' + number + '.jpg', {root: row.photos});
}
@Get('ad')
async findAdWithDesc(@Body()ad: AdvertismentsModel, @Res() res ){
const row = await this.adsService.findIDByDesc(ad.desc);
}
@Post()
async insert(@Body()ad: AdvertismentsModel){
return this.adsService.insert(ad);
}
@Post('upload')
@UseInterceptors(
FilesInterceptor('image', 20)
)
async findWithDesc(@Body()ad: AdvertismentsModel, @UploadedFiles() files){
ad.photos = 'F:/ads/ad' + ad.id + '/photos/';
return this.adsService.updateAd(ad, files);
}
}
<file_sep>/src/entities/cars/cars.module.ts
import { Module } from '@nestjs/common';
import { CarsController } from './cars.controller';
import { CarsService } from './cars.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Cars } from './cars.entity';
import { EngineType } from '../engine-type/engine-type.entity';
import { Models } from '../models/models.entity';
import { Transmission_Type } from '../trans-type/trans-type.entity';
import { Type_of_car } from '../car-type/car-type.entity';
import { Wheeldrive } from '../wheeldrive/wheeldrive.entity';
import { Manufacturer } from '../manufacturer/manufacturer.entity';
@Module({
imports: [TypeOrmModule.forFeature([Cars, EngineType, Models, Transmission_Type, Type_of_car, Wheeldrive, Manufacturer])],
controllers: [CarsController],
providers: [CarsService, ]
})
export class CarsModule {
}
<file_sep>/src/entities/cars/cars.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Cars } from './cars.entity';
import { Repository } from 'typeorm';
import { CarsModel } from 'src/DTO/cars.model';
import { EngineType } from '../engine-type/engine-type.entity';
import { Models } from '../models/models.entity';
import { Transmission_Type } from '../trans-type/trans-type.entity';
import { Type_of_car } from '../car-type/car-type.entity';
import { Wheeldrive } from '../wheeldrive/wheeldrive.entity';
import { Manufacturer } from '../manufacturer/manufacturer.entity';
import { SearchModel } from 'src/DTO/search.model';
@Injectable()
export class CarsService {
constructor(
@InjectRepository(Cars)
private carsRepo: Repository<Cars>,
@InjectRepository(EngineType)
private engineRepo: Repository<EngineType>,
@InjectRepository(Models)
private modelsRepo: Repository<Models>,
@InjectRepository(Transmission_Type)
private transRepo: Repository<Transmission_Type>,
@InjectRepository(Type_of_car)
private carTypeRepo: Repository<Type_of_car>,
@InjectRepository(Wheeldrive)
private wheelRepo: Repository<Wheeldrive>,
@InjectRepository(Manufacturer)
private manRepo: Repository<Manufacturer>
){}
async findAll(): Promise<Cars[]>{
return this.carsRepo.find({relations: ['engineID', 'modelID', 'transID', 'carTypeID', 'wheelDriveID']});
}
async findWithModel(search: SearchModel){
return this.carsRepo
.createQueryBuilder("cars")
.leftJoinAndSelect(EngineType, "e", 'e.id = cars.engineID')
.leftJoinAndSelect(Models, "model", 'model.id = cars.modelID')
.leftJoinAndSelect(Transmission_Type, "trans", 'trans.id = cars.transID')
.leftJoinAndSelect(Type_of_car, "carType", 'carType.id = cars.carTypeID')
.leftJoinAndSelect(Wheeldrive, "wheel", 'wheel.id = cars.wheelDriveID')
.getMany();
}
/*
.innerJoinAndSelect("cars.modelID", "model")
.innerJoinAndSelect("cars.transID", "trans")
.innerJoinAndSelect("cars.carTypeID", "carType")
.innerJoinAndSelect("cars.wheelDriveID", "wheel")
.where("engine.type = :type", {type: search.engine})
.orWhere("model.modelName = :name", {name: search.model})
.orWhere("trans.type = :type", {type: search.transmission})
.orWhere("carType.name = :name", {name: search.car_type})
.orWhere("wheel.type = :type", {type: search.wheelDrive})
.getMany();
where("engine.type = :type", {type: search.engine})
.orWhere("model.modelName = :name", {name: search.model})
.orWhere("trans.type = :type", {type: search.transmission})
.orWhere("carType.name = :name", {name: search.car_type})
.orWhere("wheel.type = :type", {type: search.wheelDrive})
*/
async insert(car: CarsModel){
const row = new Cars();
row.doors = car.doorNumber;
row.year = car.yearDev;
row.engineID = await this.engineRepo.findOne({where: {type: car.engineType}});
row.modelID = await this.modelsRepo.findOne({where: {modelName: car.model}});
row.transID = await this.transRepo.findOne({where: {type: car.transType}});
row.carTypeID = await this.carTypeRepo.findOne({where: {name: car.carType}});
row.wheelDriveID = await this.wheelRepo.findOne({where: {type: car.wheelDrive}});
this.carsRepo.insert(row);
}
returnEngines(): Promise<EngineType[]>{
return this.engineRepo.find();
}
returnModels(): Promise<Models[]>{
return this.modelsRepo.find({relations: ['manID']});
}
returnTransm(): Promise<Transmission_Type[]>{
return this.transRepo.find();
}
returnCarType(): Promise<Type_of_car[]>{
return this.carTypeRepo.find();
}
returnWheelDrive(): Promise<Wheeldrive[]>{
return this.wheelRepo.find();
}
returnMan(): Promise<Manufacturer[]>{
return this.manRepo.find();
}
}
<file_sep>/src/DTO/advertisments.model.ts
import { CarsModel } from "./cars.model";
export class AdvertismentsModel{
id: number;
car: CarsModel ;
city: string;
creatorUsername: string;
creatorPN: string;
price: number;
desc: string;
photos: string;
urls: string[] = new Array(0);
/*constructor(id: number, car: number, city: string, creator: string, phone: string, price: number, desc: string){
this.id = id;
this.car = car;
this.city = city;
this.creatorUsername = creator;
this.creatorPN = phone;
this.price = price;
this.desc = desc;
}
getID(): number{
return this.id;
}
getCar(): number{
return this.car;
}
getCity(): string{
return this.city;
}
getCreatorID(): string{
return this.creatorUsername;
}
getCreatorPhone(): string{
return this.creatorPN;
}
getPrice(): number{
return this.price;
}
getDesc(): string{
return this.desc;
}*/
}<file_sep>/src/entities/models/models.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { ModelsService } from './models.service';
import { Models } from './models.entity';
import { ModelsModel } from 'src/DTO/models.model';
@Controller('models')
export class ModelsController {
constructor( protected readonly modelsService: ModelsService){}
@Get()
async findAll(): Promise<Models[]>{
return this.modelsService.findAll();
}
@Post()
insertModel(@Body() model: ModelsModel){
try{
this.modelsService.insertOne(model);
}
catch(err){
return "Already exists";
}
}
}
<file_sep>/src/entities/cities/cities-http.module.ts
import { Module } from '@nestjs/common';
import { CitiesModule } from './cities.module';
import { CitiesService } from './cities.service';
import { CitiesController } from './cities.controller';
@Module({
imports: [CitiesModule],
providers: [CitiesService],
controllers: [CitiesController],
})
export class CitiesHttpModule{
}<file_sep>/src/entities/wheeldrive/wheeldrive.service.ts
import { Injectable, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Wheeldrive } from './wheeldrive.entity';
import { Repository } from 'typeorm';
import { WheelDriveModel } from 'src/DTO/wheelDrive.model';
import { throwError } from 'rxjs';
@Injectable()
export class WheeldriveService {
constructor(
@InjectRepository(Wheeldrive)
private driveRepo: Repository<Wheeldrive>,
){}
async findAll(): Promise<Wheeldrive[]>{
return this.driveRepo.find();
}
async findWithName(name: string): Promise<Wheeldrive>{
return this.driveRepo.findOne({where: {type: name}});
}
async insert(wheel: WheelDriveModel){
const row = new Wheeldrive();
row.type = wheel.wheelType;
if(await this.checkExists(wheel.wheelType) != 0){
throwError(ConflictException);
}
this.driveRepo.insert(row);
}
private checkExists(name: string){
return this.driveRepo.count({where: {type: name}});
}
}
<file_sep>/src/DTO/search.model.ts
export class SearchModel{
manufacturer: string;
model: string;
year_from: number;
year_to: number;
car_type: string;
price_from: number;
price_to: number;
wheelDrive: string;
engine: string;
transmission: string;
doors: number;
city: string;
}<file_sep>/src/entities/liked-ads/liked-ads.entity.ts
import { PrimaryGeneratedColumn, Column, Entity, ManyToMany, ManyToOne } from "typeorm";
import { Advertisments } from "../advertisments/advertisments.entity";
import { Users } from "../users/users.entity";
@Entity()
export class Liked_ads{
@PrimaryGeneratedColumn()
likedID: number;
@ManyToOne(type => Advertisments, ad => ad.likedAds)
ad: Advertisments;
@ManyToOne( type => Users, user => user.lad)
user: Users;
}<file_sep>/src/account-service/local.strategy.ts
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { Strategy } from "passport-local";
import {PassportStrategy} from "@nestjs/passport"
import { AccountServiceService } from "./account-service.service";
import { UsersModel } from "src/DTO/users.model";
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy){
constructor(private accountServ: AccountServiceService){
super();
}
async validate(user: UsersModel): Promise<any>{
const logged = this.accountServ.validateUser(user);
if(!logged){
throw new UnauthorizedException();
}
return logged;
}
}<file_sep>/src/DTO/manufacturer.model.ts
export class ManufacturerModel{
id: number;
man: string;
constructor(id: number, man: string){
this.id = id;
this.man = man;
}
getID(): number{
return this.id;
}
getMan(): string{
return this.man;
}
}<file_sep>/src/entities/trans-type/trans-type.service.ts
import { Injectable, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Transmission_Type } from './trans-type.entity';
import { Repository } from 'typeorm';
import { TransTypeModel } from 'src/DTO/transType.model';
import { throwError } from 'rxjs';
@Injectable()
export class TransTypeService {
constructor(
@InjectRepository(Transmission_Type)
private transRepo: Repository<Transmission_Type>
){}
async findAll(): Promise<Transmission_Type[]>{
return this.transRepo.find();
}
async findOne(typeName: string): Promise<Transmission_Type>{
return this.transRepo.findOne({where: {type: typeName}});
}
async insertOne(type: TransTypeModel){
const row = new Transmission_Type();
row.type = type.transType;
if(await this.checkExists(type.transType) != 0){
throwError(ConflictException);
}
this.transRepo.insert(row);
}
private checkExists(typeName: string){
return this.transRepo.count({where: {type: typeName}});
}
}
<file_sep>/src/entities/engine-type/engine-type.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { EngineTypeService } from './engine-type.service';
import { EngineTypeModel } from 'src/DTO/engineType.model';
@Controller('engine-type')
export class EngineTypeController {
constructor( private engineService: EngineTypeService){}
@Get()
getAll(){
return this.engineService.findAll();
}
@Post()
insertOne(@Body()engine: EngineTypeModel){
try{
this.engineService.insertOne(engine);
}
catch(err){
return "Already exists";
}
}
}
<file_sep>/src/entities/trans-type/trans-type.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { TransTypeService } from './trans-type.service';
import { TransTypeModel } from 'src/DTO/transType.model';
@Controller('trans-type')
export class TransTypeController {
constructor(private trasnService: TransTypeService){}
@Get()
getAll(){
return this.trasnService.findAll();
}
@Post()
insert(@Body()type: TransTypeModel){
try{
this.trasnService.insertOne(type);
}
catch(err){
return 'Already exists';
}
}
}
<file_sep>/src/entities/models/models.service.ts
import { Injectable, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Models } from './models.entity';
import { Repository } from 'typeorm';
import { ModelsModel } from 'src/DTO/models.model';
import { ManufacturerService } from '../manufacturer/manufacturer.service';
@Injectable()
export class ModelsService {
constructor(
@InjectRepository(Models)
private modelsRepo: Repository<Models>,
private manService: ManufacturerService
){}
async findAll(): Promise<Models[]>{
return this.modelsRepo.find({relations: ["manID"]});
}
async findOne(id: number): Promise<Models>{
return this.modelsRepo.findOne(id);
}
async findWithName(name: string){
return this.modelsRepo.findOne({where: {modelName: name}});
}
async insertOne(model: ModelsModel){
const row = new Models();
row.manID = await this.manService.findWithName(model.man);
row.modelName = model.modelName;
if(await this.checkExists(model.modelName) != 0){
throw ConflictException;
}
else{
this.modelsRepo.insert(row);
}
}
private async checkExists(name: string): Promise<number>{
let res = await this.modelsRepo.count({where: {modelName: name}});
return res;
}
}
<file_sep>/src/entities/car-type/car-type.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Type_of_car } from './car-type.entity';
import { CarTypeService } from './car-type.service';
import { CarTypeController } from './car-type.controller';
@Module({
imports: [TypeOrmModule.forFeature([Type_of_car])],
providers: [CarTypeService],
exports: [TypeOrmModule],
controllers: [CarTypeController]
})
export class CarTypeModule {
}
<file_sep>/src/entities/manufacturer/manufacturer.controller.ts
import { Controller, Get, Post, Body, ConflictException } from '@nestjs/common';
import { ManufacturerService } from './manufacturer.service';
import { Manufacturer } from './manufacturer.entity';
import { ManufacturerModel } from 'src/DTO/manufacturer.model';
@Controller('manufacturer')
export class ManufacturerController {
constructor(protected readonly manuService: ManufacturerService){}
@Get()
async findAll(){
return this.manuService.findAll();
}
@Post()
insert(@Body('name') name: string){
try{
this.manuService.insertOne(new ManufacturerModel(0, name));
}
catch(err){
return "Already exists";
}
}
}
<file_sep>/src/entities/advertisments/advertisments.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Advertisments } from './advertisments.entity';
import { Repository, LessThanOrEqual, MoreThanOrEqual, Like } from 'typeorm';
import { AdvertismentsModel } from 'src/DTO/advertisments.model';
import * as fs from 'fs-extra';
import { Users } from '../users/users.entity';
import { Cities } from '../cities/cities.entity';
import { Cars } from '../cars/cars.entity';
import { SearchModel } from 'src/DTO/search.model';
import { CarsModel } from 'src/DTO/cars.model';
import { EngineType } from '../engine-type/engine-type.entity';
import { Models } from '../models/models.entity';
import { Transmission_Type } from '../trans-type/trans-type.entity';
import { Type_of_car } from '../car-type/car-type.entity';
import { Wheeldrive } from '../wheeldrive/wheeldrive.entity';
import { Manufacturer } from '../manufacturer/manufacturer.entity';
@Injectable()
export class AdvertismentsService {
private lastInsertedADID: number = 0;
constructor(
@InjectRepository(Advertisments)
private adsRepo:Repository<Advertisments>,
@InjectRepository(Cars)
private carsRepo: Repository<Cars>,
@InjectRepository(Cities)
private citiesRepo: Repository<Cities>,
@InjectRepository(Users)
private usersRepo:Repository<Users>,
@InjectRepository(EngineType)
private engineRepo: Repository<EngineType>,
@InjectRepository(Models)
private modelsRepo: Repository<Models>,
@InjectRepository(Transmission_Type)
private transRepo: Repository<Transmission_Type>,
@InjectRepository(Type_of_car)
private carTypeRepo: Repository<Type_of_car>,
@InjectRepository(Wheeldrive)
private wheelRepo: Repository<Wheeldrive>,
@InjectRepository(Manufacturer)
private manRepo: Repository<Manufacturer>
){}
async findAll(): Promise<Advertisments[]>{
return this.adsRepo.find({relations: ['carID', 'carID.engineID', 'carID.modelID', 'carID.modelID.manID','carID.transID', 'carID.carTypeID', 'carID.wheelDriveID', 'cityID', 'creatorID'],
});
}
findWithID(id: number): Promise<Advertisments>{
return this.adsRepo.findOne(id);
}
getCities(): Promise<Cities[]>{
return this.citiesRepo.find();
}
async findOne(creatorUsername: string ): Promise<Advertisments[]>{// за търсене на обяви за един човек
return this.adsRepo.find({
where: {
creatorID: {
username: creatorUsername
}
}
});
}
async findWithModel(search: SearchModel){
var array = await this.findAll();
}
async findIDByDesc(descr: string){
const log: Advertisments = await this.adsRepo.findOne({
where: {
desc: descr
}
});
return log;
}
checkExists(descr: string){
return this.adsRepo.count({where: {desc: descr}});
}
async insert(ad: AdvertismentsModel){
const row = new Advertisments();
var newID: number;
const carID = await this.searchCar(ad.car);
if(carID == null){
const newCar = await this.createCar(ad.car);
const car = await this.carsRepo.insert(newCar).then(()=>{
return this.carsRepo.getId(newCar);
});
newID = car;
row.carID = await this.carsRepo.findOne(newID);
}
else{
row.carID = carID;
}
row.cityID = await this.citiesRepo.findOne({where: {cityName: ad.city}});
row.creatorID = await this.usersRepo.findOne({where: {username: ad.creatorUsername}});
row.creatorPN = ad.creatorPN;
row.price = ad.price;
row.desc = ad.desc;
row.photos = "new";
var id = await this.adsRepo.insert(row).then(()=>{
return this.adsRepo.getId(row);
});
ad.id = id;
return ad;
}
insertPhotos(files: any[], id: number){
let counter = 1;
files.forEach(async file =>{
fs.move('./ads/photos/' + file.filename, await this.createFilePath(counter, id))
counter++;
});
}
updateAd(ad: AdvertismentsModel, files: any[]){
const row = new Advertisments();
let urlAd = ad;
urlAd.urls = [];
let counter = 1;
this.adsRepo
.createQueryBuilder()
.update(Advertisments)
.set({photos: ad.photos})
.where('adID = :adID', { adID: ad.id })
.execute();
files.forEach( file =>{
var path = this.createFilePath(counter, ad.id);
fs.move('./ads/photos/' + file.filename, path);
urlAd.urls.push('localhost:3000/img/' + ad.id + '_' + counter + '.jpg');
counter++;
});
this.isCreated = false;
return urlAd;
}
private createFilePath(counter: number, id: number){
this.createDir(id);
return 'F:/ads/ad' + id + '/photos/' + id + '_' + counter + '.jpg';
}
private isCreated: boolean = false;
private createDir(ad: number){
if(this.isCreated == true){
if(!fs.existsSync('F:/ads/ad' + ad +'/photos',)){
this.isCreated = true;
fs.mkdir('F:/ads/ad' + ad, (err)=>{
if(err) throw err;
} );
fs.mkdir('F:/ads/ad' + ad +'/photos', (err)=>{
if(err) throw err;
} );
}
}
}
private async searchCar(car: CarsModel){
const array = await this.carsRepo.find({relations: ['engineID', 'modelID', 'transID', 'carTypeID', 'wheelDriveID']});
return this.searchEngine(car, array)[0];
}
private searchEngine(car: CarsModel, array: Cars[]){
return this.searchModel(car, array.filter(function(value, index, arr){
return value.engineID.type == car.engineType;
}));
}
private searchModel(car: CarsModel, array: Cars[]){
return this.searchTrans(car, array.filter(function(value, index, arr){
return value.modelID.modelName == car.model;
}));
}
private searchTrans(car: CarsModel, array: Cars[]){
return this.searchCarType(car, array.filter(function(value, index, arr){
return value.transID.type == car.transType;
}));
}
private searchCarType(car: CarsModel, array: Cars[]){
return this.searchWheel(car, array.filter(function(value, index, arr){
return value.carTypeID.name == car.carType;
}));
}
private searchWheel(car: CarsModel, array: Cars[]){
return this.searchDoors(car, array.filter(function(value, index, arr){
return value.wheelDriveID.type == car.wheelDrive;
}));
}
private searchDoors(car: CarsModel, array: Cars[]){
return this.searchYear(car, array.filter(function(value, index, arr){
return value.doors == car.doorNumber;
}));
}
private searchYear(car: CarsModel, array: Cars[]){
return array.filter(function(value, index, arr){
return value.year == car.yearDev;
});
}
private async createCar(car: CarsModel){
const row = new Cars();
row.doors = car.doorNumber;
row.year = car.yearDev;
row.engineID = await this.engineRepo.findOne({where: {type: car.engineType}});
if(await this.manRepo.count({where: {name: car.man}}) == 0){
const manu = new Manufacturer();
manu.name = car.man;
this.manRepo.insert(manu);
}
if(await this.modelsRepo.count({where: {modelName: car.model}}) == 0){
const model = new Models();
const manID = await this.manRepo.findOne({where: {name: car.man}});
model.manID = manID;
model.modelName = car.model;
const mod = await this.modelsRepo.insert(model).then(()=>{
return this.modelsRepo.getId(model);
});
var modID: number = mod;
row.modelID = await this.modelsRepo.findOne({where: {id: modID}});
}
row.modelID = await this.modelsRepo.findOne({where: {modelName: car.model}});
row.transID = await this.transRepo.findOne({where: {type: car.transType}});
row.carTypeID = await this.carTypeRepo.findOne({where: {name: car.carType}});
row.wheelDriveID = await this.wheelRepo.findOne({where: {type: car.wheelDrive}});
return row;
}
}
<file_sep>/src/DTO/carType.model.ts
export class CarTypeModel{
id: number;
carType: string;
constructor(id: number, type: string){
this.id = id;
this.carType = type;
}
getID(): number{
return this.id;
}
getCarType(): string{
return this.carType;
}
}<file_sep>/src/entities/wheeldrive/wheeldrive.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Wheeldrive } from './wheeldrive.entity';
import { WheeldriveService } from './wheeldrive.service';
import { WheeldriveController } from './wheeldrive.controller';
@Module({
imports: [TypeOrmModule.forFeature([Wheeldrive])],
providers: [WheeldriveService],
exports: [TypeOrmModule],
controllers: [WheeldriveController]
})
export class WheeldriveModule {}
<file_sep>/src/DTO/transType.model.ts
export class TransTypeModel{
id: number;
transType: string;
constructor(id: number, type :string){
this.id = id;
this.transType = type;
}
getID(): number{
return this.id;
}
getTransType(): string{
return this.transType;
}
}<file_sep>/src/account-service/account-service.module.ts
import { Module } from '@nestjs/common';
import { AccountServiceController } from './account-service.controller';
import { AccountServiceService } from './account-service.service';
import { UsersModule } from 'src/entities/users/users.module';
import { UsersService } from 'src/entities/users/users.service';
import { PassportModule } from '@nestjs/passport';
import { LocalStrategy } from './local.strategy';
import { JwtService, JwtModule } from '@nestjs/jwt';
import { jwtConstants } from './constants';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports:[
UsersModule,
PassportModule,
JwtModule.register({
secret: jwtConstants.secret,
signOptions: {expiresIn: '60s'},
}),
],
controllers: [AccountServiceController],
providers: [AccountServiceService, UsersService, LocalStrategy, JwtStrategy],
exports: [AccountServiceService]
})
export class AccountServiceModule {}
<file_sep>/src/entities/wheeldrive/wheeldrive.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { WheeldriveService } from './wheeldrive.service';
import { WheelDriveModel } from 'src/DTO/wheelDrive.model';
@Controller('wheeldrive')
export class WheeldriveController {
constructor(private wheelService: WheeldriveService){}
@Get()
getAll(){
return this.wheelService.findAll();
}
@Post()
insertOne(@Body() wheel: WheelDriveModel){
try{
this.wheelService.insert(wheel);
}
catch(err){
return 'Already exists';
}
}
}
<file_sep>/src/DTO/users.model.ts
export class UsersModel{
id: number;
username: string;
password: string;
email: string;
name: string;
constructor(id: number, username: string, pass: string, email: string, name: string){
this.id = id;
this.username = username;
this.password = <PASSWORD>;
this.email = email;
this.name = name;
}
getID(): number{
return this.id;
}
getUsername(): string{
return this.username;
}
getPassword(): string{
return <PASSWORD>;
}
getEmail(): string{
return this.email;
}
getName(): string{
return this.name;
}
}<file_sep>/src/entities/models/models.entity.ts
import { PrimaryGeneratedColumn, Column, OneToMany, Entity, ManyToOne } from "typeorm";
import { Cars } from "../cars/cars.entity";
import { Manufacturer } from "../manufacturer/manufacturer.entity";
@Entity()
export class Models{
@PrimaryGeneratedColumn()
id: number;
@Column()
modelName: string;
@ManyToOne(type => Manufacturer, man => man.models)
manID: Manufacturer;
@OneToMany( type => Cars, car => car.modelID)
cars: Cars[];
}<file_sep>/src/entities/car-type/car-type.controller.ts
import { Controller, Get, Body, Post, Req } from '@nestjs/common';
import { CarTypeService } from './car-type.service';
import { CarTypeModel } from 'src/DTO/carType.model';
@Controller('car-type')
export class CarTypeController {
constructor(private typeService: CarTypeService){}
@Get()
getAll(){
return this.typeService.findAll();
}
@Post()
insertOne( @Body() type: CarTypeModel){
try{
this.typeService.insertOne(type);
}
catch(err){
return 'Already exixts';
}
}
}
<file_sep>/src/entities/liked-ads/liked-ads.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Liked_ads } from './liked-ads.entity';
@Module({
imports: [TypeOrmModule.forFeature([Liked_ads])],
exports: [TypeOrmModule]
})
export class LikedAdsModule {}
<file_sep>/src/entities/advertisments/advertisments.module.ts
import { Module } from '@nestjs/common';
import { AdvertismentsService } from './advertisments.service';
import { AdvertismentsController } from './advertisments.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Advertisments } from './advertisments.entity';
import { Cars } from '../cars/cars.entity';
import { MulterModule } from '@nestjs/platform-express';
import { Users } from '../users/users.entity';
import { Cities } from '../cities/cities.entity';
import { EngineType } from '../engine-type/engine-type.entity';
import { Models } from '../models/models.entity';
import { Transmission_Type } from '../trans-type/trans-type.entity';
import { Type_of_car } from '../car-type/car-type.entity';
import { Wheeldrive } from '../wheeldrive/wheeldrive.entity';
import { Manufacturer } from '../manufacturer/manufacturer.entity';
@Module({
imports: [TypeOrmModule.forFeature([Advertisments, Cars, Users, Cities, EngineType, Models, Transmission_Type, Type_of_car, Wheeldrive, Manufacturer]),
MulterModule.register({
dest: './ads/photos/'
})],
providers: [AdvertismentsService, ],
controllers: [AdvertismentsController],
})
export class AdvertismentsModule {}
<file_sep>/src/entities/cars/cars.controller.ts
import { Controller, Get, Body, Post } from '@nestjs/common';
import { CarsService } from './cars.service';
import { Cars } from './cars.entity';
import { CarsModel } from 'src/DTO/cars.model';
import { SearchModel } from 'src/DTO/search.model';
@Controller('cars')
export class CarsController {
constructor(private readonly carsService: CarsService){}
@Get()
findAll() :Promise<Cars[]>{
return this.carsService.findAll();
}
@Get('search')
searchWithModel(@Body()search: SearchModel){
return this.carsService.findWithModel(search);
}
@Post()
insertCar(@Body()car: CarsModel ){
this.carsService.insert(car);
}
}
<file_sep>/src/entities/liked-ads/liked-ads.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Liked_ads } from './liked-ads.entity';
import { Repository } from 'typeorm';
@Injectable()
export class LikedAdsService {
constructor(
@InjectRepository(Liked_ads)
private likedAdsRepo: Repository<Liked_ads>,
){}
async findAll(): Promise<Liked_ads[]>{
return this.likedAdsRepo.find();
}
findOne(id: number): Promise<Liked_ads>{
return this.likedAdsRepo.findOne(id);
}
}
<file_sep>/src/entities/cities/cities.controller.ts
import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { CitiesService } from './cities.service';
import { Cities } from './cities.entity';
import { CitiesModel } from 'src/DTO/cities.model';
@Controller('cities')
export class CitiesController {
constructor(protected readonly citiesService: CitiesService){}
@Get()
findAll(): Promise<Cities[]>{
return this.citiesService.findAll();
}
@Get(':id')
findOne(@Param('id') id: number){
return this.citiesService.findOne(id);
}
@Post()
setCity(@Body('name') name: string ) {
this.citiesService.insertOne(new CitiesModel(0, name));
}
@Post('update/:id')
updateCity(@Param('id') id: number, @Body('name') name: string) {
this.citiesService.updateOne(new CitiesModel(id, name));
}
}
<file_sep>/src/DTO/models.model.ts
export class ModelsModel{
id: number;
modelName: string;
man: string;
constructor(id: number, name: string, man: string){
this.id = id;
this.modelName = name;
this.man = man;
}
getID(): number{
return this.id;
}
getName(): string{
return this.modelName;
}
getMan(): string{
return this.man;
}
}<file_sep>/src/queries/queries.module.ts
import { Module } from '@nestjs/common';
import { QueriesController } from './queries.controller';
import { QueriesService } from './queries.service';
import { AdvertismentsModule } from 'src/entities/advertisments/advertisments.module';
import { AdvertismentsService } from 'src/entities/advertisments/advertisments.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Advertisments } from 'src/entities/advertisments/advertisments.entity';
import { Cars } from 'src/entities/cars/cars.entity';
import { Users } from 'src/entities/users/users.entity';
import { Cities } from 'src/entities/cities/cities.entity';
import { EngineType } from 'src/entities/engine-type/engine-type.entity';
import { CarsModule } from 'src/entities/cars/cars.module';
import { CarsService } from 'src/entities/cars/cars.service';
import { Transmission_Type } from 'src/entities/trans-type/trans-type.entity';
import { Type_of_car } from 'src/entities/car-type/car-type.entity';
import { Wheeldrive } from 'src/entities/wheeldrive/wheeldrive.entity';
import { Models } from 'src/entities/models/models.entity';
import { Manufacturer } from 'src/entities/manufacturer/manufacturer.entity';
@Module({
imports: [AdvertismentsModule, CarsModule,
TypeOrmModule.forFeature([Advertisments, Cars, Users, Cities, EngineType, Transmission_Type, Type_of_car, Wheeldrive, Models, Manufacturer])],
controllers: [QueriesController],
providers: [QueriesService, AdvertismentsService, CarsService]
})
export class QueriesModule {}
<file_sep>/src/DTO/cars.model.ts
export class CarsModel{
carID: number;
engineType: string;
model: string;
transType: string;
carType: string;
wheelDrive: string;
doorNumber: number;
yearDev: number;
man: string;
constructor(id: number, engine: string, model: string, trans: string, car: string, drive: string, doors: number, year: number){
this.carID = id;
this.engineType = engine;
this.model = model;
this.transType = trans;
this.carType = car;
this.wheelDrive = drive;
this.doorNumber = doors;
this.yearDev = year;
}
getID(): number{
return this.carID;
}
getEngine(): string{
return this.engineType;
}
getModel(): string{
return this.model;
}
getTransmission(): string{
return this.transType;
}
getCarType(): string{
return this.carType;
}
getWheelDrive(): string{
return this.wheelDrive;
}
getDoors(): number{
return this.doorNumber;
}
getYearDev(): number{
return this.yearDev;
}
}<file_sep>/src/DTO/cities.model.ts
export class CitiesModel{
id: number;
cityName: string;
constructor(id: number, name: string){
this.id = id;
this.cityName = name;
}
getID(): number{
return this.id;
}
getCity(): string{
return this.cityName;
}
}<file_sep>/src/entities/users/users.entity.ts
import { PrimaryGeneratedColumn, Column, OneToMany, Entity } from "typeorm";
import { Liked_ads } from "../liked-ads/liked-ads.entity";
import { Advertisments } from "../advertisments/advertisments.entity";
@Entity()
export class Users{
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
@Column()
email: string;
@Column()
name: string;
@OneToMany( type => Advertisments, ad => ad.creatorID )
ad: Advertisments[];
@OneToMany( type => Liked_ads, lad => lad.user )
lad: Liked_ads[];
}<file_sep>/src/img/img.controller.ts
import { Controller, Get, Res, Param } from '@nestjs/common';
import * as fs from 'fs-extra';
@Controller('img')
export class ImgController {
@Get(':ad')
findAdWithDesc(@Param('ad') ad: string, @Res() res){
const id = ad.split("_");
const dir = 'F:/ads/ad' + id[0] +'/photos';
if( !fs.existsSync(dir) ){
return res.status(404).send();
}
else{
res.sendFile( ad , { root: dir});
}
}
}
<file_sep>/src/entities/car-type/car-type.service.ts
import { Injectable, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Type_of_car } from './car-type.entity';
import { Repository } from 'typeorm';
import { CarTypeModel } from 'src/DTO/carType.model';
@Injectable()
export class CarTypeService {
constructor(
@InjectRepository(Type_of_car)
private carTypeRepo: Repository<Type_of_car>,
){}
async findAll(): Promise<Type_of_car[]>{
return this.carTypeRepo.find();
}
async findWithName(typeName: string): Promise<Type_of_car>{
return this.carTypeRepo.findOne({where: {name: typeName}});
}
findOne(id: number): Promise<Type_of_car>{
return this.carTypeRepo.findOne(id);
}
async insertOne(type: CarTypeModel){
const row = new Type_of_car();
row.name = type.carType;
if(await this.checkExists(type.carType) != 0){
throw ConflictException;
}
this.carTypeRepo.insert(row);
}
updateOne(type: CarTypeModel){
const row = new Type_of_car();
row.name = type.getCarType();
this.carTypeRepo.update(type.getID(), row);
}
deleteOne(id: number){
this.carTypeRepo.delete(id);
}
private checkExists(type: string){
return this.carTypeRepo.count({where: {name: type}});
}
}
<file_sep>/src/queries/queries.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { QueriesService } from './queries.service';
import { SearchModel } from 'src/DTO/search.model';
import * as fs from 'fs-extra';
import { Advertisments } from 'src/entities/advertisments/advertisments.entity';
import { AddUserOptions } from 'typeorm';
@Controller('queries')
export class QueriesController {
constructor(private queriesService: QueriesService){}
@Get('ads')
async getAds(){
return await this.queriesService.getAds(false);
}
@Get('all')
async getAllData(){
var cities = await this.queriesService.getCities();
var ads= await this.queriesService.getAds(false);
var wheelDrives = await this.queriesService.getWheel();
var engines = await this.queriesService.getEngines();
var transmissions = await this.queriesService.getTransm();
var models = await this.queriesService.getModels();
var types = await this.queriesService.getCarType();
var man = await this.queriesService.getMan();
var arrayUrls: any[] = new Array(0);
ads.forEach(ad => {
var urls: string[] = new Array(0);
const files = fs.readdirSync(ad.photos);
files.forEach(file => {
urls.push('localhost:3000/img/' + file)
});
arrayUrls.push({
'id': ad.adID,
'urls': urls
})
});
return {
"cities": cities,
"wheel drives": wheelDrives,
"engines": engines,
"transmissions": transmissions,
"models": models,
"car types": types,
"manufacturers": man,
"ads": ads,
"adsUrls": arrayUrls
}
}
@Post('search')
async searchBy(@Body()search: SearchModel){
return this.queriesService.searchBy(search);
}
}
<file_sep>/src/upload/uploads/uploads.controller.ts
import { Controller, Post, UseInterceptors, UploadedFile, UploadedFiles, Param, Res, Get, Body } from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import * as fs from 'fs-extra';
import { AdvertismentsModel } from 'src/DTO/advertisments.model';
@Controller('uploads')
export class UploadsController {
@Post()
@UseInterceptors(
FileInterceptor('image',)
)
async getImage(@UploadedFile() file, ad: AdvertismentsModel){
fs.move('./ads/photos/' + file.filename, this.createFilePath(1, ad));
}
@Post('multiple')
@UseInterceptors(
FilesInterceptor('image', 20)
)
async getAllImages(@UploadedFiles() files, @Body() ad: AdvertismentsModel){
let count = 1;
files.forEach(file => {
fs.move('./ads/photos/' + file.filename, this.createFilePath(count, ad) );
count++;
});
}
@Get(':img')
seeImage(@Param('img') image, @Res() res, @Body()ad: AdvertismentsModel){
let rootDirAd = 'F:/ads/ad' + ad.id + '/photos/';
let fileName = ad.id + '_' + image + '.jpg'
return res.sendFile( fileName, { root: rootDirAd });
}
private createFilePath(counter: number, ad: AdvertismentsModel){
this.createDir(ad);
return 'F:/ads/ad' + ad.id + '/photos/' + ad.id + '_' + counter + '.jpg';
}
private createDir(ad: AdvertismentsModel){
if(!fs.existsSync('F:/ads/ad' + ad.id +'/photos',)){
fs.mkdir('F:/ads/ad' + ad.id, (err)=>{
if(err) throw err;
} );
fs.mkdir('F:/ads/ad' + ad.id +'/photos', (err)=>{
if(err) throw err;
} );
}
}
}
<file_sep>/src/entities/car-type/car-type.entity.ts
import { PrimaryGeneratedColumn, Column, OneToMany, Entity } from "typeorm";
import { Cars } from "../cars/cars.entity";
@Entity()
export class Type_of_car{
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(type => Cars, car => car.carTypeID)
cars: Cars[];
}<file_sep>/src/account-service/account-service.service.ts
import { Injectable } from '@nestjs/common';
import { UsersService } from 'src/entities/users/users.service';
import { UsersModel } from 'src/DTO/users.model';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AccountServiceService {
constructor(
private usersService: UsersService,
private jwtService: JwtService
){}
async validateUser(user: UsersModel){
const logged = await this.usersService.findWithUsername(user.email);
if(logged.password != user.password){
return false;
}
return true;
}
async login(user: any){
const ifLogged = await this.usersService.findUser(user);
if(ifLogged.id == null){
return "no";
}
const payload = { username: user.username, name: ifLogged.name, sub: user.userID};
return {
access_token: this.jwtService.sign(payload),
};
}
}
<file_sep>/src/entities/engine-type/engine-type.service.ts
import { Injectable, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { EngineType } from './engine-type.entity';
import { Repository } from 'typeorm';
import { EngineTypeModel } from 'src/DTO/engineType.model';
import { throwError } from 'rxjs';
@Injectable()
export class EngineTypeService {
constructor(
@InjectRepository(EngineType)
private engineTypeRepo: Repository<EngineType>,
){}
findAll(): Promise<EngineType[]>{
return this.engineTypeRepo.find();
}
findOne(id: number): Promise<EngineType>{
return this.engineTypeRepo.findOne(id);
}
findWithType(typeName: string): Promise<EngineType>{
return this.engineTypeRepo.findOne({where: {type: typeName}});
}
async insertOne(type: EngineTypeModel){
const row = new EngineType();
row.type = type.engineType;
if(await this.checkExists(type.engineType) != 0){
throwError(ConflictException);
}
this.engineTypeRepo.insert(row);
}
updateOne(type: EngineTypeModel){
const row = new EngineType();
row.type = type.getEngineType();
this.engineTypeRepo.update(type.getID(), row);
}
deleteOne(id: number){
this.engineTypeRepo.delete(id);
}
private checkExists(engine: string){
return this.engineTypeRepo.count({where: {type: engine}});
}
}
<file_sep>/src/entities/models/models.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Models } from './models.entity';
import { ModelsController } from './models.controller';
import { ModelsService } from './models.service';
import { ManufacturerService } from '../manufacturer/manufacturer.service';
import { Manufacturer } from '../manufacturer/manufacturer.entity';
import { ManufacturerModule } from '../manufacturer/manufacturer.module';
@Module({
imports: [ TypeOrmModule.forFeature([Models, Manufacturer]), ManufacturerModule],
providers: [ModelsService, ManufacturerService],
exports: [TypeOrmModule],
controllers: [ModelsController]
})
export class ModelsModule {
}
<file_sep>/src/account-service/constants.ts
export const jwtConstants = {
secret: 'secretKey',//to do da ne se vijda
};<file_sep>/src/DTO/engineType.model.ts
export class EngineTypeModel{
id: number;
engineType: string;
constructor(id: number, type: string){
this.id = id;
this.engineType = type;
}
getID(): number{
return this.id;
}
getEngineType(): string{
return this.engineType;
}
}<file_sep>/src/entities/cars/cars.entity.ts
import { PrimaryGeneratedColumn, Column, OneToMany, Entity, ManyToOne } from "typeorm";
import { Advertisments } from "../advertisments/advertisments.entity";
import { EngineType } from "../engine-type/engine-type.entity";
import { Models } from "../models/models.entity";
import { Transmission_Type } from "../trans-type/trans-type.entity";
import { Type_of_car } from "../car-type/car-type.entity";
import { Wheeldrive } from "../wheeldrive/wheeldrive.entity";
@Entity()
export class Cars{
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(type => EngineType, type => type.cars)
engineID: EngineType;
@ManyToOne(type => Models, model => model.cars)
modelID: Models;
@ManyToOne(type => Transmission_Type, trans => trans.cars)
transID: Transmission_Type;
@ManyToOne(type => Type_of_car, type => type.cars)
carTypeID: Type_of_car;
@ManyToOne(type => Wheeldrive, drive => drive.cars)
wheelDriveID: Wheeldrive;
@Column()
doors: number;
@Column()
year: number;
@OneToMany( type => Advertisments, ad => ad.carID)
ad: Advertisments[];
}<file_sep>/src/entities/manufacturer/manufacturer.service.ts
import { Injectable, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Manufacturer } from './manufacturer.entity';
import { Repository } from 'typeorm';
import { ManufacturerModel } from 'src/DTO/manufacturer.model';
@Injectable()
export class ManufacturerService {
constructor(
@InjectRepository(Manufacturer)
private manRepo: Repository<Manufacturer>
){}
async findAll(): Promise<Manufacturer[]>{
return this.manRepo.find();
}
async findOne(id: number): Promise<Manufacturer>{
return this.manRepo.findOne(id);
}
async findWithName(man: string): Promise<Manufacturer>{
return this.manRepo.findOne({where: {name: man}});
}
async insertOne(mann: ManufacturerModel){
const row = new Manufacturer();
row.name = mann.man;
if (await this.checkExists(mann.man) != 0){
throw ConflictException;
}
this.manRepo.insert(row);
}
updateOne(man: ManufacturerModel){
const row = new Manufacturer();
row.name = man.man;
this.manRepo.update(man.getID(), row);
}
deleteOne(id: number){
this.manRepo.delete(id);
}
private async checkExists(manName: string): Promise<number>{
return this.manRepo.count({where: {name: manName}});
}
}
<file_sep>/src/entities/engine-type/engine-type.entity.ts
import { PrimaryGeneratedColumn, Column, OneToMany, Entity } from "typeorm";
import { Cars } from "../cars/cars.entity";
@Entity()
export class EngineType{
@PrimaryGeneratedColumn()
id: number;
@Column()
type: string;
@OneToMany(type => Cars, car => car.engineID)
cars: Cars[];
}<file_sep>/src/queries/queries.service.ts
import { Injectable } from '@nestjs/common';
import { AdvertismentsService } from 'src/entities/advertisments/advertisments.service';
import { CarsService } from 'src/entities/cars/cars.service';
import { SearchModel } from 'src/DTO/search.model';
import { Advertisments } from 'src/entities/advertisments/advertisments.entity';
import fs from 'fs-extra';
import { AdvertismentsModel } from 'src/DTO/advertisments.model';
import { Cars } from 'src/entities/cars/cars.entity';
import { CarsModel } from 'src/DTO/cars.model';
@Injectable()
export class QueriesService {
constructor(
private ads: AdvertismentsService,
private cars: CarsService
){}
async getAds(choice: boolean){
const ads = await this.ads.findAll();
if(choice == true){
var adsModels: AdvertismentsModel[] = new Array(0);
ads.forEach(ad=>{
adsModels.push(this.fromEntityToModel(ad));
});
return adsModels;
}
return ads;
}
getPhotos(ads: Advertisments[]){
ads.forEach(ad => {
var photoObj = {
name: ad.adID,
}
});
}
private fromEntityToModel(ad: Advertisments){
var adModel: AdvertismentsModel;
adModel.id = ad.adID;
adModel.car = this.fromCarsToModel(ad.carID);
adModel.city = ad.cityID.cityName;
adModel.creatorPN = ad.creatorPN;
adModel.creatorUsername = ad.creatorID.username;
adModel.desc = ad.desc;
adModel.price = ad.price;
const files = fs.readdirSync(ad.photos);
files.forEach(file => {
adModel.urls.push('localhost:3000/img/' + file)
});
return adModel;
}
private fromCarsToModel(car: Cars){
var carModel: CarsModel;
carModel.carID = car.id;
carModel.doorNumber = car.doors;
carModel.engineType = car.engineID.type;
carModel.man = car.modelID.manID.name;
carModel.yearDev = car.year;
carModel.transType = car.transID.type;
carModel.wheelDrive = car.wheelDriveID.type;
carModel.model = car.modelID.modelName;
carModel.carType = car.carTypeID.name;
return carModel;
}
private getPhotosWithID(dir: string,id: number){
var array = new Array(0);
fs.readdir(dir, (error, files) => {
let totalFiles = files.length;
for(var i=0; i < files.length; i++){
array.push();
}
});
}
async searchBy(search: SearchModel){
var array = await this.ads.findAll();
return this.getWithSearch(search, array);
}
private getWithSearch(seacrh: SearchModel, array: Advertisments[]){
return this.getEngine(seacrh, array);
}
private getEngine(seacrh: SearchModel, array: Advertisments[]){
if(seacrh.engine != "null"){
return this.getTrans(seacrh, array.filter(function(value, index, arr){
return value.carID.engineID.type == seacrh.engine;
}));
}
return this.getTrans(seacrh, array);
}
private getTrans(seacrh: SearchModel, array: Advertisments[]){
if(seacrh.transmission != "null"){
return this.getModel(seacrh, array.filter(function(value, index, arr){
return value.carID.transID.type == seacrh.transmission;
}))
}
return this.getModel(seacrh, array);
}
private getModel(seacrh: SearchModel, array: Advertisments[]){
if(seacrh.model != "null"){
return this.getManSearch( seacrh, array.filter(function(value, index, arr){
return value.carID.modelID.modelName == seacrh.model;
}))
}
return this.getManSearch(seacrh, array);
}
private getManSearch(seacrh: SearchModel, array: Advertisments[]){
if(seacrh.manufacturer != "null"){
return this.getCar(seacrh, array.filter(function(value, index, arr){
return (value.carID.modelID.manID.name == seacrh.manufacturer);
}))
}
return this.getCar(seacrh, array);
}
private getCar(seacrh: SearchModel, array: Advertisments[]){
if(seacrh.car_type != "null"){
return this.getWheelSearch(seacrh, array.filter(function(value, index, arr){
return (value.carID.carTypeID.name == seacrh.car_type);
}))
}
return this.getWheelSearch(seacrh, array);
}
private getWheelSearch(seacrh: SearchModel, array: Advertisments[]){
if(seacrh.wheelDrive != "null"){
return this.getDoors(seacrh, array.filter(function(value, index, arr){
return (value.carID.wheelDriveID.type == seacrh.wheelDrive);
}))
}
return this.getDoors(seacrh, array);
}
private getDoors(seacrh: SearchModel, array: Advertisments[]){
if(seacrh.doors != 0){
return this.getCity(seacrh, array.filter(function(value, index, arr){
return (value.carID.doors == seacrh.doors);
}))
}
return this.getCity(seacrh, array);
}
private getCity(seacrh: SearchModel, array: Advertisments[]){
if(seacrh.city != "null"){
return this.getYearSeacrh(seacrh, array.filter(function(value, index, arr){
return (value.cityID.cityName == seacrh.city);
}))
}
return this.getYearSeacrh(seacrh, array);
}
private getYearSeacrh(seacrh: SearchModel, array: Advertisments[]){
var doneArray: Advertisments[] = new Array(0);
array.forEach(ad => {
if(ad.carID.year >= seacrh.year_from){
if(seacrh.year_to != 0){
if(ad.carID.year <= seacrh.year_to){
doneArray.push(ad);
}
}
else{
doneArray.push(ad);
}
}
else{
return this.getPriceSearch(seacrh, array);
}
});
return this.getPriceSearch(seacrh,doneArray);
}
private getPriceSearch(seacrh: SearchModel, array: Advertisments[]){
var doneArray: Advertisments[] = new Array(0);
array.forEach(ad => {
if(ad.price >= seacrh.price_from){
if(seacrh.price_to != 0){
if(ad.price <= seacrh.price_to){
doneArray.push(ad);
}
}
else{
doneArray.push(ad);
}
}
else{
return array;
}
});
return doneArray;
}
async getCities(){
return await this.ads.getCities();
}
async getEngines(){
return await this.cars.returnEngines();
}
async getModels(){
return await this.cars.returnModels();
}
async getTransm(){
return await this.cars.returnTransm();
}
async getCarType(){
return await this.cars.returnCarType();
}
async getWheel(){
return await this.cars.returnWheelDrive();
}
async getMan(){
return await this.cars.returnMan();
}
}
<file_sep>/src/entities/engine-type/engine-type.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { EngineType } from './engine-type.entity';
import { EngineTypeService } from './engine-type.service';
import { EngineTypeController } from './engine-type.controller';
@Module({
imports: [TypeOrmModule.forFeature([EngineType])],
providers:[EngineTypeService],
exports: [TypeOrmModule],
controllers: [EngineTypeController]
})
export class EngineTypeModule {}
| bfe104097f20d4cf72c8b380cce963773a3ebb8b | [
"TypeScript"
] | 62 | TypeScript | dasnonap/Cars | c91652b9d1de46ccae8ccc80dd543a0855bbf398 | 67024e2ec3bc7641b6c43e6de1d70f4fc4fd2ea1 |
refs/heads/master | <repo_name>AAGAN/twoPhaseSimulationInternProject<file_sep>/articles/readme.md
all the research articles related to this project
<file_sep>/weeklyReports/Week 1.md
# Week 1 Report (10th June-14th June)
## Literature review
### Different types of Fire suppression systems under consideration
#### 1. SAPPHIRE® PLUS 70-BAR SYSTEM
[ https://www.ansul.com/en/us/pages/ProductSeries.aspx?ProductType=Clean+Agent+Systems ]
Chemical used: 3M Novec 1230 [Refer 3M pdf for detailed properties] or dodecafluoro-2-methylpentan-3-one
Pressure: 70bar (mostly 25-42 bar pressurized with help of nitrogen) [ref: https://www.tycoifs.co.uk/how-we-can-help/protect-your-business/fire-suppression-systems-marine/gaseous-systems-sapphire-novec-1230/ ]
Container size range: 8ltr to 180 ltr
Release time: within 10sec (depends on combination of pressure and valve)
Method: Fully flooding, mainly absorbs heat and has some chemical interference with the flame. Upon discharge forms a gaseous mixture with air
Specialties:
1. Higher fill densities reduces no. of cylinders
2. Increased pressure helps in keeping containers far away and selector valves possibles
3. pipe size may also be reduced to save money and design flexibility
4. good for class A,B and C fire hazard
5. Evaporates 50 times faster than water
6. Electrically non-conductive
7. Very Low water solubility
8. principal atmospheric sink for Novec 1230 agent is photolysis
Concentrations: 4.5 – 5.9% (safe up to 10%)
ODP=0, ALT= 3-5 DAYS, GWP=1.0
Safety:
NOVEC 1230 decomposes at temperatures in excess of 500°C and it is therefore important to avoid applications involving hazards where continuously hot surfaces are involved. Upon exposure to the flame, NOVEC 1230 will decompose to form halogen acids. Their presence will be readily detected by a sharp, pungent odor before maximum exposure levels are reached.
Each container assembly comprises of a container, valve, siphon tube, safety fittings and container nameplate. Containers are painted signal red to identify them as fire protection equipment.
The valve is designed for high discharge rates to allow the full container contents to be released within ten seconds.
Thermal properties:

Variation in vapor pressure and density with temperature:


Even though liquid has enough vapor concentration to suppress fire. At 39% volume concentration in air it reaches saturation. In applications concentration used is less than 6%
Novec 1230 fluid is such that it would support an extinguishing concentration of 5vol% at a temperature as low as –16°C (3°F). Water does not support a 5vol% concentration in air until the temperature exceeds 33°C(91°F). This can be seen in following graph.

https://instor.com/blog/which-data-center-fire-suppression-solution-works-best-for-you/
#### Inergen Systems
Inergen is a breathable gas comprised of 52% Nitrogen, 40%Argon and 8% Carbon Dioxide. It suppresses a fire by lowering the oxygen level in a room below the level needed to support combustion, but still leaves the oxygen level high enough to sustain life, while suppressing the fire. The release time for Inergen is 60 seconds, which is the longest release time of these three options. Inergen systems require more intricate pipe systems that also require more pressure to be maintained within the system.
#### FM-200 Systems
FM-200 systems also suppress fires by removing heat from the room. They can be used with people in the room with few adverse effects. FM-200 systems are also much quicker than Inergen systems to reach full fire suppression levels. FM-200 has a much better potential for having a global warming effect than the other two systems.
All three of these different clean agent systems can be used while employees remain inside of the room, but Inergen seems to have more of a risk factor for some people because it lowers the oxygen level, which may not be ideal for all people. All three of these systems require floor space and are costlier to install and maintain than water systems. In addition to these disadvantages, clean agent systems can be linked to the EPO (Emergency Power Off) System. This was a requirement of the NFPA until 2011.
#### CO2 Agent:
Carbon dioxide is an effective fire suppressing agent that can be used on many types of fires. It is effective for surface fires, such as flammable liquids and most solid combustible materials. It expands at a ratio of 450 to 1 by volume. For fire suppression purposes, the discharge is designed to raise the carbon dioxide concentration in the hazard. This displaces the air, which contains oxygen that supports combustion, and results in fire suppression. Other attributes are its high degree of effectiveness, its excellent thermal stability, and its freedom from deterioration. It is electrically non-conductive, and leaves no residue to clean up after discharge.
### DIFFERENT MODEL USED FOR ANALYSIS
#### Modeling of the Flow Properties and Discharge of Halon Replacement Agents (by <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, Hughes Associates)
##### * Assumptions
1.Conditions in cylinder (P, T, composition) = f( initial conditions, outage fraction)
where outage fraction= fraction of initial mass left; This assumption ignores impact of K.E. of fluid leaving cylinder on the cylinder energy balance
2.Quasi-steady Flow
(average flow rate over a small time step is equal to the flow rate that would exist if the cylinder conditions were held steady during the time step)
3.Flow through pipe is homogeneouos (both phases at same velocity with one phase totally dispersed in other)
4.Heat transfer through the pipes is considered insignificant. (This can't be done for our model)
##### * Method used (HFLOW with small extension for application)
1.Flow rate estimated approximately (guess)
2.Network is stepped through to determine condition at nozzle
3.Use Energy and momentum balance eqn to find P and T at each node.
(branches in the network stepped by 34.5KPa pressure drops and distance travelled determined through momentum balance but some adjustment can be done in the pressure to keep the distance between nodes less than 8cm. The distance aims at easy identification of location for sonic condition )
4.Estimated flow rate is then refined by comparison to deteremined flow through the nozzles. Iterations done.
5.Elapsed time measured using mass balance (Mass that has already left cylincer/ mass flow rate)
##### *Variation in pressure vs Time

In Normal Scenario (a):
Start – (1): agent not reached the nozzle yet, progressing through network at sonic conditions
(1)-(2): After the pipe gets full at (1), pressure and mass in the pipe network starts building up to reach peak value. (In this section flow rate through the network starts dropping whereas flow from the nozzle starts increasing)
(2)-(3): Mass flow rate out of cylinder is equal to that of nozzle.
(3)-(4): Vapor front from the cylinder starts flowing in the pipe network in the same way as the liquid front started initially. The low flow rate of liquid ahead of the vapor in the network controls and prevents vapor from increasing its flow rate.
After(4): Once nozzle is cleared of liquid, the flow rate of vapor from cylinder increases rapidly and then falls off (flow rate from cylinder = nozzle)
Other scenarios:
(b).Cylinder runs out of liquid prior to reaching peak pressure in pipe:
In such case the pressure at nozzle will continue to rise but the apex won’t be that high. Also steady flow section never comes i.e (2)-(3)
(c).Nozzle does not control the flow rate or controls it completely:
In extreme cases pipe peak pressure already occurs before liquid front reaches nozzles. i.e. section (1)-(2) is skipped.
##### *Flow chart/Algorithm of the model

##### *Accuracy and Limitations of Model
1.Model can measure the discharge time based on nozzle liquid runout with reasonable accuracy and its easy to modify for halon kind of gases.
2.Model halts execution if the cylinder runs out of liquid prior to liquid reaching the last nozzle. This limits the pipe volume roughly to an NFPA 12A 70% agent in pipe. (pipe volume/ initial cylincder liquid volume = 1.6)
3.Needs to tested on more orientation of pipe networks. (here it is tested against 2 Tee orientation: Horizontal bull-head and horizontal side flow)
4.Largest flow splits that the model can handle is also not known for different pipe networks. (The two orienations used here have maximum flow split around 90%/10%)
##### *Original HFLOW Model (refered in this document) is taken from the following research paper: Flow of Nitrogen- Pressurized Halon 1301 in Fire Extinguishing syatems by Elliot et. al.

Note: The numbers in the diagram show the sequence of steps the program goes through
##### Will add more details of this research paper and its model in next Weekly report
<file_sep>/modules/calcQ.py
import numpy as np
from scipy.integrate import solve_ivp
class calcQ:
def __init__(self,
L, #length of the pipe
D, #internal Diameter of the pipe
M1, #Initial Mach number
ff, #friction factor of the pipe
T01, #initial total temperature of the gas
T1, #initial temperature of the gas
P01, #initial pressure of the gas
P1, #initial pressure of the gas
rho1, #initial density of the gas
gamma, #ratio of specific heats
Q, #Tw-T0 is constant for the case of constant heat transfer to the pipe
numSteps = 10000 #number of steps from the begining to the end of the pipe
):
self._L = L
self._D = D
self._M1 = M1
self._ff = ff
self._T01 = T01
self._T1 = T1
self._P01 = P01
self._P1 = P1
self._gamma = gamma
self._Q = Q
self._numSteps = numSteps
self._rho1 = rho1
def FuncT0(self, Msq, Gamma):
FuncT0 = Msq*(1.0+Gamma*Msq)*(1.0+(Gamma-1.0)/2.0*Msq)/(1.0-Msq)
return FuncT0
def FuncFf(self, Msq, Gamma):
FuncFf = Gamma*Msq**2*(1.0+(Gamma-1.0)/2.0*Msq)/(1.0-Msq)
return FuncFf
def dT0_dx(self, T0):
_dT0_dx = 2 * self._ff / self._D * (self._Q)
return _dT0_dx
def dM2_dx(self, Msq, T0):
_dM2_dx = self.FuncT0(Msq, self._gamma) * self.dT0_dx(T0) / T0 + self.FuncFf(Msq, self._gamma) * 4.0 * self._ff / self._D
return _dM2_dx
def f(self, t,y):
dydt = [self.dM2_dx(y[0], y[1]),self.dT0_dx(y[1])]
return dydt
def solve(self):
yinit = [self._M1 **2, self._T01]
#tspan = np.linspace(0,self._L,self._numSteps)
#self._soln = solve_ivp(lambda t, y: self.f(t, y), [tspan[0], tspan[-1]], yinit, method = 'Radau', t_eval=tspan, jac = None)
self._soln = solve_ivp(lambda t, y: self.f(t, y), [0, self._L], yinit, method = 'Radau', jac = None)
self._M2 = np.sqrt(self._soln.y[0][-1])
self._T02 = self._soln.y[1][-1]
self.T2()
self.P2()
self.P02()
self.rho2()
self.V2()
def T2(self):
self._T2 = self._T02 / (1+(self._gamma-1.0)/2.0*self._M2**2)
def P2(self):
self._P2 = self._P1 * self._M1/self._M2*np.sqrt((1+(self._gamma-1)/2*self._M1**2)/(1+(self._gamma-1)/2*self._M2**2))*np.sqrt(self._T02/self._T01)
def P02(self):
comg = (self._gamma - 1 ) / 2
self._P02 = self._P01 * self._P2 / self._P1 * ((1+comg*self._M2**2)/(1+comg*self._M1**2))**(self._gamma/(self._gamma-1))
def rho2(self):
self._rho2 = self._rho1 * self._P2/self._P1 * self._T1 / self._T2
def V2(self):
self._V2 = self._M2 / self._M1 * np.sqrt(self._T2/self._T1)<file_sep>/modules/main.py
# overall algorithm is going to be in this file
from thermo import mixture
from fluids.units import *
from thermo.units import Chemical
from pipeNetwork import pipeNetwork
from containerClass import container
from systemDefinitions import system,pipeSections3,orificeDiam3,pipeSections0,orificeDiam0
m = mixture.Mixture(['nitrogen','argon','carbon dioxide'], zs=[.52, .4, .08], T = 300, P=1e5)
#print("Cp = {:.4f}, Cv = {:.4f}, mu = {:.8f}, MW = {:.4f}, SG = {:.4f}, Cp/Cv = {:.4f}, Z = {:.4f}".format(m.Cp, m.Cvg, m.mu, m.MW, m.SG, m.isentropic_exponent, m.Z))
net = pipeNetwork()
net.addSystem(system)
net.addAllPipes(pipeSections3, orificeDiam3)
print(net.tanks.indices)
print(net.nozzles.indices)
final_time = 120.0 #seconds
dt = 1.0 #second
initialMass = 32.2 #kg of agent in each tank
cylInitialTemp = 295.0
agentInitialTemp = 294.0
cylOrificeDiam = 0.0066565
cylL = 1.7
cylD = 0.267
cylWallThickness = 0.005
ambientTemp = 300
initialBackP = 1e5
numTimeSteps = 200
cylInitialPressure = initialMass / (np.pi * cylD**2.0 / 4.0 * cylL) * 8.3145 / m.MW * agentInitialTemp
m = mixture(['nitrogen','argon','carbon dioxide'], zs=[.52, .4, .08], T = agentInitialTemp, P=cylInitialPressure)
cont = [0] * len(net.tanks)
def updatePipeNetwork(oldNetwork):
#create a new pipenetwork based on the caculated values of the previous time
newNetwork = oldNetwork
return newNetwork
time = 0
net.calcNetwork()
nets = []
while time<final_time:
time = time + dt
net = updatePipeNetwork(net)
net.calcNetwork()
if time % 10 == 0:
nets.append(net)<file_sep>/modules/pipeClass.py
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import fsolve
class pipe:
def __init__(self,
pipeLength,
initialMach,
wallTemp,
gamma,
T02_T01 = 1.05):
self.L = pipeLength
self.M1 = initialMach
self.OrgM1 = initialMach
self.finalMach = initialMach
self.gamma = gamma
self.h = 0.01
self.Tw01 = wallTemp
self.Eps = 1e-6 #convergence criteria
self._M2 = [initialMach]
self._T0_T01 = [1]
self._4fx_D = [0]
self._T_T1 = [1]
self._P_P1 = [1]
self._P0_P01 = [1]
#self.findT02()
self.T02_T01 = T02_T01
self.T01 = 300
def printResults(self):
for i in range(len(self._M2)):
print("{:.4f} , {:.4f} , {:.4f} , {:.4f} , {:.4f} , {:.4f}".format(self._M2[i],self._T0_T01[i],self._4fx_D[i],self._T_T1[i],self._P_P1[i],self._P0_P01[i]))
def findT02(self):
OrgM1 = self.M1
M2 = self.M1 + self.h
Prod = 1.0
CommG = (self.gamma - 1.0)/2.0
while (round(M2,5)<=1):
Soln = self.Solve(self.M1,M2,self.Tw01,self.gamma,self.Eps)
if Soln>1.0:
Prod = Prod * Soln
X = 2.0 * (np.log(self.Tw01-1.0)-np.log(self.Tw01-Prod))
T = Prod * (1.0+CommG*OrgM1*OrgM1)/(1.0+CommG*M2*M2)
P = OrgM1/M2*T**0.5
P0 = Prod**0.5*OrgM1/M2*((1.0+CommG*M2*M2)/(1.0+CommG*OrgM1*OrgM1))**((self.gamma+1.0)/(2.0*(self.gamma-1.0)))
#print("{:.4f} , {:.4f} , {:.4f} , {:.4f} , {:.4f} , {:.4f}".format(M2,Prod,X,T,P,P0))
self._M2.append(M2)
self._T0_T01.append(Prod)
self._4fx_D.append(X)
self._T_T1.append(T)
self._P_P1.append(P)
self._P0_P01.append(P0)
else:
print("solution is not converging after M2 = {:.4f}".format(M2))
break
self.M1 = M2
M2 = M2 + self.h
def findM2(self):
M2 = self.M1 + self.h
Prod = 1.0
# if(M2 > 1.0):
# print("There is no solution for the given input, \n The solution does not converge after M2 = {:.4f}".format(M2))
# else:
while True:
if (M2 > 1.0):
print("There is no solution for the given input, \n The solution does not converge after M2 = {:.4f}".format(M2))
break
else:
Soln = self.Solve(self.M1,M2,self.Tw01,self.gamma,self.Eps)
if Soln>1.0:
Prod = Prod * Soln
if (Prod-self.T02_T01 > 0.0):
Prod = Prod / Soln
self.Improv(self.M1,self.T02_T01,self.Tw01,self.gamma,self.Eps,self.h,Prod)
break
else:
self.M1 = M2
M2 = M2 + self.h
else:
print("There is no solution for the given input, \n The solution does not converge after M2 = {:.4f}".format(M2))
break
#print(self.finalMach)
return self._M2[-1]
# def constantTemp(self, M2):
# Mbarsq = ((self.M1 + M2) / 2.0)**2.0
# val = M2**2.0 - self.M1**2.0 - 2.0*(self.T02_T01 - 1.0) * (self.FuncT0(Mbarsq, self.gamma)/(self.T02_T01+1.0))+2.0*self.FuncFf(Mbarsq,self.gamma)/(2.0*self.Tw01-self.T02_T01-1.0)
# return val
# def constantTemp(self):
# T02_T01 = -np.exp(np.log(self.Tw01 - 1.0) - 2.0 * self.f * self.L / self.D ) + self.Tw01
# T
# def findM2fsolve(self):
# root = fsolve(self.constantTemp,0.4)
# print(root)#"rootsq = {:.6f} , root = {:.6f}".format(rootsq,root))
# #return root
def Improv(self,M1,T02_T01,Tw01,gamma,Eps,h,Prod):
NewM1 = M1
Step = h/10.0
NewM2 = M1 + Step
while(Step > Eps):
Soln = self.Solve(NewM1,NewM2,Tw01,gamma,Eps)
Prod = Prod * Soln
if (abs(Prod-T02_T01) < Eps):
#print(NewM2)
break
else:
if(Prod-T02_T01 > 0.0):
NewM2 = NewM2 - Step
Step = Step / 10.0
if Step<Eps:
#print(NewM2)
break
else:
NewM2 = NewM2 + Step
CommG = (self.gamma - 1.0)/2.0
X = 2.0 * (np.log(self.Tw01-1.0)-np.log(self.Tw01-Prod))
T = Prod * (1.0+CommG*self.OrgM1*self.OrgM1)/(1.0+CommG*NewM2*NewM2)
P = self.OrgM1/NewM2*T**0.5
P0 = Prod**0.5*self.OrgM1/NewM2*((1.0+CommG*NewM2*NewM2)/(1.0+CommG*self.OrgM1*self.OrgM1))**((self.gamma+1.0)/(2.0*(self.gamma-1.0)))
self._M2.append(NewM2)
self._T0_T01.append(Prod)
self._4fx_D.append(X)
self._T_T1.append(T)
self._P_P1.append(P)
self._P0_P01.append(P0)
print("M2 = {:.4f}".format(self._M2[-1]))
print("T0/T01 = {:.4f}".format(self._T0_T01[-1]))
print("4fx_D = {:.4f}".format(self._4fx_D[-1]))
print("T_T1 = {:.4f}".format(self._T_T1[-1]))
print("P_P1 = {:.4f}".format(self._P_P1[-1]))
print("P0_P01 = {:.4f}".format(self._P0_P01[-1]))
def M2(self):
return self._M2
def T0_T01(self):
return self._T0_T01
def fx4_D(self):
return self._4fx_D
def T_T1(self):
return self._T_T1
def P_P1(self):
return self._P_P1
def P0_P01(self):
return self._P0_P01
def Solve(self,M1, M2, Tw01, Gamma, Eps):
Init = 1.0
T21 = Init
OldTmp = T21
Mbarsq = ((M1+M2)/2.0)**2.0
Ft0 = self.FuncT0(Mbarsq, Gamma)
Ff = self.FuncFf(Mbarsq, Gamma)
Iter = 0
while (True):
Iter = Iter + 1
#define a relation between Tw01 and T21 for constant heat flux Tw01 = f(T21) or more generally Twn_T0n = f(T21,Tw1_T01)
Soln = -2.0 * Ff * ( np.log(Tw01-1.0) - np.log(Tw01 - T21))
Soln = (M2**2.0 - M1**2.0) / Mbarsq + Soln
Soln = 1.0 + 1.0 / Ft0 * Soln
if (abs(Soln-OldTmp)<Eps):
break
if (Iter>100):
Soln = (OldTmp+Soln)/2.0
break
if (Soln>Tw01):
Soln = abs(Tw01-Soln)
OldTmp = Soln
T21 = Soln
return Soln
def FuncT0(self, Mbarsq, Gamma):
FuncT0 = (1.0+Gamma*Mbarsq)*(1.0+(Gamma-1.0)/2.0*Mbarsq)/(1.0-Mbarsq)
return FuncT0
def FuncFf(self, Mbarsq, Gamma):
FuncFf = Gamma*Mbarsq*(1.0+(Gamma-1.0)/2.0*Mbarsq)/(1.0-Mbarsq)
return FuncFf
# for i in range(10,100, 5):
# print("Tw/T0 = ", i/10.0)
# a = pipe(pipeLength=10,initialMach= 0.5,wallTemp = i/10.0,gamma = 1.4)
# a.findT02()
# plt.plot(a.fx4_D(),a.M2(),label='Tw/T01= {:.1f}'.format(i/10.0))
# plt.ylabel('M2')
# plt.xlabel("$\\frac{4fx}{D}$")
# plt.legend()
# plt.grid()
# plt.show()
# for i in range(10,71,10):
# print("Tw/T0 = ", i/10.0)
# a = pipe(pipeLength=10,initialMach= 0.2,wallTemp = i/10.0,gamma = 1.4)
# a.findT02()
# plt.plot(a.fx4_D(),a.T_T1(),label='Tw/T01= {:.1f}'.format(i/10.0))
# plt.ylabel('Tw/T01')
# plt.xlabel("$\\frac{4fx}{D}$")
# plt.legend()
# plt.grid()
# plt.show()
# for i in range(30,41,10):
# print("Tw/T0 = ", i/10.0)
# a.findT02()
# a = pipe(pipeLength=10,initialMach= 0.4,wallTemp = i/10.0,gamma = 1.4)
#
# a = pipe(pipeLength=10,initialMach= 0.4,wallTemp = 4,gamma = 1.4, T02_T01 = 1.00575)
# a.findM2()
# a = pipe(pipeLength=10,initialMach= 0.4,wallTemp = 4,gamma = 1.4, T02_T01 = 1.00575)
# a.findM2fsolve()<file_sep>/modules/containerClass.py
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
class container:
"""container class to calculate the properties of a pressurized container"""
def __init__(self,
agentInitialTemp, #initial temperature of the gas inside the cylinder
initialMass,
cylInitialTemp,
cylLength,
cylDiam,
nozzleDiam,
wallThickness,
ambientTemp,
backPressure,
endTime,
numTimeSteps = 1000):
#define the parameters
self.T_a0 = agentInitialTemp
self.m_a0 = initialMass #initial mass of gas inside the cylinder
self.T_w0 = cylInitialTemp #initial temperature of the cylinder walls
self.L = cylLength #length of the cylinder
self.D = cylDiam #diameter of the cylinder
self.A_s = np.pi * self.D * ( self.L + self.D / 2.0 ) #surface area of the walls of the tank
self.D_e = nozzleDiam #diameter of the nozzle at the exit (assuming a converging nozzle here)
self.A_e = np.pi * self.D_e **2 / 4.0 #exit area of the nozzle
self.A_c = np.pi* self.D ** 2 /4.0 #Area of the cylinder
self.V = self.A_c * self.L # volume inside the tank
self.R_a = 8.314/0.0340669#gas constant for gas
self.c_w = 1250 #specific heat of the tank wall material
self.g_c = 1 #proportionality appearing in Newton's second law
self.g = 9.81 #gravitational acceleration
self.J = 1 #joule's constant
self.rho_container = 1200 #container wall's density
self.wall_thickness = wallThickness #container wall's thickness
self.m_w = self.rho_container * (np.pi * (self.D+self.wall_thickness/2.0)*self.L*self.wall_thickness + 2 * np.pi / 4.0 * self.D ** 2 * self.wall_thickness) #mass of cylinder
self.T_inf = ambientTemp #ambient temperature
self.p_b = backPressure #back pressure (ambient pressure)
self.Pb = []
self.tt = []
self._endTime = endTime
self.Cd = 0.61
#self.tspan = np.linspace(0,endTime,numTimeSteps) #
def mu(self, T):#=============================================function of film temperature
return 0.00003544#1.8e-3 #* u.kilogram / (u.meter * u.second)
def k_t(self, T):#=============================================function of film temperature
return 0.026 #* u.watt / u.meter / u.kelvin #thermal conductivity of the gas==============================
def beta(self, T):
return 1/T #for ideal gasses
def p_a(self, m_a,R_a,T_a,V):
p = m_a * R_a * T_a / V
return p
def c_p(self, T):#=============================================function of film temperature
return 775#average between 200 and 350 kelvin for inergen #* u.joule / u.kilogram / u.kelvin
def c_v(self, T):#=============================================function of film temperature
return 530#average between 200 and 350 kelvin for inergen #* u.joule / u.kilogram / u.kelvin
def k(self, T):
return 1.4614#k for inergen #self.c_p(T)/self.c_v(T)
def hbar_i(self, T_w, T, ma):
_beta = self.beta(T)
_c_p = self.c_p((T+T_w)/2.0)
_rho = ma / self.V
_mu = self.mu((T+T_w)/2.0)
_k_t = self.k_t((T+T_w)/2.0)
_neu = _mu / _rho
Gr = (self.g * _beta * abs(T_w - T) * self.L ** 3 ) / _neu ** 2
Pr = _c_p * _mu / _k_t
#print(Gr,'\n',_mu,'\n',Pr,'\n',(Gr*Pr))
if 10**4 < Gr * Pr <= 10**9:
C = 0.59
m = 0.25
else:
C = 0.129
m = 1.0/3.0
h = (C * (Gr * Pr) ** m)*_k_t/self.L
return h
def hbar_o(self, T_w):
_beta = self.beta(self.T_inf)
_c_p = self.c_p((self.T_inf+T_w)/2.0)
_rho = self.p_b / self.R_a / self.T_inf
_mu = self.mu((self.T_inf+T_w)/2.0)
_neu = _mu / _rho
_k_t_inf = self.k_t((self.T_inf+T_w)/2.0)
Gr = (self.g * _beta * abs(T_w - self.T_inf) * self.L ** 3 ) / _neu ** 2
Pr = _c_p * _mu / _k_t_inf
#print(Gr,'\n',_mu,'\n',Pr,'\n',(Gr*Pr))
if 10**4 < Gr * Pr <= 10**9:
C = 0.59
m = 0.25
else:
C = 0.129
m = 1.0/3.0
h = (C * (Gr * Pr) ** m)*_k_t_inf/self.L
return h
def mdot_a(self, m_a, T_a, T_w):
'''
This function is calculating the mass flow rate based on venturi or smooth nozzle
geometry. In this case, the Cd = 1. To use this function for orifice plate or other
valves, the Cd of that device should be added to the function.
'''
_k = self.k(T_a)
_p_a = self.p_a(m_a,self.R_a,T_a,self.V)
if self.p_b/_p_a > (2/(_k+1))**(_k/(_k-1)):
p_e = self.p_b
Me = 2 / (_k-1) * (1-(p_e/_p_a)**((_k-1)/_k))
Te = T_a / (1+(_k-1)/2*Me**2)
ce = (_k*self.R_a*self.g_c*Te)**0.5
ve = Me * ce
mdote = -p_e/self.R_a/Te*self.A_e*ve
else: #chocked flor for p_b/p_a <= 0.528
p_e = (2/(_k+1))**(_k/(_k-1)) * _p_a
Me = 1.0
Te = T_a / (1+(_k-1)/2.0)
ve = ce = (_k*self.R_a*self.g_c*Te)**0.5
mdote = -p_e/self.R_a/Te*self.A_e*ve
return mdote * self.Cd
def T_e(self, m_a, T_a, T_w):
_k = self.k(T_a)
_p_a = self.p_a(m_a,self.R_a,T_a,self.V)
if self.p_b/_p_a > 0.528:
p_e = self.p_b
Me = 2 / (_k-1) * (1-(p_e/_p_a)**((_k-1)/_k))
Te = T_a / (1+(_k-1)/2*Me**2)
else: #chocked flor for p_b/p_a <= 0.528
p_e = 0.528 * _p_a
Me = 1.0
Te = T_a / (1+(_k-1)/2.0)
return Te
def v_e(self, m_a, T_a, T_w):
_k = self.k(T_a)
_p_a = self.p_a(m_a,self.R_a,T_a,self.V)
if self.p_b/_p_a > 0.528:
p_e = self.p_b
Me = 2 / (_k-1) * (1-(p_e/_p_a)**((_k-1)/_k))
Te = T_a / (1+(_k-1)/2*Me**2)
ce = (_k*self.R_a*self.g_c*Te)**0.5
ve = Me * ce
else: #chocked flor for p_b/p_a <= 0.528
p_e = 0.528 * _p_a
Me = 1.0
Te = T_a / (1+(_k-1)/2.0)
ve = ce = (_k*self.R_a*self.g_c*Te)**0.5
return ve
def dTa_dt(self, m_a, T_a, T_w):
_hbar_i = self.hbar_i(T_w, T_a, m_a)
_mdot_e = -self.mdot_a(m_a, T_a, T_w)
_T_e = self.T_e(m_a, T_a, T_w)
_v_e = self.v_e(m_a, T_a, T_w)
firstTerm = _mdot_e / m_a * T_a
secondTerm = self.A_s * _hbar_i / self.c_v(T_a) / m_a * (T_w - T_a)
thirdTerm = -_mdot_e / m_a * self.c_p(T_a) / self.c_v(T_a) * _T_e
forthTerm = -_mdot_e * _v_e ** 2 / 2.0 / self.J / self.g_c / self.c_v(T_a) / m_a
dTa_dt = firstTerm + secondTerm + thirdTerm + forthTerm
return dTa_dt # firstTerm , secondTerm , thirdTerm , forthTerm
def dTw_dt(self, m_a,T_a,T_w):
_hbar_o = self.hbar_o(T_w)
_hbar_i = self.hbar_i(T_w, T_a, m_a)
firstTerm = self.A_s*_hbar_o/self.m_w/self.c_w*(self.T_inf-T_w)
secondTerm = -self.A_s*_hbar_i/self.m_w/self.c_w*(T_w-T_a)
dTw_dt = firstTerm+secondTerm
#return dTw_dt
return dTw_dt
#RK4 implementation
def f(self,t, y):
self.p_b = (-9.74505954e-06* t**4 + 1.15123832e-03 * t**3 + 9.92757293e-02 * t**2 - 1.84554866e+01 * t + 6.70539113e+02)*6895
if self.p_b<=1e5:
self.p_b = 1e5
self.Pb.append(self.p_b)
self.tt.append(t)
dydt = [self.mdot_a(y[0], y[1], y[2]), self.dTa_dt(y[0], y[1], y[2]) , self.dTw_dt(y[0], y[1], y[2])]
return dydt
def solve(self):
yinit = [self.m_a0,self.T_a0,self.T_w0]
self.sol = solve_ivp(lambda t, y: self.f(t, y),
[0, self._endTime], yinit,method = 'Radau', jac = None)
# self.sol = solve_ivp(lambda t, y: self.f(t, y),
# [self.tspan[0], self.tspan[-1]], yinit,method = 'Radau', jac = None)
def t(self):
return self.sol.t
def ma(self):
return self.sol.y[0]
def t_t(self):#returns the times when the solver called the f(t,y) function
return self.tt
def P_b(self):#returns the back pressure during the calculation, can be plotted vs t_t
return self.Pb
def Ta(self):
return self.sol.y[1]
def Tw(self):
return self.sol.y[2]
def Pt(self):
return self.p_a(self.sol.y[0],self.R_a,self.sol.y[1],self.V)
def Ve(self):
ve = np.zeros(len(self.sol.y[0]))
for i in range(len(self.sol.y[0])):
ve[i] = self.v_e(self.sol.y[0][i],self.sol.y[1][i],self.sol.y[2][i])
return ve
def Me(self):
Me = np.zeros(len(self.sol.y[0]))
for i in range(len(self.sol.y[0])):
Me[i] = self.M_e(self.sol.y[0][i],self.sol.y[1][i],self.sol.y[2][i])
return Me
def plot(self):
plt.rcParams['figure.figsize'] = (15, 10)
plt.rcParams.update({'font.size': 15})
plt.subplot(2,2,1)
plt.plot(self.sol.t, self.sol.y[0],linewidth = 3)
plt.ylabel("$m_a (kg)$")
plt.ylim(0)
plt.grid()
plt.subplot(2,2,2)
plt.ylabel("$T_a (K)$")
plt.plot(self.sol.t, self.sol.y[1],linewidth = 3)
plt.grid()
#plt.legend()
#plt.xlabel("time (s)")
plt.subplot(2,2,3)
plt.ylabel("$T_w (K)$")
plt.plot(self.sol.t, self.sol.y[2],linewidth = 3)
plt.grid()
#plt.legend()
plt.xlabel("time (s)")
plt.subplot(2,2,4)
plt.ylabel("$Pressure (psi)$")
plt.plot(self.sol.t, self.p_a(self.sol.y[0],self.R_a,self.sol.y[1],self.V)*0.000145038,linewidth = 3)
plt.grid()
#plt.legend()
plt.xlabel("time (s)")
plt.show()
def M_e(self, m_a, T_a, T_w):
_k = self.k(T_a)
_p_a = self.p_a(m_a,self.R_a,T_a,self.V)
if self.p_b/_p_a > 0.528:
p_e = self.p_b
Me = 2 / (_k-1) * (1-(p_e/_p_a)**((_k-1)/_k))
else: #chocked flor for p_b/p_a <= 0.528
p_e = 0.528 * _p_a
Me = 1.0
return Me
def plotVe(self):
ve = np.zeros(len(self.sol.y[0]))
for i in range(len(self.sol.y[0])):
ve[i] = self.M_e(self.sol.y[0][i],self.sol.y[1][i],self.sol.y[2][i])
plt.plot(self.sol.t, ve,linewidth = 3)
plt.grid()
#plt.legend()
plt.show()
<file_sep>/README.md
# twoPhaseSimulationInternProject
* Simulate the properties of the container during the discharge process
* Simulate the properties of the gas (pressure drop) as it flows in the pipe from the container to the nozzles
* Simulate the arrangement of pipes in a tree type network
* Design the system based on the provided design criteria
<file_sep>/modules/orificeForward.py
import numpy as np
from scipy.optimize import fsolve
## Function for Orifice
#For forward pass (Things already known prior to calculation is the mdot, M1, P01, T01 i.e upstream parameters)
def mass_critical (P1,T1,A_o,y,Cd,Mw_gas):
P_1=P1
T_1=T1
_A_o=A_o
C_d=Cd
_y=y
R= 8.3145
_Mw_gas=Mw_gas
_R=R/Mw_gas
m_c= C_d*_A_o*P_1*(2/_R/T_1)**0.5*(_y/(_y+1)*(2/(_y+1))**(2/(_y-1)))**0.5
return m_c
def stat_P (P0, M, y):
P_0=P0
P_stat= P_0/(1+(y-1)/2*M**2)**(y/(y-1))
return P_stat
def stat_T(T0, M, y):
T_0=T0
T_stat= T_0/(1+(y-1)/2 *M**2)
return T_stat
def main_nozzle_forward(P01, T01, mdot,M, d_orifice, d_upstream_pipe,y, Mw_gas):
A_o= (np.pi*d_orifice**2/4) #Area of orifice
A_p= (np.pi*d_upstream_pipe**2/4) #Area of pipe
Cd= 0.61 #Coefficient of discharge, It will be less than 1
#y= 1.4 gamma value changes with the type of gas and conditions
#g=9.81 #gravitational constant
R= 8.3145
_Mw_gas = Mw_gas #since input in grams, if in kg remove this
_R=R/_Mw_gas
B = np.sqrt(A_o/A_p)
P_01=P01
T_01=T01
_m=mdot
P_1=stat_P(P_01,M,y) #these equatiions need Mach number
T_1=stat_T(T_01,M,y)
rho1= P_1/(_R*T_1)
m_c= mass_critical(P_1, T_1, A_o,y,Cd,Mw_gas)
if _m>m_c:
r_f = m_c/_m #reduction factor
print("mass flow rate is greater than critical mass flow rate")
print ('the output you got is the ratio needed to be multiplied to the original first m assumed')
return r_f
elif _m == m_c:
print ('Flow is choked')
P_2 = P_1*(2/(y+1))**(y/(y-1))
P_02 = P_01 + P_2 - P_1 # need to calculate this? or P_02 is P_2 critical itself?
return P_2,P_02
else: #no choking
A=A_o
_B=B
def equation(P_2):
return (Cd*(1-(0.333+1.145*(_B**2+0.7*_B**5+ 12*_B**13))*(P_1-P_2)/(y*P_1))*A*(2*rho1*(P_1-P_2))**0.5-_m)
_P_2= fsolve(equation, P_1-2000 , xtol=0.000001)
#print("Y",(1-(0.333+1.145*(_B**2+0.7*_B**5+ 12*_B**13))*(P_1-_P_2)/(y*P_1)))
#print ('P2=',_P_2,'error=', equation(_P_2))
P_02 = P_01 + _P_2 - P_1
return _P_2[0],P_02[0] # we can even get M and P2 from here
<file_sep>/weeklyReports/Readme.md
folder for the weekly reports
<file_sep>/modules/pipeNetwork.py
from containerClass import container
import numpy as np
from scipy.integrate import solve_ivp
import igraph
from calcTw import calcTw
from calcQ import calcQ
from containerClass import container
from orificeForward import main_nozzle_forward, mass_critical
from systemDefinitions import system,pipeSections,pipeSections1, pipeSections3,orificeDiam3,pipeSections4,pipeSections0,orificeDiam0
class pipeNetwork:
def __init__(self):
self.t = igraph.Graph(directed = True)
#self.t = igraph.GraphBase(directed = True)
#attributes of the pipe network
self.t["agent"] = ""
self.t["discharge_time"] = 0
self.t["cyl_valve_type"] = ""
self.t["cyl_pressure"] = 0
self.t["cyl_size"] = 0
#attributes of the nodes (name is the _id or the provided number of the node)
self.t.vs['type'] = ""
self.t.vs['x'] = 0 #x-coordinate
self.t.vs['y'] = 0 #y-coordinate
self.t.vs['z'] = 0 #z-coordinate
self.t.vs['M'] = 0 #Mach number
self.t.vs['T0'] = 0 #total temperature
self.t.vs['T'] = 0 #temperature
self.t.vs['P0'] = 0 #total pressure
self.t.vs['P'] = 0 #pressure
self.t.vs['rho'] = 0 #density
self.t.vs['D'] = 0 #diameter
self.t.vs['MFR'] = 0 #mass flow rate
self.t.vs['calculated'] = False
#attributes of the edges
self.t.es['L'] = 0 #length
self.t.es['D'] = 0 #internal diameter
self.t.es['H'] = 0 #elevation change
self.t.es['Sch'] = 0 #Schedule
self.t.es['Elb'] = 0 #number of elbows
self.t.es['Stee'] = False #starts with side tee?
self.t.es['Ttee'] = False #start with a through tee?
self.t.es['Cpl'] = 0 #number of coupling or unions
self.t.es['Dtrp'] = 0 #number of dirt traps
self.t.es['Ptap'] = 0 #number of pressure taps
self.t.es['SV'] = 0 #number of selector valves
self.t.es['f'] = 0 #friction factor
self.t.es['MFR'] = 0 #mass flow rate
self.t.es['P0i'] = 0 #initial total pressure calculated
self.C1 = 1e-5 #c1 parameter for the ratio function
self.C2 = 1e-5 #c2 parameter for the ratio function
self.Err = 0.1 #error in calculating deltaP0
self.numSteps = 1000
self.Q = 1 #(Tw-T0) for the case of constant heat flux to the pipe
self.Tw = 300 #wall temperature for the case of constant wall temperature
self.gamma = 1.4
self.ff = 0.005 #friction factor of pipes
self.Cd_orifice = 0.6 #coefficient of discharge for orifices
self.Cd_valve = 0.6 #coefficient of discharge for valves
self.Mdot0 = 0.1 #kg/s initial mass flow rate guess for the first tank
#self.nozzles #stores the vertex sequence of all the nozzles
#self.tanks #stores the vertex sequence of all the tanks
#self.firstTank #index of the first tank vertex
#self.lastNozzle #index of the last nozzle vertex
#self.commonNode # index of the common node
def addSystem(self, _system):
self.t["agent"] = _system["agent"]
self.t["discharge_time"] = _system["discharge_time"]
self.t["cyl_valve_type"] = _system["cyl_valve_type"]
self.t["cyl_pressure"] = _system["cyl_pressure"]
self.t["cyl_size"] = _system["cyl_size"]
def addNode(self, _id, _type=None, _x=None, _y=None, _z=None, _M=None, _P=None, _T=None, _P0=None, _T0=None, _rho=None,_Diam = 0):
self.t.add_vertex(_id, type=_type, x =_x, y=_y, z=_z, M=_M, P=_P, T=_T, P0=_P0, T0=_T0, rho=_rho, D = _Diam)
def addPipe(self,_start, _end, _L, _D, _H, _Sch, _Elb, _Stee, _Ttee, _Cpl, _Dtrp, _Ptap, _SV, _f):
sourceIndex = self.t.vs.select(name_eq = _start)[0].index #it should be bases on _start we need to look up the index from vertices
targetIndex = self.t.vs.select(name_eq = _end)[0].index #same as above
self.t.add_edge(sourceIndex, targetIndex, L=_L, D=_D, H=_H, Sch=_Sch, Elb=_Elb, Stee=_Stee, Ttee= _Ttee, Cpl=_Cpl, Dtrp=_Dtrp, Ptap=_Ptap, SV=_SV, f=_f)
# def addAllNodes(self, _nodes):
# for i in _nodes:
# self.addNode(i[0],i[1],i[2],i[3],i[4],0,0,0,0,0,0)
def addAllNodes(self, _pipes, _orificeDiams):
_nodes=[]
for i in _pipes:
if i[0] not in _nodes:
_nodes.append(i[0])
if i[1] not in _nodes:
_nodes.append(i[1])
for n in _nodes:
diam = 0
if n in _orificeDiams:
diam = _orificeDiams[n]
self.addNode(n, _Diam= diam)
def addAllPipes(self, _pipes, _orificeDiams):
self.addAllNodes(_pipes, _orificeDiams)
for i in _pipes:
self.addPipe(i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8],i[9],i[10],i[11],i[12],0)
#After all the pipes and nodes are added, process the pipe data information
self.processNetwork()
self.findCommonNode()
def processNetwork(self):
if len(self.t.vs.select(_outdegree_gt = 2)) > 0 :
print('only junctions with 2 outlets are accepted')
if len(self.t.vs.select(_indegree_gt = 2)) > 0:
print('only junctions with 2 inlets are accepted')
self.t.vs.select(_outdegree = 0)['type'] = 'nozzle'
self.t.vs.select(_indegree = 0)['type'] = 'tank'
self.t.vs.select(_outdegree = 2)['type'] = 'tee'
self.t.vs.select(_indegree = 2)['type'] = 'tee'
self.t.vs.select(_indegree = 1, _outdegree = 1)['type'] = 'coupling'
self.nozzles = self.t.vs.select(_outdegree = 0)
self.tanks = self.t.vs.select(_indegree = 0)
farthest_points = self.t.farthest_points(directed = True)
self.firstTank = farthest_points[0]
self.lastNozzle = farthest_points[1]
self.t.es['f'] = self.ff
def findCommonNode(self):
commonNodes = []
for node in self.t.vs:
if node.index not in self.nozzles.indices and node.index not in self.tanks.indices:
Common = True
for noz in self.nozzles.indices:
for tank in self.tanks.indices:
if self.t.edge_connectivity(node.index,noz)== 0 or self.t.edge_connectivity(tank, node.index)==0:
Common = False
break
if Common == True:
commonNodes.append(node.index)
self.commonNode = commonNodes[-1]
def topoSummary(self):
igraph.summary(self.t)
print(self.t.get_edgelist())
print(self.t.farthest_points(directed=True))
for i in self.t.vs:
print(i['name'],i.index,i.degree(),i.degree(mode='OUT'),i.degree(mode='IN'))
def plot(self,vertexLabel,edgeLabel):
layout = self.t.layout("kk")
#self.t.vs["label"]=self.t.vs.indices#["index"]#["D"]
#self.t.es["label"]=self.t.es.indices#["L"]
#igraph.plot(self.t, bbox = (1400,1400), layout = layout)
edge_labels = []
vertex_labels = []
visual_style = {}
visual_style["vertex_size"] = 15#40
visual_style["vertex_color"] = "red"#[color_dict[gender] for gender in g.vs["gender"]]
if vertexLabel == "index":
visual_style["vertex_label"] = self.t.vs.indices #["index"]#g.vs["name"]
else:
for i in self.t.vs.indices:
vertex_labels.append((i , self.t.vs[i][vertexLabel]))
visual_style["vertex_label"] = vertex_labels #self.t.vs[vertexLabel]#vertex_labels
if edgeLabel == "index":
visual_style["edge_label"] = self.t.es.indices
else:
for i in self.t.es.indices:
edge_labels.append((i , self.t.es[i][edgeLabel]))
visual_style["edge_label"] = edge_labels #self.t.es[edgeLabel]#edge_labels
visual_style["vertex_label_size"] = 10#25
visual_style["edge_width"] = 2#5#[1 + 2 * int(is_formal) for is_formal in g.es["is_formal"]]
visual_style["edge_label_size"] = 10#25
visual_style["layout"] = layout
visual_style["bbox"] = (500, 500)
visual_style["margin"] = 50
#print(visual_style["vertex_label"])
#print(visual_style["edge_label"])
return igraph.plot(self.t, **visual_style)
def findNext(self, node, edge):
#function to find the next tee, nozzle, tank, commonNode from a node and a pipe based on the direction of the pipe
#if the returned degree findNext()[1] is 1:tank or nozzle, 0:commonNode, 3:tee
_common = self.commonNode
_edge = edge
_node = node
_graph = self.t
_nodeIDs = [node.index]
if _node.index == _common:
return _nodeIDs, 0
if _node.index == _edge.source:
#move forward in the graph until the next tee
_nextNodeID = _edge.target
_nodeIDs.append(_nextNodeID)
while _graph.vs[_nextNodeID].degree()==2 and _graph.vs[_nextNodeID].index != _common:
_nextNodeID = _graph.vs[_nextNodeID].successors()[0].index
_nodeIDs.append(_nextNodeID)
elif _node.index == _edge.target:
#move backwards in the graph until the next tee
_nextNodeID = _edge.source
_nodeIDs.append(_nextNodeID)
while _graph.vs[_nextNodeID].degree()==2 and _graph.vs[_nextNodeID].index != _common:
_nextNodeID = _graph.vs[_nextNodeID].predecessors()[0].index
_nodeIDs.append(_nextNodeID)
else:
return "edge is not connected to the node!"
_nodeType = _graph.vs[_nextNodeID].degree()
if _nextNodeID == _common:
_nodeType = 0
return _nodeIDs, _nodeType
#Assume 50% division at every node in the beginning
def divide(self, ratio2, P_01, P_02,c1,c2, error):
del_P = P_02-P_01
rat_old= ratio2
if del_P > error:
rat_new = rat_old* np.exp(-c1*del_P)
elif del_P < -error:
rat_new = 1 - np.exp(c2*del_P) + rat_old*np.exp(c2*del_P)
return rat_new
#propagate mass flow rates downstream a tee
def propagateMFR(self,node, edge1, edge2):
P01 = edge1['P0i']
P02 = edge2['P0i']
MFR1 = edge1['MFR']
MFR2 = edge2['MFR']
MFR_total = MFR1 + MFR2
ratio = MFR2 / MFR_total
if np.abs(P01-P02)>self.Err:
ratio_new = self.divide(ratio,P01,P02,self.C1,self.C2, self.Err)
ratio_new = 0.1
MFR1_new = (1 - ratio_new)*MFR_total
MFR2_new = ratio_new*MFR_total
#distribute the MFR1_new to the downstream nozzles evenly
nextNodeInEdge1Direction = self.findNext(node,edge1) #find the next node in edge1 direction
if nextNodeInEdge1Direction[1] == 3:#if it is a tee
allPassesFromEdge1 = self.t.get_all_shortest_paths(nextNodeInEdge1Direction[0][-1],self.t.vs.select(_outdegree = 0))
allNozzleIndicesFromEdge1 = [L[-1] for L in allPassesFromEdge1]
for noz in allNozzleIndicesFromEdge1:#allPassesFromEdge1[][-1]:#for noz in all the nozzles after this tee
self.t.vs[noz]['MFR'] = MFR1_new / len(allNozzleIndicesFromEdge1)
else:#if it is a nozzle
self.t.vs[nextNodeInEdge1Direction[0][-1]]['MFR'] = MFR1_new
#distribute the MFR2_new to the downstream nozzles evenly
nextNodeInEdge2Direction = self.findNext(node,edge2)
if nextNodeInEdge2Direction[1] == 3:
allPassesFromEdge2 = self.t.get_all_shortest_paths(nextNodeInEdge2Direction[0][-1],self.t.vs.select(_outdegree = 0))
allNozzleIndicesFromEdge2 = [L[-1] for L in allPassesFromEdge2]
for noz in allNozzleIndicesFromEdge2:#allPassesFromEdge2[][-1]:
self.t.vs[noz]['MFR'] = MFR2_new / len(allNozzleIndicesFromEdge2)
else:
self.t.vs[nextNodeInEdge2Direction[0][-1]]['MFR'] = MFR2_new
#set the 'calculated' property of all the nodes downstream the node to False
for i in self.t.get_all_shortest_paths(node.index,self.t.vs.select(_outdegree = 0)):
for j in i:
self.t.vs[j]['calculated'] = False
#set the P0i of all the edges downstream the node to 0
for i in self.t.get_all_shortest_paths(node.index,self.t.vs.select(_outdegree = 0)):
for k in range(0,len(i)-1):
self.t.es.select(_source = i[k],_target = i[k+1])['P0i'] = 0
else:
node['calculated'] = True
P0 = (P01+P02)/2.0
node['P0']=P0
edge3 = self.t.es.select(_source = self.t.vs[node.index].predecessors()[0].index , _target = node.index)[0]
previousNode = self.findNext(node,edge3)
self.calcNode(node,self.t.vs[previousNode[0][-1]]) #calculate the properties for all the nodes until the next node backwards
def calcNode(self,source, target):
'''
function to calculate the pressure drop between two nodes (from source to target)
calculates all the properties on the path from the source to the target node
saves all the properties on the pipes and nodes. except for MFR and P0
there should be only one path between source and target nodes
'''
nodes = self.t.get_shortest_paths(source.index, target.index,mode='ALL')[0]
direction = 1.0
if len(self.t.es.select(_from = nodes[0], _to = nodes[1])) == 0:
direction = -1.0
for i in range(len(nodes)-1):
if direction == 1:
edge = self.t.es.select(_from = nodes[i], _to = nodes[i+1])[0]
else:
edge = self.t.es.select(_from = nodes[i+1], _to = nodes[i])[0]
#if we're going in the direction of the flow, then edge['L'] is positive, otherwise we need to multiply it by (-1)
calcEdge = calcTw(direction*edge['L'],edge['D'],self.t.vs[nodes[i]]['M'],edge['f'],self.t.vs[nodes[i]]['T0'],self.t.vs[nodes[i]]['T'],self.t.vs[nodes[i]]['P0'],
self.t.vs[nodes[i]]['P'],self.t.vs[nodes[i]]['rho'],self.gamma,self.Tw,self.numSteps)
calcEdge.solve()
self.t.vs[nodes[i+1]]['M'] = calcEdge._M2
self.t.vs[nodes[i+1]]['T0'] = calcEdge._T02
self.t.vs[nodes[i+1]]['T'] = calcEdge._T2
self.t.vs[nodes[i+1]]['P'] = calcEdge._P2
if i != len(nodes)-2:
self.t.vs[nodes[i+1]]['P0'] = calcEdge._P02
edge['P0i'] = calcEdge._P02 #this will be the calculated total pressure at the end of the pipe depending on the direction of calc
self.t.vs[nodes[i+1]]['rho'] = calcEdge._rho2
def calcAfterOrifice(self, MFR,M1, P01, T01, P1, T1, Ao, A1, A2):
'''
calculates the properties after an orifice (section Ao) given the mass flow rate through and the pressure before
page 13-14-15 of the paper
'''
#calculate the critical mass flow rate from equation
mdotCritical = self.Cd_orifice*Ao*P1*np.sqrt(2/self.R/T1)*np.sqrt(self.gamma/(self.gamma+1)*(2/(self.gamma+1))**(2/(self.gamma-1)))
if mdotCritical<MFR:
return mdotCritical/MFR #the main code should reduce the initial mass flow from the first tank by this amount and restart the calculation
elif mdotCritical == MFR: #flow is chocked and equations 4 and 5 needs to be solved to achive the properties after the orifice
P2Critical = P1 * (2/(self.gamma+1))**(self.gamma/(self.gamma-1))
else: #flow is not chocked and equations 1,2,3 should be solved to find the properties after the orifice
return M2,P02,T02,P2,T2
def calcBeforeOrifice(self,MFR, M2, P02, T02, P2, T2, Ao, A1, A2):
'''
calculates the properties before an orifice (section A1) given the mass flow rate through and pressure after the nozzle
'''
r = 200
M1 = MFR / self.t.vs[self.commonNode]['MFR']
P01 = r * M1
T01 = r * M1
P1 = r * M1
T1 = r * M1
return M1,P01,T01,P1,T1
def forwardPass(self):
firstTank = self.firstTank #id of the first tank's node
tank1 = self.t.vs[firstTank]
tank1Valve = self.t.vs[firstTank].successors()[0]
initialMdot0Guess = self.Mdot0
self.t.es.select(_source = tank1.index, _target = tank1Valve.index)[0]['MFR'] = initialMdot0Guess #initial guess by considering a small dt for the container function
nextEdge = self.t.es.select(_source = tank1Valve.index, _target = tank1Valve.successors()[0].index)[0]
if tank1Valve.index == self.commonNode:
pass
#calculate the properties for the common node and store it in that node
else:
nextNode = self.findNext(tank1Valve,nextEdge)[0][-1]#id of the next node to be calculated
#calculate the properties for the next node and store the properties on the next node
self.calcNode(self.t.vs[tank1Valve],self.t.vs[nextNode])
while nextNode[0][-1] != self.commonNode:
print("so far we can only do one cylinder systems")
pass
#find the oposite edge
#find the next tank in the oposite edge direction
#guess a mfr value for this tank
#calculate the properties until the node
#compare the P01 and P02 using the function ratio
#if dp is good then assign average p0 to the node
#add the mfr from both inputs to the next edge
#find the next node
#calculate the properties for the next node and store the properties on that next node except MFR and P0, MFR and P0 should be saved only on the pipes
def backwardPass(self):
#Backward pass implementation
# g.vs[commonNode]['MFR'] = 1
# totalMFR = g.vs[commonNode]['MFR']
# nozzles = g.vs.select(_outdegree = 0)
# for i in nozzles:
# i['MFR'] = totalMFR / len(nozzles)
# i['calculated'] = False
# #print(i['MFR'])
# for noz in nozzles:
# if noz['calculated'] == False:
# print(findNext(noz,g.es.select(_target = noz.index)[0],g,commonNode))
# path = findNext(noz,g.es.select(_target = noz.index)[0],g,commonNode)
# calcNode(g.vs[path[0][0]],g.vs[path[0][-1]],g)
pass
def calcNetwork(self):#calculates the network at the current instace of time
#create a queue for all tees in net2
#calculate the pressure from each nozzle to the upstream tee or manifold node
#if p is calculated from both branches of the tee then calculate the pressure at that tee by iterating over the mass flow rates
#move upstream until all the tees are calculated and have known properties
#start from the most remote cylinder and calculate the pressure downstream until all the properties on tees are known
#compare the pressure of the manifold node from net1 and net2
#Iterate until the pressure of the manifold node is equal
pass | e8bae409b1b92fa8ca98d7c7ef18b5e0d4c78e13 | [
"Markdown",
"Python"
] | 10 | Markdown | AAGAN/twoPhaseSimulationInternProject | 3189dda721a26223c05ae06d3824fd9d892a4f88 | abf3ade87d9f935631f5d6275af8e2ce03c0a885 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace OnTheWay_Models.Trips
{
public class Trip
{
public int MyProperty { get; set; }
}
}
<file_sep>using System;
namespace OnTheWay_Services
{
public class Class1
{
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
namespace OnTheWay_Data.Contracts
{
internal interface IMappingConfiguration
{
void ApplyConfiguration(ModelBuilder modelBuilder);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace OnTheWay_Models.Users
{
public class User : BaseEntity
{
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public DateTime CreatedOnUTC { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime? LastPasswordChangeDate { get; set; }
public int Age { get; set; }
//public Address Address { get; set; }
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using OnTheWay_Data.Contracts;
using OnTheWay_Data.Repositories.Contracts;
using OnTheWay_Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnTheWay_Data.Repositories
{
public class Repository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
{
private readonly IDBContext _context;
private DbSet<TEntity> _entities;
public Repository(IDBContext context)
{
this._context = context;
}
public IQueryable<TEntity> Table => Entities;
protected virtual DbSet<TEntity> Entities
{
get
{
if (_entities == null)
_entities = _context.Set<TEntity>();
return _entities;
}
}
public async Task AddAsync(TEntity entity)
{
if (entity == null)
throw new ArgumentNullException(nameof(entity));
try
{
await Entities.AddAsync(entity);
_context.SaveChanges();
}
catch (DbUpdateException exception)
{
//ensure that the detailed error text is saved in the Log
throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
}
}
public async Task AddRangeAsync(IEnumerable<TEntity> entityCollection)
{
if (entityCollection == null)
throw new ArgumentNullException(nameof(entityCollection));
try
{
await Entities.AddRangeAsync(entityCollection);
_context.SaveChanges();
}
catch (DbUpdateException exception)
{
//ensure that the detailed error text is saved in the Log
throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
}
}
public void Remove(TEntity entity)
{
if (entity == null)
throw new ArgumentNullException(nameof(entity));
try
{
Entities.Remove(entity);
_context.SaveChanges();
}
catch (DbUpdateException exception)
{
//ensure that the detailed error text is saved in the Log
throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
}
}
public async Task<TEntity> GetByIdAsync(int id)
{
return await Entities.FindAsync(id);
}
public void Update(TEntity entity)
{
if (entity == null)
throw new ArgumentNullException(nameof(entity));
try
{
Entities.Update(entity);
_context.SaveChanges();
}
catch (DbUpdateException exception)
{
//ensure that the detailed error text is saved in the Log
throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
}
}
#region Utilities
/// <summary>
/// Rollback of entity changes and return full error message
/// </summary>
/// <param name="exception">Exception</param>
/// <returns>Error message</returns>
protected string GetFullErrorTextAndRollbackEntityChanges(DbUpdateException exception)
{
//rollback entity changes
if (_context is DbContext dbContext)
{
var entries = dbContext.ChangeTracker.Entries()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified).ToList();
entries.ForEach(entry =>
{
try
{
entry.State = EntityState.Unchanged;
}
catch (InvalidOperationException)
{
// ignored
}
});
}
try
{
_context.SaveChanges();
return exception.ToString();
}
catch (Exception ex)
{
//if after the rollback of changes the context is still not saving,
//return the full text of the exception that occurred when saving
return ex.ToString();
}
}
#endregion
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using System;
using System.Collections.Generic;
using System.Text;
namespace OnTheWay_Data
{
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<OnTheWayDbContext>
{
public OnTheWayDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<OnTheWayDbContext>();
builder.UseSqlServer("Data Source=DESKTOP-S3RA57L;Initial Catalog=onTheWay;Integrated Security=true;",
opt => opt.MigrationsAssembly("OnTheWay_Migrations"));
return new OnTheWayDbContext(builder.Options);
}
}
}
<file_sep># On_the_Way
sample .NET MVC web app for travels
<file_sep>using Microsoft.EntityFrameworkCore.Metadata.Builders;
using OnTheWay_Models.Users;
using System;
using System.Collections.Generic;
using System.Text;
namespace OnTheWay_Data.EntityTypeConfigurations.Users
{
public class UserEntityTipeConfiguration : OnTheWayEntityTypeConfiguration<User>
{
public override void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(u => u.Id);
builder.Property(u => u.Username)
.IsRequired();
builder.Property(u => u.FirstName)
.HasMaxLength(20)
.IsRequired();
builder.Property(u => u.LastName)
.HasMaxLength(15)
.IsRequired();
builder.Property(u => u.Email)
.IsRequired();
builder.Property(u => u.Password)
.IsRequired();
builder.Property(u => u.CreatedOnUTC)
.IsRequired();
base.Configure(builder);
}
}
}
<file_sep>using OnTheWay_Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnTheWay_Data.Repositories.Contracts
{
public interface IRepository<TEntity> where TEntity : BaseEntity
{
IQueryable<TEntity> Table { get; }
Task AddAsync(TEntity entity);
Task AddRangeAsync(IEnumerable<TEntity> entityCollection);
void Update(TEntity entity);
void Remove(TEntity entity);
Task<TEntity> GetByIdAsync(int id);
}
}
<file_sep>using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnTheWay_App.Controllers.Trip
{
public class TripController : Controller
{
public IActionResult Book()
{
return View();
}
public IActionResult GetPackages()
{
return View();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OnTheWay_Data;
using OnTheWay_Data.Contracts;
using Microsoft.EntityFrameworkCore;
using Autofac;
using OnTheWay_Data.Repositories;
using OnTheWay_Data.Repositories.Contracts;
using Autofac.Extensions.DependencyInjection;
namespace OnTheWay_App
{
public class Startup
{
public Startup(IWebHostEnvironment env)
{
// In ASP.NET Core 3.0 `env` will be an IWebHostingEnvironment, not IHostingEnvironment.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public ILifetimeScope AutofacContainer { get; private set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddControllersWithViews();
//services.AddDbContext<IDBContext, OnTheWayDbContext>(options =>
// options.UseSqlServer("Data Source=DESKTOP-S3RA57L;Initial Catalog=onTheWay;Integrated Security=true;"));
}
// ConfigureContainer is where you can register things directly
// with Autofac. This runs after ConfigureServices so the things
// here will override registrations made in ConfigureServices.
// Don't build the container; that gets done for you by the factory.
public void ConfigureContainer(ContainerBuilder builder)
{
//builder.RegisterModule();
builder.RegisterType<DbContextOptions<OnTheWayDbContext>>().AsSelf();
builder.Register(context => new OnTheWayDbContext(context.Resolve<DbContextOptions<OnTheWayDbContext>>()))
.As<IDBContext>().InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
AutofacContainer = app.ApplicationServices.GetAutofacRoot();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseEndpoints(endpointRouteBuilder =>
{
endpointRouteBuilder.MapDefaultControllerRoute();
});
}
}
}
| d2bda18864773bf3df27453ca317717b9c40343c | [
"Markdown",
"C#"
] | 11 | C# | kvadrat4o/On_the_Way | fd5c08e8ab410ae08966ce6ee26c3eb8433bfc1f | b07b6991b2a4be5f9f01c24aa934d08aca818150 |
refs/heads/master | <file_sep>//
// ViewController.swift
// webviewex
//
// Created by i mac on 2016. 11. 13..
// Copyright © 2016년 goplayzig. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myWebView: UIWebView! //웹뷰
let stringURL = "https://www.google.co.kr" //URL 을 나타내는 문자열로 URL 객체 만듬
override func viewDidLoad() {
super.viewDidLoad()
if let Stringurl = URL(string : stringURL) { //지정한 문자열이 URL 형식인 지 확인 (nil 이 아닌지 확인)
let need = URLRequest(url: Stringurl) //Url request
myWebView.loadRequest(need) //웹뷰 요청
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 94b4c52356e6e529ac3f13b2baedf6a0d79b71ff | [
"Swift"
] | 1 | Swift | goplayzig/WebView-ex | ab956cadada56aa27c009d1c635e17d527111239 | 923e36ded2f500f6350846afb2efadbeeec05d8b |
refs/heads/main | <repo_name>RenatoasMedeiros/MedicalChat<file_sep>/Back/src/MedicChat.Domain/model/Medico.cs
using System;
using System.Collections.Generic;
using MedicChat.Domain.Identity;
using Microsoft.AspNetCore.Identity;
namespace MedicChat.Domain.model
{
public class Medico : IdentityUser<int> // O médico é um usuario para login, logo herda as propriedades de IdentityUser
{
public string Nome { get; set; }
public int Telemovel { get; set; }
public string Foto { get; set; }
public DateTime DataNascimento { get; set; }
public string Genero { get; set; }
public string Especialidade { get; set; }
public string Descricao { get; set; }
public string Endereco { get; set; }
public string CodPostal { get; set; }
public List<UserRole> UserRoles { get; set; } //Lista de permições
// Propriedade de Navegação! - Foreing Key
public IEnumerable<VideoChat> VideoChats { get; set; }
}
}
<file_sep>/Back/src/MedicChat.Domain/Identity/UserRole.cs
using MedicChat.Domain.model;
using Microsoft.AspNetCore.Identity;
namespace MedicChat.Domain.Identity
{
public class UserRole : IdentityUserRole<int>
{
public Medico Medico { get; set; }
public Role Role { get; set; }
}
}<file_sep>/Back/src/MedicChat.Application/VideoChatService.cs
using System;
using System.Threading.Tasks;
using AutoMapper;
using MedicChat.Application.Contratos;
using MedicChat.Application.Dtos;
using MedicChat.Domain.model;
using MedicChat.Persistence.Contratos;
namespace MedicChat.Application
{
public class VideoChatService : IVideoChatService
{
private readonly IGeralPersist _geralPersist;
private readonly IVideoChatPersist _videoChatPersist;
private readonly IMapper _mapper;
public VideoChatService(IGeralPersist geralPersist, IVideoChatPersist videoChatPersist, IMapper mapper)
{
_mapper = mapper;
_videoChatPersist = videoChatPersist;
_geralPersist = geralPersist;
}
public async Task<VideoChatDto> AddVideoChat(VideoChatDto model)
{
try
{
// Map do videoChat(Dto) para videoChat(model)
var videoChat = _mapper.Map<VideoChat>(model);
videoChat.DataInicio = videoChat.DataInicio.AddHours(1);
_geralPersist.Add<VideoChat>(videoChat);
if (await _geralPersist.SaveChangesAsync())
{
// Map do videoChat(model) para videoChat(dto)
var videoChatRetorno = await _videoChatPersist.GetVideoChatByIdAsync(videoChat.Id);
return _mapper.Map<VideoChatDto>(videoChatRetorno);
}
return null;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<VideoChatDto> UpdateVideoChat(int videoChatId, VideoChatDto model)
{
try
{
if(model.Relatorio == string.Empty){ // se o relatorio estiver vazio é porque a consulta só foi agendada
model.DataInicio = model.DataInicio.AddHours(1);
}
if(model.Relatorio != string.Empty){ // se o relatorio não estiver vazio é porque a consulta foi finalizada
model.DataFim = model.DataFim.AddHours(1);
}
var videoChat = await _videoChatPersist.GetVideoChatByIdAsync(videoChatId);
if (videoChat == null) return null;
model.Id = videoChat.Id;
_mapper.Map(model, videoChat);
_geralPersist.Update(videoChat);
if (await _geralPersist.SaveChangesAsync())
{
// Map do videoChat(model) para videoChat(dto)
var videoChatRetorno = await _videoChatPersist.GetVideoChatByIdAsync(videoChat.Id);
return _mapper.Map<VideoChatDto>(videoChatRetorno);
}
return null;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<bool> DeleteVideoChat(int videoChatId)
{
try
{
var videoChat = await _videoChatPersist.GetVideoChatByIdAsync(videoChatId);
if (videoChat == null) throw new Exception("Video Chat não foi encontrado.");
_geralPersist.Delete<VideoChat>(videoChat);
return await _geralPersist.SaveChangesAsync();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<VideoChatDto[]> GetAllVideoChatAsync()
{
try
{
var videoChat = await _videoChatPersist.GetAllVideoChatAsync();
if (videoChat == null)
return null;
// Dado o Objeto medicoDto é mapeado as videoChats
var resultado = _mapper.Map<VideoChatDto[]>(videoChat);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<VideoChatDto[]> GetAllVideoChatsByPacienteIdAsync(int pacienteId)
{
try
{
var videoChats = await _videoChatPersist.GetAllVideoChatsByPacienteIdAsync(pacienteId);
if (videoChats == null) return null;
// Dado o Objeto VideoChatDto é mapeado os videoChats
var resultado = _mapper.Map<VideoChatDto[]>(videoChats);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<VideoChatDto[]> GetAllVideoChatsByMedicoIdAsync(int medicoId)
{
try
{
var videoChats = await _videoChatPersist.GetAllVideoChatsByMedicoIdAsync(medicoId);
if (videoChats == null) return null;
// Dado o Objeto VideoChatDto é mapeado os videoChats
var resultado = _mapper.Map<VideoChatDto[]>(videoChats);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<VideoChatDto> GetVideoChatByIdAsync(int videoChatId)
{
try
{
var videoChat = await _videoChatPersist.GetVideoChatByIdAsync(videoChatId);
if (videoChat == null) return null;
// Dado o Objeto medicoDto é mapeado os medicos
var resultado = _mapper.Map<VideoChatDto>(videoChat);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}<file_sep>/Front/MediChat-App/src/app/components/medicos/medico-lista/medico-lista.component.ts
import { Component, OnInit, TemplateRef } from '@angular/core';
import { Router } from '@angular/router';
import { Medico } from '@app/models/Medico';
import { MedicoService } from '@app/services/medico.service';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-medico-lista',
templateUrl: './medico-lista.component.html',
styleUrls: ['./medico-lista.component.scss']
})
export class MedicoListaComponent implements OnInit {
modalRef: BsModalRef;
public medicos: Medico[];
public medicosFiltrados: Medico[] = [];
private _filtroLista: string = '';
public get filtroLista() {
return this._filtroLista;
}
public set filtroLista(value: string) {
this._filtroLista = value;
// Se filtroLista possuir algum valor, filtrarMedico == filtrolista
this.medicosFiltrados = this.filtroLista ? this.filtrarMedicos(this.filtroLista) : this.medicos;
}
public filtrarMedicos(filtrarPor: string): Medico[] {
filtrarPor = filtrarPor.toLocaleLowerCase();
return this.medicos.filter(
medico => medico.nome.toLocaleLowerCase().indexOf(filtrarPor) !== -1 || medico.especialidade.toLocaleLowerCase().indexOf(filtrarPor) !== -1
);
}
constructor(
private medicoService: MedicoService,
private modalService: BsModalService,
private toastr: ToastrService,
private spinner: NgxSpinnerService,
private router: Router
) { }
ngOnInit() {
this.spinner.show();
this.getMedicos();
}
public getMedicos(): void{
this.medicoService.getMedicos().subscribe({
next: (_medicos: Medico[]) => {
this.medicos = _medicos;
this.medicosFiltrados = this.medicos;
},
error: error => {
this.spinner.hide(),
this.toastr.error('Erro ao carregar os Medicos', 'Erro!')
},
complete: () => this.spinner.hide()
});
}
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template, {class: 'modal-sm'});
}
confirm(): void {
this.modalRef.hide();
this.toastr.success('O Medico foi apagado com sucesso!', 'Apagado!');
}
decline(): void {
this.modalRef.hide();
}
infoPaciente(id: number): void {
this.router.navigate([`medicos/informacao/${id}`]);
}
}
<file_sep>/Back/src/MedicChat.Persistence/VideoChatPersist.cs
using System.Linq;
using System.Threading.Tasks;
using MedicChat.Domain.model;
using MedicChat.Persistence.Contextos;
using MedicChat.Persistence.Contratos;
using Microsoft.EntityFrameworkCore;
namespace MedicChat.Persistence
{
public class VideoChatPersist : IVideoChatPersist
{
private readonly MedicChatContext _context;
public VideoChatPersist(MedicChatContext context)
{
_context = context;
}
public async Task<VideoChat[]> GetAllVideoChatAsync()
{
IQueryable<VideoChat> query = _context.VideoChats
.Include(m => m.Medico)
.Include(p => p.Paciente);
query = query.AsNoTracking().OrderBy(m => m.Id);
return await query.ToArrayAsync();
}
public async Task<VideoChat[]> GetAllVideoChatsByPacienteIdAsync(int pacienteId)
{
IQueryable<VideoChat> query = _context.VideoChats
.Include(m => m.Medico)
.Include(p => p.Paciente);
query = query.AsNoTracking()
.Where(videoChat => videoChat.PacienteID == pacienteId);
return await query.ToArrayAsync();
}
public async Task<VideoChat[]> GetAllVideoChatsByMedicoIdAsync(int medicoId)
{
IQueryable<VideoChat> query = _context.VideoChats
.Include(m => m.Medico)
.Include(p => p.Paciente);
query = query.AsNoTracking()
.Where(videoChat => videoChat.MedicoID == medicoId);
return await query.ToArrayAsync();
}
public async Task<VideoChat> GetVideoChatByIdAsync(int videoChatId)
{
IQueryable<VideoChat> query = _context.VideoChats
.Include(m => m.Medico)
.Include(p => p.Paciente);
query = query.AsNoTracking().OrderBy(m => m.Id).Where(m => m.Id == videoChatId);
return await query.FirstOrDefaultAsync();
}
}
}<file_sep>/Front/MediChat-App/src/app/shared/nav/nav.component.ts
import { ToastrService } from 'ngx-toastr';
import { MedicoService } from '@app/services/medico.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { v4 as uuidv4 } from 'uuid';
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.scss']
})
export class NavComponent implements OnInit {
isCollapsed = true;
constructor(
private router: Router,
private medicoService: MedicoService,
private toastr: ToastrService
) { }
ngOnInit() {
}
showMenu(): boolean {
if(localStorage.getItem('token') == null) //Verifica se o utilizador é administrador
return false;
var menu = this.router.url !== '/user/login';
return menu;
}
loggedIn() {
return this.medicoService.loggedIn();
}
entrar() {
this.router.navigate(['/user/login']);
}
logout() {
localStorage.removeItem('token'); // Remove o token da localStorage
localStorage.removeItem('username'); // Remove o username da localStorage
localStorage.removeItem('email'); // Remove o email da localStorage
localStorage.removeItem('id'); // Remove o id da localStorage
this.toastr.show('Log Out efetuado com sucesso.'); // Toastr de Logout
this.router.navigate(['/user/login']); // Redireciona para a pagina de login
}
email(){
return localStorage.getItem('email');
}
public administrador(): boolean {
if(localStorage.getItem('username') == "admin") //Verifica se o utilizador é administrador
return true;
return false; // Se não for retorna False
}
}
<file_sep>/Back/src/MedicChat.Application/Contratos/IMailSenderService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MedicChat.Application.Contratos
{
public interface IMailSenderService
{
void EnviarGmailConsultaAgendada(string recipientEmail, string recipientName, DateTime videochatDateInicio);
void EnviarGmailConsultaIniciada(string recipientEmail, string recipientName, string token, int idConsulta);
}
}<file_sep>/Back/src/MedicChat.Application/Dtos/PacienteDto.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MedicChat.Domain.model;
namespace MedicChat.Application.Dtos
{
public class PacienteDto
{
public int Id { get; set; }
[Required(ErrorMessage ="O campo {0} é obrigatorio.")]
[MinLength(4, ErrorMessage ="O campo deve ter no minimo 4 caracteres.")]
[MaxLength(100, ErrorMessage ="O campo só pode ter 100 caracteres.")]
public string Nome { get; set; }
[Required(ErrorMessage ="O campo {0} é obrigatorio.")]
[EmailAddress(ErrorMessage = "O campo {0} precisa ser um e-mail válido.")]
public string Email { get; set; }
[Required(ErrorMessage ="O campo {0} é obrigatorio.")]
[Phone(ErrorMessage="O campo {0} está com um numero inválido.")]
public string Telemovel { get; set; }
[RegularExpression(@".*\.(gif|jpe?g|bmp|png)$", ErrorMessage = "Não é uma imagem válida. Imagens válidas: (gif, jp(e)g, png ou bmp).")]
public string Foto { get; set; }
[Required(ErrorMessage ="O campo {0} é obrigatorio.")]
public DateTime DataNascimento { get; set; }
public string Genero { get; set; }
[Required(ErrorMessage ="O campo {0} é obrigatorio.")]
[MinLength(6, ErrorMessage ="O campo deve ter no minimo 6 caracteres.")]
[MaxLength(70, ErrorMessage ="O campo só pode ter 70 caracteres.")]
public string Endereco { get; set; }
[Required(ErrorMessage ="O campo {0} é obrigatorio.")]
public string CodPostal { get; set; }
// Propriedade de Navegação!
// public IEnumerable<VideoChat> VideoChats { get; set; }
}
}<file_sep>/Front/MediChat-App/src/app/app-routing.module.ts
import { AuthGuard } from './auth/auth.guard';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './components/user/login/login.component';
import { UserComponent } from './components/user/user.component';
import { RegistarMedicoComponent } from './components/user/registar-medico/registar-medico.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { AgendaComponent } from './components/agenda/agenda.component';
import { AgendaListaComponent } from './components/agenda/agenda-lista/agenda-lista.component';
import { MedicosComponent } from './components/medicos/medicos.component';
import { MedicoListaComponent } from './components/medicos/medico-lista/medico-lista.component';
import { PacientesComponent } from './components/pacientes/pacientes.component';
import { PacienteInformacaoComponent } from './components/pacientes/paciente-informacao/paciente-informacao.component';
import { PacienteListaComponent } from './components/pacientes/paciente-lista/paciente-lista.component';
import { AgendaCriarComponent } from './components/agenda/agenda-criar/agenda-criar.component';
import { VideoChatComponent } from './components/videoChat/videoChat.component';
const routes: Routes = [
{
path: 'user', component: UserComponent,
children: [
{ path: 'login', component: LoginComponent },
{ path: 'registar-medico', component: RegistarMedicoComponent },
]
},
{ path: 'pacientes', redirectTo: 'pacientes/lista' },
{
path: 'pacientes', component: PacientesComponent, canActivate: [AuthGuard],
children: [
{ path: 'informacao/:id', component: PacienteInformacaoComponent, canActivate: [AuthGuard] },
{ path: 'informacao', component: PacienteInformacaoComponent, canActivate: [AuthGuard] },
{ path: 'lista', component: PacienteListaComponent, canActivate: [AuthGuard] },
]
},
{ path: 'medicos', redirectTo: 'medicos/lista' },
{
path: 'medicos', component: MedicosComponent, canActivate: [AuthGuard],
children: [
{ path: 'lista', component: MedicoListaComponent, canActivate: [AuthGuard] },
]
},
{ path: 'agenda', redirectTo: 'agenda/lista' },
{
path: 'agenda', component: AgendaComponent, canActivate: [AuthGuard],
children: [
{ path: 'criar/:id', component: AgendaCriarComponent, canActivate: [AuthGuard] },
{ path: 'criar', component: AgendaCriarComponent, canActivate: [AuthGuard] },
{ path: 'lista', component: AgendaListaComponent, canActivate: [AuthGuard] },
]
},
{ path: 'consulta/:id/:idConsulta', component: VideoChatComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' }, // Rota Raíz da aplicação
{ path: '**', redirectTo: 'dashboard', pathMatch: 'full' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/Front/MediChat-App/src/app/components/agenda/agenda-criar/agenda-criar.component.ts
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { DatePipe } from '@angular/common';
import { PacienteService } from './../../../services/paciente.service';
import { MedicoService } from './../../../services/medico.service';
import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { VideoChat } from '@app/models/VideoChat';
import { VideoChatService } from '@app/services/videoChat.service';
import { BsLocaleService } from 'ngx-bootstrap/datepicker';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { Medico } from '@app/models/Medico';
import { Paciente } from '@app/models/Paciente';
import { v4 as uuidv4 } from 'uuid';
import { Route } from '@angular/compiler/src/core';
@Component({
selector: 'app-agenda-criar',
templateUrl: './agenda-criar.component.html',
styleUrls: ['./agenda-criar.component.scss']
})
export class AgendaCriarComponent implements OnInit {
locale = 'pt'; // idioma português
modalRef: BsModalRef;
public form: FormGroup;
public videoChatId = 0;
public medicos: Medico[] = [];
public pacientes: Paciente[] = [];
medicoId = localStorage.getItem('id');
videoChat = {} as VideoChat;
estadoGuardar = 'post'; // Inicia em post para criar um novo paciente
get modoEditar(): boolean {
return this.estadoGuardar === 'put';
}
get f(): any {
return this.form.controls;
}
get bsConfig(): any {
return {
adaptivePosition: true, // Escolhe uma posição favorável (cima ou baixo)
dateInputFormat: 'DD/MM/YYYY HH:mm', // formatação do input
showWeekNumbers: false // não mostrar os dias da semana
}
}
constructor(
private fb: FormBuilder,
private localeService: BsLocaleService,
private router: ActivatedRoute,
private route: Router,
private videoChatService: VideoChatService,
private medicoService: MedicoService,
private pacienteService: PacienteService,
private spinner: NgxSpinnerService,
private toastr: ToastrService,
private modalService: BsModalService
) { this.localeService.use(this.locale); }
public carregarConsultas(): void {
const videoChatIdParam = this.router.snapshot.paramMap.get('id'); //recebe o id da url
if(videoChatIdParam !== null){ // verifico se o get é diferente de nulo
this.spinner.show(); // ativa o spinner
this.estadoGuardar = 'put';
this.videoChatService.getVideoChatById(+videoChatIdParam).subscribe( // + para converter para o tipo INT, pois o pacienteId é retornado como uma string
{ // subscrive recebe um observable com 3 propriedades
next: (videoChat: VideoChat) => { // realiza uma copia do objeto do parametro e atribui para dentro do paciente
this.videoChat = {...videoChat}; // SPREAD (cada paciente é atribuido aos pacientes)
this.form.patchValue(this.videoChat); // definir os valores recebidos no formulário
},
error: (error: any) => {
this.spinner.hide(); // Esconde o spinner
this.toastr.error('Erro ao tentar carregar as Consultas.'); // Em caso de erro mostra um toaster
console.error(error);
},
complete: () => this.spinner.hide(), // Esconde o spinner
}
)
}
}
public getMedicos(): void{
this.medicoService.getMedicos().subscribe({
next: (_medico: Medico[]) => {
this.medicos = _medico;
},
error: error => {
this.spinner.hide(),
this.toastr.error('Erro ao carregar os Medicos', 'Erro!')
},
complete: () => this.spinner.hide()
});
}
public getPacientes(): void{
this.pacienteService.getPacientes().subscribe({
next: (_paciente: Paciente[]) => {
this.pacientes = _paciente;
},
error: error => {
this.spinner.hide(),
this.toastr.error('Erro ao carregar os Pacientes', 'Erro!')
},
complete: () => this.spinner.hide()
});
}
criarVideoChat(videoChat: VideoChat): FormGroup {
return this.fb.group({
id: [videoChat.id],
relatorio: [videoChat.relatorio, Validators.maxLength(3000)],
token: [videoChat.token],
dataInicio: [videoChat.dataInicio, Validators.required],
dataFim: [""],
estadoVideoChat: [0, Validators.required],
medicoID: [videoChat.medicoID, Validators.required],
pacienteID: [videoChat.pacienteID, Validators.required]
});
};
ngOnInit(): void {
this.carregarConsultas();
this.getMedicos();
this.getPacientes();
this.validation();
}
public validation(): void {
this.form = this.fb.group({
medicoID: [this.medicoId, [Validators.required]],
pacienteID: ['', [Validators.required]],
dataInicio: ['', Validators.required],
relatorio: ['', Validators.maxLength(3000)],
});
}
public resetForm(): void {
this.form.reset();
}
openModal(event: any, template: TemplateRef<any>, videoChatId: number): void {
event.stopPropagation(); // nao propaga o evento do click
this.videoChatId = videoChatId;
this.modalRef = this.modalService.show(template, {class: 'modal-sm'});
}
public cssValidator(campoForm: FormControl): any {
return {'is-invalid': campoForm.errors && campoForm.touched};
}
public guardarVideoChat(): void {
this.spinner.show();
if(this.form.valid) {
this.videoChat = (this.estadoGuardar === 'post')
? {...this.form.value} // atribui ao paciente o formulário (Se o mesmo for válido) (SPREAD OPERATOR)
: { id: this.videoChat.id, ...this.form.value} // atribui ao paciente o formulário, MENOS o Id pois ele tem que se manter visto que é um PUT (Se o mesmo for válido) (SPREAD OPERATOR)
this.videoChatService[this.estadoGuardar](this.videoChat).subscribe(
(videoChatRetorno: VideoChat) => { // NEXT
this.toastr.success('Consulta agendada com Sucesso!', 'Sucesso');
},
(error: any) => {
console.error(error);
this.spinner.hide();
this.toastr.error('Erro ao agendar a consulta', 'Erro');
}, // ERROR
() => this.spinner.hide() // COMPLETE
);
}
}
consultaConcluida(): boolean {
var estado = this.videoChat.estadoVideoChat == 1;
return estado;
}
}
<file_sep>/Front/MediChat-App/src/app/components/pacientes/paciente-lista/paciente-lista.component.ts
import { Router } from '@angular/router';
import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { Paciente } from '@app/models/Paciente';
import { PacienteService } from '@app/services/paciente.service';
@Component({
selector: 'app-paciente-lista',
templateUrl: './paciente-lista.component.html',
styleUrls: ['./paciente-lista.component.scss']
})
export class PacienteListaComponent implements OnInit {
modalRef: BsModalRef;
public pacientes: Paciente[] = [];
public pacientesFiltrados: Paciente[] = [];
public pacienteId = 0;
public widthFoto: number = 50;
public heightFoto: number = 50;
public marginFoto: number = 2;
public exibirFoto: boolean = true;
public mobile: boolean = false;
private _filtroLista: string = '';
public get filtroLista() {
return this._filtroLista;
}
public set filtroLista(value: string) {
this._filtroLista = value;
// Se filtroLista possuir algum valor, filtrarPacientes == filtrolista
this.pacientesFiltrados = this.filtroLista ? this.filtrarPacientes(this.filtroLista) : this.pacientes;
}
public filtrarPacientes(filtrarPor: string): Paciente[] {
filtrarPor = filtrarPor.toLocaleLowerCase();
return this.pacientes.filter(
paciente => paciente.nome.toLocaleLowerCase().indexOf(filtrarPor) !== -1
);
}
constructor(
private pacienteService: PacienteService,
private modalService: BsModalService,
private toastr: ToastrService,
private spinner: NgxSpinnerService,
private router: Router
) { }
public ngOnInit(): void {
this.spinner.show();
this.carregarPacientes();
if (window.screen.width <= 375) {
this.mobile = true;
}
}
public alterarEstadoFoto(): void {
this.exibirFoto = !this.exibirFoto;
}
public carregarPacientes(): void {
this.pacienteService.getPacientes().subscribe({
next: (_pacientes: Paciente[]) => {
this.pacientes = _pacientes;
this.pacientesFiltrados = this.pacientes;
},
error: error => {
this.spinner.hide(),
this.toastr.error('Erro ao carregar os Pacientes', 'Erro!')
},
complete: () => this.spinner.hide()
});
}
openModal(event: any, template: TemplateRef<any>, pacienteId: number): void {
event.stopPropagation(); // nao propaga o evento do click
this.pacienteId = pacienteId;
this.modalRef = this.modalService.show(template, {class: 'modal-sm'});
}
confirm(): void {
this.modalRef.hide();
this.spinner.show();
this.pacienteService.deletePaciente(this.pacienteId).subscribe(
(resultado: any) => { // NEXT
if(resultado.mensagem == 'Apagado'){
this.toastr.success('O Paciente foi apagado com sucesso!', 'Apagado!');
this.carregarPacientes();
}
},
(error: any) => { // ERROR
console.error(error);
this.toastr.error(`Erro ao tentar Apagar o Paciente ${this.pacienteId}`, 'Erro');
}
).add(() => this.spinner.hide());
}
decline(): void {
this.modalRef.hide();
}
infoPaciente(id: number): void {
this.router.navigate([`pacientes/informacao/${id}`]);
}
}
<file_sep>/Front/MediChat-App/src/app/services/medico.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Medico } from '../models/Medico';
import { take, map } from 'rxjs/operators';
import { JwtHelperService } from '@auth0/angular-jwt';
@Injectable(
// {providedIn: 'root'}
)
export class MedicoService {
baseURL = 'https://localhost:5001/api/Medicos';
jwtHelper = new JwtHelperService(); //Service Jwt do angular - Verificar o token
TokenDescodificador: any;
constructor(private http: HttpClient) {}
getMedicos(): Observable<Medico[]> {
return this.http.get<Medico[]>(this.baseURL)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
getMedicosByNome(nome: string): Observable<Medico[]> {
return this.http.get<Medico[]>(`${this.baseURL}/${nome}/nome`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
getMedicosByEspecialidade(especialidade: string): Observable<Medico[]> {
return this.http.get<Medico[]>(`${this.baseURL}/${especialidade}/especialidade`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
getMedicoById(id: number): Observable<Medico> {
return this.http.get<Medico>(`${this.baseURL}/${id}`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
put(medico: Medico): Observable<Medico> {
return this.http.put<Medico>(`${this.baseURL}/${medico.id}`, medico)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
// LOGIN ------------
login(model: Medico) {
return this.http.post(`${this.baseURL}/Login`, model).pipe(
map((response: any) => {
const user = response;
if(user) {
localStorage.setItem('token', user.token);
this.TokenDescodificador = this.jwtHelper.decodeToken(user.token);
localStorage.setItem('username', this.TokenDescodificador.unique_name);
localStorage.setItem('email', this.TokenDescodificador.email);
localStorage.setItem('id', this.TokenDescodificador.nameid);
}
})
);
}
// REGISTAR
registar(medico: Medico) {
return this.http.post<Medico>(this.baseURL, medico)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
loggedIn(){
const token = localStorage.getItem('token');
return this.jwtHelper.isTokenExpired(token);
}
postUpload(file: File, nome: string): Observable<any>{
const fileToUpload = <File>file[0]; //1º posição do file que é um array
const formData = new FormData();
formData.append('file', fileToUpload, nome);
return this.http.post(`${this.baseURL}/uploadImagemMedico`, formData)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
}
<file_sep>/Back/src/MedicChat.API/Controllers/VideoChatController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MedicChat.Application.Contratos;
using MedicChat.Domain.model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Mail;
using Microsoft.Extensions.Logging;
using FluentEmail.Smtp;
using System.Net;
using FluentEmail.Core;
using System.Globalization;
using MedicChat.Application.Dtos;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
namespace MedicChat.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class VideoChatController : ControllerBase
{
private readonly IVideoChatService _videoChatService;
private readonly IMailSenderService _mailSenderService;
private readonly IMapper _mapper;
public VideoChatController(IVideoChatService videoChatService, IMailSenderService mailSenderService, IMapper mapper)
{
_videoChatService = videoChatService;
_mailSenderService = mailSenderService;
_mapper = mapper;
}
[HttpGet]
public async Task<IActionResult> GetAllVideoChatAsync()
{
try
{
var videoChat = await _videoChatService.GetAllVideoChatAsync();
if (videoChat == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return Ok(videoChat);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar videoChat. Erro: {ex.Message}");
}
}
[HttpGet("{id}")]
public async Task<IActionResult> GetVideoChatByIdAsync(int id)
{
try
{
var videoChat = await _videoChatService.GetVideoChatByIdAsync(id);
if (videoChat == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return Ok(videoChat);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar video chamada. Erro: {ex.Message}");
}
}
[HttpGet("paciente/{pacienteId}")]
public async Task<IActionResult> GetAllVideoChatsByPacienteIdAsync(int pacienteId)
{
try
{
var videoChat = await _videoChatService.GetAllVideoChatsByPacienteIdAsync(pacienteId);
if (videoChat == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return Ok(videoChat);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar a Video Chamada. Erro: {ex.Message}");
}
}
[HttpGet("medico/{medicoId}")]
public async Task<IActionResult> GetAllVideoChatsByMedicoIdAsync(int medicoId)
{
try
{
var videoChat = await _videoChatService.GetAllVideoChatsByMedicoIdAsync(medicoId);
if (videoChat == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return Ok(videoChat);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar a Video Chamada. Erro: {ex.Message}");
}
}
[HttpPost]
public async Task<IActionResult> Post(VideoChatDto model)
{
try
{
// Dado o Objeto medicoDto é mapeado os medicos
var videoChat = await _videoChatService.AddVideoChat(model);
videoChat.DataInicio.AddHours(1); // Adiciona 1 hora
if (videoChat == null) return NoContent(); // Retorna StatusCode 204 - NoContent
try
{
_mailSenderService.EnviarGmailConsultaAgendada(videoChat.Paciente.Email, videoChat.Paciente.Nome, videoChat.DataInicio);
}
catch(Exception ex) {
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar adicionar a Video Chamada, email não enviado ao Paciente Erro: {ex.Message}");
}
return Ok(videoChat);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar adicionar a Video Chamada. Erro: {ex.Message}");
}
}
[HttpPut("{id}")]
public async Task<IActionResult> Put(int id, VideoChatDto model)
{
try
{
var videoChat = await _videoChatService.UpdateVideoChat(id, model);
if (videoChat == null) return NoContent(); // Retorna StatusCode 204 - NoContent
try
{
_mailSenderService.EnviarGmailConsultaAgendada(videoChat.Paciente.Email, videoChat.Paciente.Nome, videoChat.DataInicio);
}
catch(Exception ex) {
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar adicionar a Video Chamada, email não enviado ao Paciente Erro: {ex.Message}");
}
return Ok(videoChat);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar atualizar a Video Chamada. Erro: {ex.Message}");
}
}
[HttpPut("enviarEmail/{id}")]
public async Task<IActionResult> PutEnviaEmail(int id, VideoChatDto model)
{
try
{
var videoChat = await _videoChatService.UpdateVideoChat(id, model);
if (videoChat == null) return NoContent(); // Retorna StatusCode 204 - NoContent
try
{
_mailSenderService.EnviarGmailConsultaIniciada(videoChat.Paciente.Email, videoChat.Paciente.Nome, videoChat.Token, videoChat.Id);
}
catch(Exception ex) {
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar adicionar a Video Chamada, email não enviado ao Paciente Erro: {ex.Message}");
}
return Ok(videoChat);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar atualizar a Video Chamada. Erro: {ex.Message}");
}
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
try
{
// Verifica se a Consulta existe
var videoChat = await _videoChatService.GetVideoChatByIdAsync(id);
if (videoChat == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return await _videoChatService.DeleteVideoChat(id)
? Ok(new { mensagem = "Apagado"}) // retorna um objeto para o front end (boa prática)
: throw new Exception("Ocorreu algum problema ao tentar apagar a consulta!");
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar deletar a Video Chamada. Erro: {ex.Message}");
}
}
}
}
<file_sep>/Back/src/MedicChat.API/Controllers/PacientesController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using MedicChat.Application.Contratos;
using MedicChat.Application.Dtos;
using MedicChat.Domain.model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace MedicChat.API.Controllers
{
[ApiController]
[Route("api/[controller]")] // Define a rota
[Authorize] // Todos os EndPoints Percição de autorização
public class PacientesController : ControllerBase
{
private readonly IPacienteService _pacienteService;
public PacientesController(IPacienteService pacienteService)
{
_pacienteService = pacienteService;
}
[HttpGet]
public async Task<IActionResult> Get()
{
try
{
// Atribui a variavel pacientes todos os Pacientes
var pacientes = await _pacienteService.GetAllPacientesAsync();
// Caso não existam pacientes retorna NotFound
if (pacientes == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return Ok(pacientes);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar Pacientes. Erro: {ex.Message}");
}
}
[HttpGet("{id}")]
public async Task<IActionResult> GetById(int id)
{
try
{
var paciente = await _pacienteService.GetPacienteByIdAsync(id);
if (paciente == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return Ok(paciente);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar pacientes. Erro: {ex.Message}");
}
}
[HttpGet("{nome}/nome")]
public async Task<IActionResult> GetByNome(string nome)
{
try
{
var paciente = await _pacienteService.GetAllPacientesByNomeAsync(nome);
if (paciente == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return Ok(paciente);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar o Paciente. Erro: {ex.Message}");
}
}
[HttpGet("{telemovel}/telemovel")]
public async Task<IActionResult> GetByTelemovel(int telemovel)
{
try
{
var paciente = await _pacienteService.GetPacienteByTelemovelAsync(telemovel);
if (paciente == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return Ok(paciente);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar o Paciente. Erro: {ex.Message}");
}
}
[HttpPost]
public async Task<IActionResult> Post(PacienteDto model)
{
try
{
var paciente = await _pacienteService.AddPaciente(model);
if (paciente == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return Ok(paciente);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar adicionar Paciente. Erro: {ex.Message}");
}
}
[HttpPost("uploadImagemPaciente")]
public async Task<IActionResult> Upload()
{
try
{
var arquivo = Request.Form.Files[0]; // Todo o arquivo vem como um array, logo o a variavem arquivo começa no [0]
var nomePasta = Path.Combine("Resources", "ImagensPaciente");
//Caminho onde vai ser salvo
var pathParaSalvar = Path.Combine(Directory.GetCurrentDirectory(), nomePasta);
if(arquivo.Length > 0) // Se o arquivo existir
{
// Nome do arquivo vem do header
var nomeArquivo = ContentDispositionHeaderValue.Parse(arquivo.ContentDisposition).FileName;
var fullPath = Path.Combine(pathParaSalvar, nomeArquivo.Replace("\"", " ").Trim()); //Substitui as aspas duplas por " ", e Trim para remover o espaço
//Guardamos o arquivo no stream
using(var stream = new FileStream(fullPath, FileMode.Create)) {
arquivo.CopyTo(stream);
}
}
return Ok(); // retorna status code 200 (Ok) com o médico
}
catch (Exception ex)
{
// Em caso de exception retorna status code 500 e mostra o erro
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar inserir imagem. Erro: {ex.Message}");
}
}
[HttpPut("{id}")]
public async Task<IActionResult> Put(int id, PacienteDto model)
{
try
{
var paciente = await _pacienteService.UpdatePaciente(id, model);
if (paciente == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return Ok(paciente);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar atualizar Pacientes. Erro: {ex.Message}");
}
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
try
{
// Verifica se o Paciente existe
var paciente = await _pacienteService.GetPacienteByIdAsync(id);
if (paciente == null) return NoContent(); // Retorna StatusCode 204 - NoContent
return await _pacienteService.DeletePaciente(id)
? Ok(new { mensagem = "Apagado"}) // retorna um objeto para o front end (boa prática)
: throw new Exception("Ocorreu algum problema ao tentar apagar o paciente!");
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar deletar Paciente. Erro: {ex.Message}");
}
}
}
}
<file_sep>/Back/src/MedicChat.Persistence/Contratos/IVideoChatPersist.cs
using System.Threading.Tasks;
using MedicChat.Domain.model;
namespace MedicChat.Persistence.Contratos
{
public interface IVideoChatPersist
{
Task<VideoChat[]> GetAllVideoChatAsync();
Task<VideoChat[]> GetAllVideoChatsByPacienteIdAsync(int pacienteId);
Task<VideoChat[]> GetAllVideoChatsByMedicoIdAsync(int medicoId);
Task<VideoChat> GetVideoChatByIdAsync(int videoChatId);
}
}<file_sep>/Back/src/MedicChat.Persistence/Contratos/IMedicoPersist.cs
using System.Threading.Tasks;
using MedicChat.Domain.model;
namespace MedicChat.Persistence.Contratos
{
public interface IMedicoPersist
{
// MEDICOS
Task<Medico[]> GetAllMedicosAsync();
Task<Medico[]> GetAllMedicosByNomeAsync(string nome);
Task<Medico[]> GetAllMedicosByEspecialidadeAsync(string especialidade);
Task<Medico> GetMedicosByIdAsync(int medicoId);
}
}<file_sep>/Back/src/MedicChat.Application/Contratos/IMedicoService.cs
using System.Threading.Tasks;
using MedicChat.Application.Dtos;
using MedicChat.Domain.model;
namespace MedicChat.Application.Contratos
{
public interface IMedicoService
{
Task<MedicoDto> AddMedico(MedicoDto model);
Task<MedicoDto> UpdateMedico(int medicoId, MedicoDto model);
Task<bool> DeleteMedico(int medicoId);
Task<MedicoDto[]> GetAllMedicosAsync();
Task<MedicoDto[]> GetAllMedicosByNomeAsync(string nome);
Task<MedicoDto[]> GetAllMedicosByEspecialidadeAsync(string especialidade);
Task<MedicoDto> GetMedicosByIdAsync(int medicoId);
}
}<file_sep>/Back/src/MedicChat.Application/MedicoService.cs
using System;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using MedicChat.Application.Contratos;
using MedicChat.Application.Dtos;
using MedicChat.Domain.model;
using MedicChat.Persistence.Contratos;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace MedicChat.Application
{
public class MedicoService : IMedicoService
{
private readonly IGeralPersist _geralPersist;
private readonly IMedicoPersist _medicoPersist;
private readonly IMapper _mapper;
private readonly UserManager<Medico> _userManager;
private readonly IConfiguration _configuration;
public MedicoService(IGeralPersist geralPersist, IMedicoPersist medicoPersist, IMapper mapper, IConfiguration configuration, UserManager<Medico> userManager)
{
_configuration = configuration;
_userManager = userManager;
_medicoPersist = medicoPersist;
_geralPersist = geralPersist;
_mapper = mapper;
}
public async Task<MedicoDto> AddMedico(MedicoDto model)
{
try
{
// Map do medico(Dto) para medico(model)
var medico = _mapper.Map<Medico>(model);
medico.UserName = medico.Email;
var result = await _userManager.CreateAsync(medico, model.Password);
if (result.Succeeded) {
_geralPersist.Add<Medico>(medico);
// Map do medico(model) para medico(dto)
var medicoRetorno = await _medicoPersist.GetMedicosByIdAsync(medico.Id);
return _mapper.Map<MedicoDto>(medicoRetorno);
}
return null;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<MedicoDto> UpdateMedico(int medicoId, MedicoDto model)
{
try
{
var medico = await _medicoPersist.GetMedicosByIdAsync(medicoId);
if (medico == null) return null;
model.Id = medico.Id;
_mapper.Map(model, medico);
_geralPersist.Update(medico);
if (await _geralPersist.SaveChangesAsync())
{
// Map do medico(model) para medico(dto)
var medicoRetorno = await _medicoPersist.GetMedicosByIdAsync(medico.Id);
return _mapper.Map<MedicoDto>(medicoRetorno);
}
return null;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<bool> DeleteMedico(int medicoId)
{
try
{
var medico = await _medicoPersist.GetMedicosByIdAsync(medicoId);
if (medico == null) throw new Exception("Medico não foi encontrado.");
_geralPersist.Delete<Medico>(medico);
return await _geralPersist.SaveChangesAsync();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<MedicoDto[]> GetAllMedicosAsync()
{
try
{
var medicos = await _medicoPersist.GetAllMedicosAsync();
if (medicos == null) return null;
// Dado o Objeto medicoDto é mapeado os medicos
var resultado = _mapper.Map<MedicoDto[]>(medicos);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<MedicoDto[]> GetAllMedicosByEspecialidadeAsync(string especialidade)
{
try
{
var medicos = await _medicoPersist.GetAllMedicosByEspecialidadeAsync(especialidade);
if (medicos == null) return null;
// Dado o Objeto medicoDto é mapeado os medicos
var resultado = _mapper.Map<MedicoDto[]>(medicos);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<MedicoDto[]> GetAllMedicosByNomeAsync(string nome)
{
try
{
var medicos = await _medicoPersist.GetAllMedicosByNomeAsync(nome);
if (medicos == null) return null;
// Dado o Objeto medicoDto é mapeado os medicos
var resultado = _mapper.Map<MedicoDto[]>(medicos);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<MedicoDto> GetMedicosByIdAsync(int medicoId)
{
try
{
var medicos = await _medicoPersist.GetMedicosByIdAsync(medicoId);
if (medicos == null) return null;
// Dado o Objeto medicoDto é mapeado os medicos
var resultado = _mapper.Map<MedicoDto>(medicos);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}<file_sep>/Back/src/MedicChat.Domain/model/VideoChat.cs
using System;
using MedicChat.Domain.model.Enums;
namespace MedicChat.Domain.model
{
public class VideoChat
{
public int Id { get; set; }
public string Relatorio { get; set; }
public string Token { get; set; }
public DateTime DataInicio { get; set; }
public DateTime DataFim { get; set; }
public VideoChatStatus EstadoVideoChat { get; set; }
// Propriedade de Navegação!
public int MedicoID { get; set; }
public Medico Medico { get; set; }
public int PacienteID { get; set; }
public Paciente Paciente { get; set; }
}
}<file_sep>/Back/src/MedicChat.Persistence/Contratos/IPacientePersist.cs
using System.Threading.Tasks;
using MedicChat.Domain.model;
namespace MedicChat.Persistence.Contratos
{
public interface IPacientePersist
{
// PACIENTES
Task<Paciente[]> GetAllPacientesAsync();
Task<Paciente[]> GetAllPacientesByNomeAsync(string nome);
Task<Paciente> GetPacienteByIdAsync(int pacienteId);
Task<Paciente> GetPacienteByTelemovelAsync(int telemovel);
}
}<file_sep>/Back/src/MedicChat.Persistence/PacientePersist.cs
using System.Linq;
using System.Threading.Tasks;
using MedicChat.Domain.model;
using MedicChat.Persistence.Contratos;
using MedicChat.Persistence.Contextos;
using Microsoft.EntityFrameworkCore;
namespace MedicChat.Persistence
{
public class PacientePersist : IPacientePersist
{
private readonly MedicChatContext _context;
public PacientePersist(MedicChatContext context)
{
_context = context;
}
public async Task<Paciente[]> GetAllPacientesAsync()
{
IQueryable<Paciente> query = _context.Pacientes;
// .Include(m => m.VideoChats);
query = query.AsNoTracking().OrderBy(p => p.Id);
return await query.ToArrayAsync();
}
public async Task<Paciente[]> GetAllPacientesByNomeAsync(string nome)
{
IQueryable<Paciente> query = _context.Pacientes;
// .Include(m => m.VideoChats);
query = query.AsNoTracking().OrderBy(p => p.Id).Where(p => p.Nome.ToLower().Contains(nome.ToLower()));
return await query.ToArrayAsync();
}
public async Task<Paciente> GetPacienteByIdAsync(int pacienteId)
{
IQueryable<Paciente> query = _context.Pacientes;
// .Include(m => m.VideoChats);
query = query.AsNoTracking().OrderBy(p => p.Id).Where(p => p.Id == pacienteId);
return await query.FirstOrDefaultAsync();
}
public async Task<Paciente> GetPacienteByTelemovelAsync(int telemovel)
{
IQueryable<Paciente> query = _context.Pacientes;
// .Include(m => m.VideoChats);
query = query.AsNoTracking().OrderBy(p => p.Id).Where(p => p.Telemovel == telemovel);
return await query.FirstOrDefaultAsync();
}
}
}<file_sep>/Front/MediChat-App/src/app/services/paciente.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Paciente } from '@app/models/Paciente';
import { take } from 'rxjs/operators';
@Injectable(
// {providedIn: 'root'}
)
export class PacienteService {
baseURL = 'https://localhost:5001/api/pacientes';
constructor(private http: HttpClient) {}
getPacientes(): Observable<Paciente[]> {
return this.http.get<Paciente[]>(this.baseURL)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
getPacientesByNome(nome: string): Observable<Paciente[]> {
return this.http.get<Paciente[]>(`${this.baseURL}/${nome}/nome`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
getPacienteById(id: number): Observable<Paciente> {
return this.http.get<Paciente>(`${this.baseURL}/${id}`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
post(paciente: Paciente[]): Observable<Paciente[]> {
return this.http.post<Paciente[]>(this.baseURL, paciente)
.pipe(take(1)); // Só permite uma chamada
}
put(paciente: Paciente): Observable<Paciente> {
return this.http.put<Paciente>(`${this.baseURL}/${paciente.id}`, paciente)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
deletePaciente(id: number): Observable<any> { // vai receber um objeto
return this.http.delete<any>(`${this.baseURL}/${id}`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
postUpload(file: File, nome: string): Observable<any>{
const fileToUpload = <File>file[0]; //1º posição do file que é um array
const formData = new FormData();
formData.append('file', fileToUpload, nome);
return this.http.post(`${this.baseURL}/uploadImagemPaciente`, formData)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
}
<file_sep>/Back/src/MedicChat.API/Controllers/MedicosController.cs
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using MedicChat.Application.Contratos;
using MedicChat.Application.Dtos;
using MedicChat.Domain.model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Net.Http.Headers;
namespace MedicChat.API.Controllers
{
[ApiController]
[Route("api/[controller]")] // Define a rota
[Authorize] // Todos os EndPoints Percição de autorização
public class MedicosController : ControllerBase
{
private readonly IMedicoService _medicoService;
private readonly IMapper _mapper;
private readonly SignInManager<Medico> _signInManager;
private readonly UserManager<Medico> _userManager;
private readonly IConfiguration _configuration;
public MedicosController(IMedicoService medicoService, IMapper mapper, UserManager<Medico> userManager, SignInManager<Medico> signInManager, IConfiguration configuration)
{
_configuration = configuration;
_userManager = userManager;
_signInManager = signInManager;
_mapper = mapper;
_medicoService = medicoService;
}
[HttpGet]
public async Task<IActionResult> Get()
{
try
{
// Atribui a medicos todos os médicos atravez do serviço _medicoService
var medicos = await _medicoService.GetAllMedicosAsync();
if (medicos == null) return NoContent(); // Retorna StatusCode 204 - NoContent Caso o medico seja null
return Ok(medicos); // retorna status code 200 (Ok) com o médico
}
catch (Exception ex)
{
// Em caso de exception retorna status code 500 e mostra o erro
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar medicos. Erro: {ex.Message}");
}
}
[HttpGet("{id}")]
public async Task<IActionResult> GetById(int id) // Id do Médico
{
try
{
// Atribui a medico o médico dono do id passado, atravez do serviço _medicoService
var medico = await _medicoService.GetMedicosByIdAsync(id);
if (medico == null) return NoContent(); // Retorna StatusCode 204 - NoContent Caso o medico seja null
return Ok(medico); // retorna status code 200 (Ok) com o médico
}
catch (Exception ex)
{
// Em caso de exception retorna status code 500 e mostra o erro
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar medicos. Erro: {ex.Message}");
}
}
[HttpGet("{especialidade}/especialidade")]
public async Task<IActionResult> GetByEspecialidade(string especialidade) // Especialidade do Médico
{
try
{
// Atribui a medicos todos os médicos com a especialidade passada como parametro, atravez do serviço _medicoService
var medicos = await _medicoService.GetAllMedicosByEspecialidadeAsync(especialidade);
if (medicos == null) return NoContent(); // Retorna StatusCode 204 - NoContent Caso o medico seja null
return Ok(medicos); // retorna status code 200 (Ok) com o médico
}
catch (Exception ex)
{
// Em caso de exception retorna status code 500 e mostra o erro
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar medicos. Erro: {ex.Message}");
}
}
[HttpGet("{nome}/nome")]
public async Task<IActionResult> GetByNome(string nome) // Nome do Médico
{
try
{
// Atribui a medicos todos os médicos com o nome passada como parametro, atravez do serviço _medicoService
var medico = await _medicoService.GetAllMedicosByNomeAsync(nome);
if (medico == null) return NoContent(); // Retorna StatusCode 204 - NoContent Caso o medico seja null
return Ok(medico); // retorna status code 200 (Ok) com o médico
}
catch (Exception ex)
{
// Em caso de exception retorna status code 500 e mostra o erro
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar recuperar medicos. Erro: {ex.Message}");
}
}
[HttpPost]
[Authorize(Roles = "Admin")] //Sómente utilizadores com permição de Admin podem realizar este endpoint
public async Task<IActionResult> Post(MedicoDto model) // Recebe como parametro um MedicoDto
{
try
{
// Atribui a medico todo o model do MedicoDto passado como parametro
var medico = await _medicoService.AddMedico(model);
if (medico == null) return NoContent(); // Retorna StatusCode 204 - NoContent Caso o medico seja null
return Ok(medico); // retorna status code 200 (Ok) com o médico
}
catch (Exception ex)
{
// Em caso de exception retorna status code 500 e mostra o erro
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar adicionar medicos. Erro: {ex.Message}");
}
}
[HttpPost("uploadImagemMedico")]
public async Task<IActionResult> Upload()
{
try
{
var arquivo = Request.Form.Files[0]; // Todo o arquivo vem como um array, logo o a variavem arquivo começa no [0]
var nomePasta = Path.Combine("Resources", "ImagensMedico");
//Caminho onde vai ser salvo
var pathParaSalvar = Path.Combine(Directory.GetCurrentDirectory(), nomePasta);
if(arquivo.Length > 0) // Se o arquivo existir
{
// Nome do arquivo vem do header
var nomeArquivo = ContentDispositionHeaderValue.Parse(arquivo.ContentDisposition).FileName;
var fullPath = Path.Combine(pathParaSalvar, nomeArquivo.Replace("\"", " ").Trim()); //Substitui as aspas duplas por " ", e Trim para remover o espaço
//Guardamos o arquivo no stream
using(var stream = new FileStream(fullPath, FileMode.Create)) {
arquivo.CopyTo(stream);
}
}
return Ok(); // retorna status code 200 (Ok) com o médico
}
catch (Exception ex)
{
// Em caso de exception retorna status code 500 e mostra o erro
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar inserir imagem. Erro: {ex.Message}");
}
}
[HttpPut("{id}")] // Editar o médico
public async Task<IActionResult> Put(int id, MedicoDto model) // Recebe o id do médico e um model do Tipo MedicoDto
{
try
{
var medico = await _medicoService.UpdateMedico(id, model);
if (medico == null) return NoContent(); // Retorna StatusCode 204 - NoContent Caso o medico seja null
return Ok(medico); // retorna status code 200 (Ok) com o médico
}
catch (Exception ex)
{
// Em caso de exception retorna status code 500 e mostra o erro
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar atualizar medicos. Erro: {ex.Message}");
}
}
[HttpDelete("{id}")] // Eliminar o médico
public async Task<IActionResult> Delete(int id)
{
try
{
// Verifica se o Medico existe
var medico = await _medicoService.GetMedicosByIdAsync(id);
if (medico == null) return NoContent(); // Retorna StatusCode 204 - NoContent Caso o medico seja null
return await _medicoService.DeleteMedico(id)
? Ok(new { mensagem = "Apagado" }) // retorna um objeto para o front end (boa prática)
: throw new Exception("Ocorreu algum problema ao tentar apagar o Médico!");
}
catch (Exception ex)
{
// Em caso de exception retorna status code 500 e mostra o erro
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar deletar medicos. Erro: {ex.Message}");
}
}
[HttpPost("Login")]
[AllowAnonymous] // Permite o acesso a quem não está com sessão iniciada no MediChat
public async Task<IActionResult> Login(MedicoLoginDto model)
{
try
{
var medico = await _userManager.FindByEmailAsync(model.Email); // Procura na base de dados o Email
var result = await _signInManager.CheckPasswordSignInAsync(medico, model.Password, true); // Verifica de a password corresponde
if (result.Succeeded) // caso o resultado dê sucesso
{
var appMedico = await _userManager.Users.FirstOrDefaultAsync(m => m.NormalizedEmail == model.Email.ToUpper()); //Verificamos na base de dados o email que coincida com o email indiciado
var medicoRetorno = _mapper.Map<MedicoLoginDto>(appMedico);
return Ok(new
{
token = GenerateJWToken(appMedico).Result, // gera o token - .Result é IMPORTANTE (resultado da Task)
medico = medicoRetorno // Atribuimos a medico todasas propriedades do medicoRetorno
});
}
return Unauthorized(); // caso os dados estejam incorretos
}
catch (Exception ex)
{
// Em caso de exception retorna status code 500 e mostra o erro
return this.StatusCode(StatusCodes.Status500InternalServerError,
$"Erro ao tentar efetuar o login. Erro: {ex.Message}");
}
}
private async Task<string> GenerateJWToken(Medico medico)
{
try
{
var claims = new List<Claim> //Lista de claims
{
//Passam no token o ID do médico, o nome e o email
new Claim(ClaimTypes.NameIdentifier, medico.Id.ToString()),
new Claim(ClaimTypes.Name, medico.Nome),
new Claim(ClaimTypes.Email, medico.Email)
};
var roles = await _userManager.GetRolesAsync(medico); // atribui a variavel roles todas a roles do medico
// Percorre todas as roles
foreach (var role in roles) {
claims.Add(new Claim(ClaimTypes.Role, role));
}
// Chave (appsettings.json) com Enconding numa sequência de Bytes
var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:Token").Value));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); // Gera uma Hash Message Authentication Code (Hmac) Sha512(hash de 512 bits) com a chave
// informações do token
var tokenDescriptor = new SecurityTokenDescriptor {
Subject = new ClaimsIdentity(claims), // Passa as claims ("informações" do medico na token)
Expires = DateTime.Now.AddHours(12), // 12 horas para a token expirar
SigningCredentials = creds // as credenciais (a chave)
};
var tokenHandler = new JwtSecurityTokenHandler(); // Para poder criar e escrever a token
var token = tokenHandler.CreateToken(tokenDescriptor); // Cria a token com a sua descrição
return tokenHandler.WriteToken(token); // retorna a token
}
catch (System.Exception)
{
throw; // Lança a exception
}
}
}
}
<file_sep>/Front/MediChat-App/src/app/services/web-socket.service.ts
import { Injectable, EventEmitter } from '@angular/core';
import { Socket } from 'ngx-socket-io'; // Importamos o socket io
@Injectable({
providedIn: 'root'
})
export class WebSocketService {
events = ['new-user','bye-user']; // Todos os eventos possiveis
callbackEvent: EventEmitter<any> = new EventEmitter<any>();
constructor(private socket: Socket) {
this.listener();
}
listener = () => { // lê os eventos que o servidor emite
this.events.forEach(eventName => {
this.socket.on(eventName, data => this.callbackEvent.emit({
name: eventName,
data: data
}));
});
};
//Envia a informação do usuario
joinRoom = (data) => {
this.socket.emit('join', data); // emite um join e as informações (data)
}
}
<file_sep>/Back/src/MedicChat.Application/Dtos/VideoChatDto.cs
using System;
using System.ComponentModel.DataAnnotations;
using MedicChat.Domain.model;
using MedicChat.Domain.model.Enums;
namespace MedicChat.Application.Dtos
{
public class VideoChatDto
{
public int Id { get; set; }
public string Relatorio { get; set; }
public string Token { get; set; }
[Required(ErrorMessage ="O campo {0} é obrigatorio")]
public DateTime DataInicio { get; set; }
public DateTime DataFim { get; set; }
[Required(ErrorMessage ="O campo {0} é obrigatorio")]
public VideoChatStatus EstadoVideoChat { get; set; }
// Propriedade de Navegação!
[Required(ErrorMessage ="O campo {0} é obrigatorio")]
public int MedicoID { get; set; }
public Medico Medico { get; set; }
[Required(ErrorMessage ="O campo {0} é obrigatorio")]
public int PacienteID { get; set; }
public Paciente Paciente { get; set; }
}
}<file_sep>/Back/src/MedicChat.Application/Contratos/IPacienteService.cs
using System.Threading.Tasks;
using MedicChat.Application.Dtos;
namespace MedicChat.Application.Contratos
{
public interface IPacienteService
{
Task<PacienteDto> AddPaciente(PacienteDto model);
Task<PacienteDto> UpdatePaciente(int pacienteId, PacienteDto model);
Task<bool> DeletePaciente(int pacienteId);
Task<PacienteDto[]> GetAllPacientesAsync();
Task<PacienteDto[]> GetAllPacientesByNomeAsync(string nome);
Task<PacienteDto> GetPacienteByIdAsync(int pacienteId);
Task<PacienteDto> GetPacienteByTelemovelAsync(int telemovel);
}
}<file_sep>/Back/src/MedicChat.Application/PacienteService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using MedicChat.Application.Contratos;
using MedicChat.Application.Dtos;
using MedicChat.Domain.model;
using MedicChat.Persistence.Contratos;
namespace MedicChat.Application
{
public class PacienteService : IPacienteService
{
private readonly IGeralPersist _geralPersist;
private readonly IPacientePersist _pacientePersist;
private readonly IMapper _mapper;
public PacienteService(IGeralPersist geralPersist, IPacientePersist pacientePersist, IMapper mapper)
{
_pacientePersist = pacientePersist;
_geralPersist = geralPersist;
_mapper = mapper;
}
public async Task<PacienteDto> AddPaciente(PacienteDto model)
{
try
{
// Map do paciente(Dto) para paciente(model)
var paciente = _mapper.Map<Paciente>(model);
_geralPersist.Add<Paciente>(paciente);
if (await _geralPersist.SaveChangesAsync())
{
// Map do paciente(model) para paciente(dto)
var pacienteRetorno = await _pacientePersist.GetPacienteByIdAsync(paciente.Id);
return _mapper.Map<PacienteDto>(pacienteRetorno);
}
return null;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<PacienteDto> UpdatePaciente(int pacienteId, PacienteDto model)
{
try
{
var paciente = await _pacientePersist.GetPacienteByIdAsync(pacienteId);
if (paciente == null) return null;
model.Id = paciente.Id;
_mapper.Map(model, paciente);
_geralPersist.Update<Paciente>(paciente);
if (await _geralPersist.SaveChangesAsync())
{
// Map do paciente(model) para paciente(dto)
var pacienteRetorno = await _pacientePersist.GetPacienteByIdAsync(paciente.Id);
return _mapper.Map<PacienteDto>(pacienteRetorno);
}
return null;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<bool> DeletePaciente(int pacienteId)
{
try
{
var paciente = await _pacientePersist.GetPacienteByIdAsync(pacienteId);
if (paciente == null) throw new Exception("Paciente não foi encontrado.");
_geralPersist.Delete<Paciente>(paciente);
return await _geralPersist.SaveChangesAsync();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<PacienteDto[]> GetAllPacientesAsync()
{
try
{
var pacientes = await _pacientePersist.GetAllPacientesAsync();
if (pacientes == null) return null;
// Dado o Objeto array PacienteDto é mapeado os pacientes
var resultado = _mapper.Map<PacienteDto[]>(pacientes);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<PacienteDto> GetPacienteByTelemovelAsync(int telemovel)
{
try
{
var pacientes = await _pacientePersist.GetPacienteByTelemovelAsync(telemovel);
if (pacientes == null) return null;
// Dado o Objeto PacienteDto é mapeado os paceintes
var resultado = _mapper.Map<PacienteDto>(pacientes);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<PacienteDto[]> GetAllPacientesByNomeAsync(string nome)
{
try
{
var pacientes = await _pacientePersist.GetAllPacientesByNomeAsync(nome);
if (pacientes == null) return null;
// Dado o Objeto PacienteDto é mapeado os paceintes
var resultado = _mapper.Map<PacienteDto[]>(pacientes);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<PacienteDto> GetPacienteByIdAsync(int PacienteId)
{
try
{
var pacientes = await _pacientePersist.GetPacienteByIdAsync(PacienteId);
if (pacientes == null) return null;
// Dado o Objeto PacienteDto é mapeado os paceintes
var resultado = _mapper.Map<PacienteDto>(pacientes);
return resultado;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}<file_sep>/Front/MediChat-App/src/app/models/VideoChat.ts
import { Medico } from './Medico';
import { Paciente } from './Paciente';
import { VideoChatStatus } from './VideoChatStatus';
export interface VideoChat {
id: number;
relatorio: string;
token: string;
dataInicio: Date;
dataFim: Date;
estadoVideoChat: VideoChatStatus;
medicoID: number;
medico: Medico;
pacienteID: number;
paciente: Paciente;
}
<file_sep>/Front/MediChat-App/src/app/models/Paciente.ts
import { VideoChat } from './VideoChat';
export interface Paciente {
id: number;
nome: string;
email: string;
telemovel: string;
foto: string;
dataNascimento: Date;
genero: string;
endereco: string;
codPostal: string;
videoChats: VideoChat;
}
<file_sep>/Back/src/MedicChat.Application/Contratos/IVideoChatService.cs
using System.Threading.Tasks;
using MedicChat.Application.Dtos;
using MedicChat.Domain.model;
namespace MedicChat.Application.Contratos
{
public interface IVideoChatService
{
Task<VideoChatDto> AddVideoChat(VideoChatDto model);
Task<VideoChatDto> UpdateVideoChat(int videoChatId, VideoChatDto model);
Task<bool> DeleteVideoChat(int videoChatId);
Task<VideoChatDto[]> GetAllVideoChatAsync();
Task<VideoChatDto[]> GetAllVideoChatsByPacienteIdAsync(int pacienteId);
Task<VideoChatDto[]> GetAllVideoChatsByMedicoIdAsync(int medicoId);
Task<VideoChatDto> GetVideoChatByIdAsync(int videoChatId);
}
}<file_sep>/Front/MediChat-App/src/app/app.module.ts
import { AuthInterceptor } from './auth/auth.interceptor';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ClipboardModule } from '@angular/cdk/clipboard';
import { CommonModule } from '@angular/common';
import { CollapseModule } from 'ngx-bootstrap/collapse';
import { TooltipModule } from 'ngx-bootstrap/tooltip';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { ModalModule } from 'ngx-bootstrap/modal';
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
import { SocketIoConfig, SocketIoModule } from 'ngx-socket-io';
// CONFIGURAÇÕES DO DATEPICKER
import { defineLocale } from 'ngx-bootstrap/chronos';
import { ptBrLocale } from 'ngx-bootstrap/locale';
import { ToastrModule } from 'ngx-toastr';
import { NgxSpinnerModule } from 'ngx-spinner';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
// SERVICES
import { PacienteService } from './services/paciente.service';
import { MedicoService } from './services/medico.service';
import { VideoChatService } from './services/videoChat.service';
// HELPERS
import { DateTimeFormatPipe } from './helpers/DateTimeFormat.pipe';
import { DatePlusHourFormatPipe } from './helpers/DatePlusHourFormat.pipe';
// COMPONENTS
import { AgendaCriarComponent } from './components/agenda/agenda-criar/agenda-criar.component';
import { AgendaListaComponent } from './components/agenda/agenda-lista/agenda-lista.component';
import { AgendaComponent } from './components/agenda/agenda.component';
import { VideoChatPlayerComponent } from './components/videoChat/videoChat-player/videoChat-player.component';
import { VideoChatComponent } from './components/videoChat/videoChat.component';
import { MedicoListaComponent } from './components/medicos/medico-lista/medico-lista.component';
import { MedicosComponent } from './components/medicos/medicos.component';
import { PacientesComponent } from './components/pacientes/pacientes.component';
import { PacienteListaComponent } from './components/pacientes/paciente-lista/paciente-lista.component';
import { PacienteInformacaoComponent } from './components/pacientes/paciente-informacao/paciente-informacao.component';
import { UserComponent } from './components/user/user.component';
import { LoginComponent } from './components/user/login/login.component';
import { RegistarMedicoComponent } from './components/user/registar-medico/registar-medico.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
// COMPONENTES PARTILHADOS
import { NavComponent } from './shared/nav/nav.component';
import { TituloComponent } from './shared/titulo/titulo.component';
import { WebSocketService } from './services/web-socket.service';
import { PeerService } from './services/peer.service';
// socket io na porta 3000
const config: SocketIoConfig = { url: 'http://localhost:3000', options: {withCredentials: '*'}}; // Sem credenciais
defineLocale('pt', ptBrLocale);
@NgModule({
declarations: [
AppComponent,
MedicosComponent,
PacientesComponent,
PacienteInformacaoComponent,
AgendaComponent,
DashboardComponent,
NavComponent,
TituloComponent,
DateTimeFormatPipe,
DatePlusHourFormatPipe,
PacienteListaComponent,
MedicoListaComponent,
UserComponent,
LoginComponent,
RegistarMedicoComponent,
AgendaListaComponent,
AgendaCriarComponent,
VideoChatComponent,
VideoChatPlayerComponent,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
CollapseModule.forRoot(),
TooltipModule.forRoot(),
BsDropdownModule.forRoot(),
BsDatepickerModule.forRoot(),
ModalModule.forRoot(),
ToastrModule.forRoot({
timeOut: 3000,
positionClass: 'toast-bottom-right',
preventDuplicates: true,
progressBar: true
}),
NgxSpinnerModule,
ClipboardModule,
SocketIoModule.forRoot(config)
],
providers: [PacienteService, MedicoService, VideoChatService, WebSocketService, PeerService, {provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi:true }], //multi para tratar de multiplas requisições
bootstrap: [AppComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }
<file_sep>/Back/src/MedicChat.Persistence/Contextos/MedicChatContext.cs
using Microsoft.EntityFrameworkCore;
using MedicChat.Domain.model;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using MedicChat.Domain.Identity;
using Microsoft.AspNetCore.Identity;
namespace MedicChat.Persistence.Contextos
{
public class MedicChatContext : IdentityDbContext<Medico, Role, int,
IdentityUserClaim<int>,
UserRole,
IdentityUserLogin<int>,
IdentityRoleClaim<int>,
IdentityUserToken<int>>
{
public MedicChatContext(DbContextOptions<MedicChatContext> options) : base(options) { }
public DbSet<Medico> Medicos { get; set; }
public DbSet<Paciente> Pacientes { get; set; }
public DbSet<VideoChat> VideoChats { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// NECESSARIO PARA O IDENTITY CORE ENTENDER
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<UserRole>(userRole =>{
userRole.HasKey(ur => new {ur.UserId, ur.RoleId}); // MedicoRole key tem que respeirar o novo objeto
/// POSSO TER UM PAPEL COM MAIS DE UM USUARIO
userRole.HasOne(ur => ur.Role) // temos a entidade Role
.WithMany(r => r.UserRoles) // uma entidade role possui varios UserRoles
.HasForeignKey(ur => ur.RoleId) // possui chave estrangeira RoleId
.IsRequired(); //É obrigatorio
// POSSO TER UM USUARIO COM MAIS DE UM PAPEL
userRole.HasOne(ur => ur.Medico) // temos a entidade Medico
.WithMany(r => r.UserRoles) // uma entidade role possui varios UserRoles
.HasForeignKey(ur => ur.UserId) // possui chave estrangeira UserId
.IsRequired(); //É obrigatorio
});
}
}
}<file_sep>/Back/src/MedicChat.Application/Helpers/MedicChatProfile.cs
using AutoMapper;
using MedicChat.Application.Dtos;
using MedicChat.Domain.model;
namespace MedicChat.Application.Helpers
{
public class MedicChatProfile : Profile
{
public MedicChatProfile()
{
// Paciente -> PacienteDto (Criação do Map)
CreateMap<Paciente, PacienteDto>().ReverseMap();
// Medico -> MedicoDto (Criação do Map)
CreateMap<Medico, MedicoDto>().ReverseMap();
// VideoChat -> VideoChatDto (Criação do Map)
CreateMap<VideoChat, VideoChatDto>().ReverseMap();
// Medico -> MedicoLoginDto (Criação do Map)
CreateMap<Medico, MedicoLoginDto>().ReverseMap();
}
}
}<file_sep>/Front/MediChat-App/src/app/components/videoChat/videoChat.component.ts
import { VideoChatService } from './../../services/videoChat.service';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute } from "@angular/router";
import { PeerService } from '@app/services/peer.service';
import { WebSocketService } from '@app/services/web-socket.service';
import { VideoChat } from '@app/models/VideoChat';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';
import { setHours } from 'ngx-bootstrap/chronos/utils/date-setters';
@Component({
selector: 'app-videoChat',
templateUrl: './videoChat.component.html',
styleUrls: ['./videoChat.component.scss']
})
export class VideoChatComponent implements OnInit {
roomName: string; // id (hash) da sala
currentStream: any;
listUser: Array<any> = [];
videoChat = {} as VideoChat;
videoChatIdParam = this.route.snapshot.paramMap.get('id');
dataFim = new Date().toISOString();
public form: FormGroup;
get f(): any {
return this.form.controls;
}
constructor(private route: ActivatedRoute,
private webSocketService: WebSocketService,
private peerService: PeerService,
private fb: FormBuilder,
private spinner: NgxSpinnerService,
private toastr: ToastrService,
private videoChatService: VideoChatService
) { this.roomName = route.snapshot.paramMap.get('idConsulta'); }
ngOnInit(): void {
this.checkMediaDevices();
this.initPeer();
this.initSocket();
if(localStorage.getItem('token') != null) this.carregarConsulta(); // se nao existir token nao chama carregarConsulta
this.validation();
}
initPeer = () => {
const {peer} = this.peerService;
peer.on('open', (id) => {
const body = {
idPeer: id,
roomName: this.roomName
};
this.webSocketService.joinRoom(body);
});
peer.on('call', callEnter => {
callEnter.answer(this.currentStream); // Responde a stream
callEnter.on('stream', (streamRemote) => {
this.addVideoUser(streamRemote); // adiciona o novo usuario
});
}, err => {
console.log('*** ERRO *** Peer call ', err);
});
}
// Iniciamos o socket
initSocket = () => {
this.webSocketService.callbackEvent.subscribe(res => {
if (res.name === 'new-user') {
const {idPeer} = res.data;
this.sendCall(idPeer, this.currentStream);
}
})
}
checkMediaDevices = () => { //Verifica se exite camera
if (navigator && navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({ // Dados do usuario
audio: false, // Audio desativado (APRESENTAÇÃO)
video: true // Video Ativado
}).then(stream => {
this.currentStream = stream;
this.addVideoUser(stream); // Adicionamos um usuarios com Esses Dispositivos Media
}).catch(() => {
console.log('*** ERROR *** Sem Permição');
});
} else {
console.log('*** ERROR *** Sem Dispositivos Media');
}
}
addVideoUser = (stream: any) => {
this.listUser.push(stream);
const unique = new Set(this.listUser);
this.listUser = [...unique];
}
sendCall = (idPeer, stream) => {
const newUserCall = this.peerService.peer.call(idPeer, stream);
if (!!newUserCall) { //verifica se existe o evento
newUserCall.on('stream', (userStream) => {
this.addVideoUser(userStream); // Adiicona o novo usuario
})
}
}
public carregarConsulta(): void {
if(this.videoChatIdParam !== null){ // verifico se o get é diferente de nulo
this.spinner.show(); // ativa o spinner
this.videoChatService.getVideoChatById(+this.videoChatIdParam).subscribe( // + para converter para o tipo INT, pois o pacienteId é retornado como uma string
{ // subscrive recebe um observable com 3 propriedades
next: (videoChat: VideoChat) => { // realiza uma copia do objeto do parametro e atribui para dentro do paciente
this.videoChat = {...videoChat}; // SPREAD (cada paciente é atribuido aos pacientes)
this.form.patchValue(this.videoChat); // definir os valores recebidos no formulário
},
error: (error: any) => {
this.spinner.hide(); // Esconde o spinner
this.toastr.error('Erro ao tentar carregar as Consultas.'); // Em caso de erro mostra um toaster
console.error(error);
},
complete: () => this.spinner.hide(), // Esconde o spinner
}
)
}
}
public validation(): void {
this.form = this.fb.group({
relatorio: ['', Validators.maxLength(3000)],
dataInicio: [this.videoChat.dataInicio, Validators.required],
medicoID: [this.videoChat.medicoID, Validators.required],
pacienteID: [this.videoChat.pacienteID, Validators.required]
});
}
public cssValidator(campoForm: FormControl): any {
return {'is-invalid': campoForm.errors && campoForm.touched};
}
public guardarVideoChat(): void {
this.spinner.show();
if(this.form.valid) {
this.videoChat = { id: +this.videoChatIdParam, estadoVideoChat: 1, token: this.roomName, dataFim: this.dataFim, ...this.form.value} // atribui ao paciente o formulário, MENOS o Id pois ele tem que se manter visto que é um PUT (Se o mesmo for válido) (SPREAD OPERATOR)
console.log(this.videoChat);
this.videoChatService.put(this.videoChat).subscribe(
(videoChatRetorno: VideoChat) => { // NEXT
this.toastr.success('Consulta Finalizada com Sucesso!', 'Sucesso');
},
(error: any) => {
console.error(error);
this.spinner.hide();
this.toastr.error('Erro ao agendar a consulta', 'Erro');
}, // ERROR
() => this.spinner.hide() // COMPLETE
);
}
}
public enviarEmail(): void {
this.videoChat = { id: +this.videoChatIdParam, token: this.roomName, ...this.form.value} // atribui ao paciente o formulário, MENOS o Id pois ele tem que se manter visto que é um PUT (Se o mesmo for válido) (SPREAD OPERATOR)
console.log(this.videoChat);
this.videoChatService.putEnviaEmail(this.videoChat).subscribe(
(videoChatRetorno: VideoChat) => { // NEXT
this.toastr.success('E-mail enviado com Sucesso!', 'Sucesso');
},
(error: any) => {
console.error(error);
this.spinner.hide();
this.toastr.error('Erro ao enviar E-mail', 'Erro');
}, // ERROR
() => this.spinner.hide() // COMPLETE
);
}
showForm(): boolean {
if(localStorage.getItem('token') == null) //Verifica se é um utilizador
return false;
return true;
}
}
<file_sep>/Front/MediChat-App/src/app/components/user/login/login.component.ts
import { MedicoService } from '@app/services/medico.service';
import { ToastrService } from 'ngx-toastr';
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
model: any = {};
constructor(
public router: Router,
public toastr: ToastrService,
public medicoService: MedicoService,
public spinner: NgxSpinnerService
) { }
ngOnInit(): void {
if (localStorage.getItem('token') != null){
this.router.navigate(['/dashboard']);
}
}
login(){
this.spinner.show();
this.medicoService.login(this.model).subscribe(
next => {
this.router.navigate(['/dashboard']);
this.toastr.success('Login efetuado com sucesso!');
},
error => {
this.spinner.hide();
this.toastr.error('Falha ao tentar fazer Login!', 'Erro');
},
() => this.spinner.hide()
)
}
}
<file_sep>/Back/src/MedicChat.API/Startup.cs
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using MedicChat.Persistence.Contextos;
using MedicChat.Application.Contratos;
using MedicChat.Application;
using MedicChat.Persistence.Contratos;
using MedicChat.Persistence;
using System.Net.Mail;
using System.Net;
using Microsoft.AspNetCore.Identity;
using MedicChat.Domain.Identity;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using MedicChat.Domain.model;
using Microsoft.Extensions.FileProviders;
using System.IO;
using Microsoft.AspNetCore.Http;
namespace MedicChat.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MedicChatContext>(
context => context.UseSqlServer(Configuration.GetConnectionString("DefaultPortatil"))
);
// builder receber do service um user
IdentityBuilder builder = services.AddIdentityCore<Medico>(options => {
options.Password.RequiredLength = 8;
});
builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
builder.AddEntityFrameworkStores<MedicChatContext>(); // Levar em consideração o contexto para trabalhar com o resto
builder.AddRoleValidator<RoleValidator<Role>>(); // RoleValidator -> Dominio Role
builder.AddRoleManager<RoleManager<Role>>(); // RoleManager -> Dominio Role
builder.AddSignInManager<SignInManager<Medico>>(); // // SignInManager -> Dominio Medico
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true, // Validação pela assinatura da chave do emissor
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)), // Key que está a ser validada
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddControllers()
.AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
// Declaração do automapper (Dentro do domino da aplicação procurra os Assemblies que referenciem o AutoMapper)
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
// Declaração de todos os Escopos da aplicação
services.AddScoped<IGeralPersist, GeralPersist>();
services.AddScoped<IMedicoService, MedicoService>();
services.AddScoped<IMedicoPersist, MedicoPersist>();
services.AddScoped<IPacienteService, PacienteService>();
services.AddScoped<IPacientePersist, PacientePersist>();
services.AddScoped<IVideoChatService, VideoChatService>();
services.AddScoped<IVideoChatPersist, VideoChatPersist>();
services.AddScoped<IMailSenderService, MailSenderService>();
var from = Configuration.GetSection("Mail")["From"];
var gmailSender = Configuration.GetSection("Gmail")["Sender"];
var gmailPassword = Configuration.GetSection("Gmail")["Password"];
services.AddFluentEmail(gmailSender, from).AddSmtpSender(new SmtpClient("smtp.gmail.com") {
UseDefaultCredentials = false,
//Porta para o Gmail
Port = 587,
//Credenciais do Email de Envio
Credentials = new NetworkCredential(gmailSender,gmailPassword),
EnableSsl = true,
});
services.AddCors();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MedicChat.API", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MedicChat.API v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(x => x.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin());
// Usar arquivos estaticos
app.UseStaticFiles(new StaticFileOptions() {
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Resources")),
RequestPath = new PathString("/Resources")
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
});
}
}
}
<file_sep>/Back/src/MedicChat.Domain/model/Enums/VideoChatStatus.cs
namespace MedicChat.Domain.model.Enums
{
public enum VideoChatStatus : int
{
Agendada = 0,
Concluida = 1,
}
}<file_sep>/Front/MediChat-App/src/app/components/pacientes/paciente-informacao/paciente-informacao.component.ts
import { tap } from 'rxjs/internal/operators/tap';
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators, AbstractControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { PacienteService } from '@app/services/paciente.service';
import { Paciente } from '@app/models/Paciente';
import { VideoChatService } from '@app/services/videoChat.service';
import { VideoChat } from '@app/models/VideoChat';
import { BsLocaleService } from 'ngx-bootstrap/datepicker';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';
@Component({
selector: 'app-paciente-informacao',
templateUrl: './paciente-informacao.component.html',
styleUrls: ['./paciente-informacao.component.scss']
})
export class PacienteInformacaoComponent implements OnInit {
paciente = {} as Paciente; // inicializar paciente do tipo Paciente
pacienteId: number;
form: FormGroup;
estadoGuardar = 'post'; // Inicia em post para criar um novo paciente
locale = 'pt'; // idioma português
file: File;
fileNameParaUpdate: string;
get modoEditar(): boolean {
return this.estadoGuardar === 'put';
}
get videoChats(): FormArray { // retorna as Video Chamadas
return this.form.get('videoChats') as FormArray;
}
get f(): any {
return this.form.controls;
}
get bsConfig(): any {
return {
adaptivePosition: true, // Escolhe uma posição favorável (cima ou baixo)
dateInputFormat: 'DD/MM/YYYY', // formatação do input
showWeekNumbers: false // não mostrar os dias da semana
};
}
get bsConfigVideoChat(): any {
return {
adaptivePosition: true, // Escolhe uma posição favorável (cima ou baixo)
dateInputFormat: 'DD/MM/YYYY HH:mm', // formatação do input
showWeekNumbers: false // não mostrar os dias da semana
};
}
constructor (private fb: FormBuilder,
private localeService: BsLocaleService,
private activatedRouter: ActivatedRoute,
private pacienteService: PacienteService,
private spinner: NgxSpinnerService,
private toaster: ToastrService,
private router: Router,
private videoChatService :VideoChatService
) { this.localeService.use(this.locale); }
public carregarPaciente(): void {
this.pacienteId = +this.activatedRouter.snapshot.paramMap.get('id');
if(this.pacienteId !== null && this.pacienteId !== 0){ // verifico se o get é diferente de nulo
this.spinner.show(); // ativa o spinner
this.estadoGuardar = 'put'; // PUT pois vai editar
this.pacienteService.getPacienteById(this.pacienteId).subscribe( // + para converter para o tipo INT, pois o pacienteId é retornado como uma string
{ // subscrive recebe um observable com 3 propriedades
next: (paciente: Paciente) => { // realiza uma copia do objeto do parametro e atribui para dentro do paciente
this.paciente = {...paciente}; // SPREAD (cada paciente é atribuido aos pacientes)
this.fileNameParaUpdate = paciente.foto.toString(); // fileNameParaUpdate recebe o string da imagem
this.paciente.foto = ''; // inicia a foto do paciente em branco
this.form.patchValue(this.paciente); // definir os valores recebidos no formulário
this.carregarVideoChats();
},
error: (error: any) => {
this.spinner.hide(); // Esconde o spinner
this.toaster.error('Erro ao tentar carregar os Pacientes.'); // Em caso de erro mostra um toaster
console.error(error);
},
complete: () => this.spinner.hide(), // Esconde o spinner
}
)
}
}
public carregarVideoChats(): void {
this.videoChatService.getVideoChatsByPacienteId(this.pacienteId).subscribe(
(videoChatsRetorno: VideoChat[]) => {
videoChatsRetorno.forEach(videoChat => {
this.videoChats.push(this.criarVideoChat(videoChat));
});
},
(error) => {
this.toaster.error('Erro ao tentar carregar as Consultas', 'Erro')
console.error(error);
},
).add(() => this.spinner.hide());
}
ngOnInit(): void {
this.carregarPaciente();
this.validation();
}
public validation(): void {
this.form = this.fb.group({
nome: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(100)]],
email: ['', [Validators.required, Validators.email]],
telemovel: ['', [Validators.required]],
foto: [''],
dataNascimento: ['', Validators.required],
genero: ['', Validators.required],
endereco: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(70)]],
codPostal: ['', Validators.required],
videoChats: this.fb.array([])
});
}
criarVideoChat(videoChat: VideoChat): FormGroup {
return this.fb.group({
id: [videoChat.id],
relatorio: [videoChat.relatorio],
token: [videoChat.token],
dataInicio: [videoChat.dataInicio, Validators.required],
dataFim: [videoChat.dataFim],
estadoVideoChat: [videoChat.estadoVideoChat, Validators.required],
medico: [videoChat.medico.nome, Validators.required],
paciente: [videoChat.paciente.nome, Validators.required]
});
};
public resetForm(): void {
this.form.reset();
}
public cssValidator(campoForm: FormControl | AbstractControl): any {
return {'is-invalid': campoForm.errors && campoForm.touched};
}
onFileChange(event){
const reader = new FileReader();
// Verifica se é um arquivo e se ela possui tamanho
if (event.target.files && event.target.files.length) {
this.file = event.target.files; // atribuimos o arquivo a variavel file
}
}
uploadImagem(): void {
const nomeArquivo = this.paciente.foto.split('\\', 3); //Split na barra EX: [C:, imagens, foto.png]
this.paciente.foto = nomeArquivo[2];
this.pacienteService.postUpload(this.file, nomeArquivo[2]).subscribe();
}
public guardarPaciente(): void {
this.spinner.show();
if(this.form.valid) {
this.paciente = (this.estadoGuardar === 'post')
? {...this.form.value} // atribui ao paciente o formulário (Se o mesmo for válido) (SPREAD OPERATOR)
: { id: this.paciente.id, ...this.form.value} // atribui ao paciente o formulário, MENOS o Id pois ele tem que se manter visto que é um PUT (Se o mesmo for válido) (SPREAD OPERATOR)
this.uploadImagem();
this.pacienteService[this.estadoGuardar](this.paciente).subscribe(
(pacienteRetorno: Paciente) => { // NEXT
this.toaster.success('Paciente guardado com Sucesso!', 'Sucesso');
},
(error: any) => {
console.error(error);
this.spinner.hide();
this.toaster.error('Erro ao guardar o Paciente', 'Erro');
}, // ERROR
() => this.spinner.hide() // COMPLETE
);
}
}
}
<file_sep>/Front/MediChat-App/src/app/models/VideoChatStatus.ts
export enum VideoChatStatus {
Agendada = 0,
Concluida = 1,
}
<file_sep>/Back/src/MedicChat.Application/MailSenderService.cs
using System;
using System.Collections.Generic;
using MedicChat.Application.Contratos;
using Microsoft.Extensions.DependencyInjection;
using FluentEmail.Core;
namespace MedicChat.Application
{
public class MailSenderService : IMailSenderService
{
private readonly IServiceProvider _serviceProvider;
private readonly IVideoChatService _videoChatService;
public MailSenderService(IServiceProvider serviceProvider, IVideoChatService videoChatService)
{
_serviceProvider = serviceProvider;
_videoChatService = videoChatService;
}
public void SendHtmlGmail(string recipientEmail, string recipientName)
{
throw new System.NotImplementedException();
}
public async void EnviarGmailConsultaAgendada(string recipientEmail, string recipientName, DateTime videochatDate)
{
try {
using (var scope = _serviceProvider.CreateScope()) {
var mailer = scope.ServiceProvider.GetRequiredService<IFluentEmail>();
var email = mailer
.To(recipientEmail, recipientName)
.Subject("MediChat " + recipientName + " - Consulta Agendada")
.Body("Olá "+ recipientName +", a sua consulta foi agendada no dia " + videochatDate.Day + "/"
+ videochatDate.Month + "/"
+ videochatDate.Year + " às "
+ videochatDate.Hour + ":"
+ videochatDate.Minute + "."
);
await email.SendAsync();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async void EnviarGmailConsultaIniciada(string recipientEmail, string recipientName, string token, int idConsulta)
{
try {
using (var scope = _serviceProvider.CreateScope()) {
var mailer = scope.ServiceProvider.GetRequiredService<IFluentEmail>();
var email = mailer
.To(recipientEmail, recipientName)
.Subject("MediChat " + recipientName + " - Consulta Agendada")
.Body("Olá "+ recipientName +", a sua consulta já se encontra ativa! Por favor entre em: http://localhost:4200/consulta/"+idConsulta+"/"+token);
await email.SendAsync();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}<file_sep>/Front/MediChat-App/src/app/services/videoChat.service.ts
import { VideoChat } from '@app/models/VideoChat';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { take } from 'rxjs/operators';
@Injectable(
// providedIn: 'root'
)
export class VideoChatService {
baseURL = 'https://localhost:5001/api/VideoChat';
constructor(private http: HttpClient) {}
getVideoChats(): Observable<VideoChat[]> {
return this.http.get<VideoChat[]>(this.baseURL)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
getVideoChatsByPacienteId(pacienteId: number): Observable<VideoChat[]> {
return this.http.get<VideoChat[]>(`${this.baseURL}/paciente/${pacienteId}`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
getVideoChatsByMedicoId(medicoId: number): Observable<VideoChat[]> {
return this.http.get<VideoChat[]>(`${this.baseURL}/medico/${medicoId}`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
getVideoChatsByNomePaciente(nomePaciente: string): Observable<VideoChat[]> {
return this.http.get<VideoChat[]>(`${this.baseURL}/${nomePaciente}/nome`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
getVideoChatById(id: number): Observable<VideoChat> {
return this.http.get<VideoChat>(`${this.baseURL}/${id}`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
post(videoChat: VideoChat[]): Observable<VideoChat[]> {
return this.http.post<VideoChat[]>(this.baseURL, videoChat)
.pipe(take(1)); // Só permite uma chamada
}
put(videoChat: VideoChat): Observable<VideoChat> {
return this.http.put<VideoChat>(`${this.baseURL}/${videoChat.id}`, videoChat)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
putEnviaEmail(videoChat: VideoChat): Observable<VideoChat> {
return this.http.put<VideoChat>(`${this.baseURL}/enviarEmail/${videoChat.id}`, videoChat)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
deleteVideoChat(id: number): Observable<any> { // vai receber um objeto
return this.http.delete<any>(`${this.baseURL}/${id}`)
.pipe(take(1)); // Só permite uma chamada - depois dá unsubscrive
}
}
<file_sep>/Front/MediChat-App/src/app/components/dashboard/dashboard.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
constructor() { }
ngOnInit() {
}
userName(){
var nome = localStorage.getItem('username');
return (nome.split(" ")[0] + " " + nome.split(" ")[nome.split(" ").length - 1]); // retorna o primeiro e o ultimo nome do utilizador
}
}
<file_sep>/Front/MediChat-App/src/app/components/user/registar-medico/registar-medico.component.ts
import { MedicoService } from '@app/services/medico.service';
import { Medico } from './../../../models/Medico';
import { ValidatorField } from './../../../helpers/ValidatorField';
import { AbstractControlOptions, FormBuilder, FormControl, FormGroup, Validators, FormsModule } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { Spinner } from 'ngx-spinner/lib/ngx-spinner.enum';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { Router } from '@angular/router';
@Component({
selector: 'app-registar-medico',
templateUrl: './registar-medico.component.html',
styleUrls: ['./registar-medico.component.scss']
})
export class RegistarMedicoComponent implements OnInit {
public form: FormGroup;
medico: Medico;
file: File;
get f(): any {
return this.form.controls;
}
constructor(
private fb: FormBuilder,
private spinner: NgxSpinnerService,
private toaster: ToastrService,
private router: Router,
private medicoService: MedicoService
) { }
ngOnInit(): void {
this.validation();
}
public validation(): void {
const formOptions: AbstractControlOptions = {
validators: ValidatorField.MustMatch('password', 'confirmarPassword')
};
this.form = this.fb.group({
nome: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(100)]],
email: ['', [Validators.required, Validators.email]],
telemovel: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(15)]],
especialidade: ['', Validators.required],
foto: [''],
endereco: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(70)]],
codPostal: ['', Validators.required],
password: ['', [Validators.required, Validators.pattern('(?=\\D*\\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=.*[$@#$!%*?&]).{8,30}')]],
confirmarPassword: ['',Validators.required]
}, formOptions);
}
onFileChange(event){
const reader = new FileReader();
// Verifica se é um arquivo e se ela possui tamanho
if (event.target.files && event.target.files.length) {
this.file = event.target.files; // atribuimos o arquivo a variavel file
}
}
uploadImagem(): void {
const nomeArquivo = this.medico.foto.split('\\', 3); //Split na barra EX: [C:, imagens, foto.png]
this.medico.foto = nomeArquivo[2];
this.medicoService.postUpload(this.file, nomeArquivo[2]).subscribe();
}
public registarMedico() {
this.spinner.show();
if(this.form.valid) { //verifica se o formulario está válido
this.medico = {...this.form.value};
this.uploadImagem();
this.medicoService.registar(this.medico).subscribe(
next => {
this.router.navigate(['/user/login']);
this.toaster.success('Registo realizado com Sucesso.')
}, // NEXT
error => {
const erro = error.error;
console.error(error);
this.spinner.hide();
erro.forEach(element => {
switch (element.code) {
case 'DuplicateUserName':
this.toaster.error('O Endereço de email já foi cadastrado', 'Erro');
break;
default:
this.toaster.error(`Erro ao registar o Médico! CODE: ${element.code}`, 'Erro');
break;
}
});
}, // ERROR
() => this.spinner.hide() // COMPLETE
)
}
}
public cssValidator(campoForm: FormControl): any {
return {'is-invalid': campoForm.errors && campoForm.touched};
}
}
<file_sep>/Back/src/MedicChat.Persistence/MedicoPersist.cs
using System.Linq;
using System.Threading.Tasks;
using MedicChat.Domain.model;
using MedicChat.Persistence.Contratos;
using MedicChat.Persistence.Contextos;
using Microsoft.EntityFrameworkCore;
namespace MedicChat.Persistence
{
public class MedicoPersist : IMedicoPersist
{
private readonly MedicChatContext _context;
public MedicoPersist(MedicChatContext context)
{
_context = context;
}
public async Task<Medico[]> GetAllMedicosAsync()
{
IQueryable<Medico> query = _context.Medicos
.Include(m => m.VideoChats);
query = query.AsNoTracking().OrderBy(m => m.Id);
return await query.ToArrayAsync();
}
public async Task<Medico[]> GetAllMedicosByEspecialidadeAsync(string especialidade)
{
IQueryable<Medico> query = _context.Medicos
.Include(m => m.VideoChats);
query = query.AsNoTracking().OrderBy(m => m.Id).Where(m => m.Especialidade.ToLower().Contains(especialidade.ToLower()));
return await query.ToArrayAsync();
}
public async Task<Medico[]> GetAllMedicosByNomeAsync(string nome)
{
IQueryable<Medico> query = _context.Medicos
.Include(m => m.VideoChats);
query = query.AsNoTracking().OrderBy(m => m.Id).Where(m => m.UserName.ToLower().Contains(nome.ToLower()));
return await query.ToArrayAsync();
}
public async Task<Medico> GetMedicosByIdAsync(int medicoId)
{
IQueryable<Medico> query = _context.Medicos
.Include(m => m.VideoChats);
query = query.AsNoTracking().OrderBy(m => m.Id).Where(m => m.Id == medicoId);
return await query.FirstOrDefaultAsync();
}
}
}<file_sep>/Front/MediChat-App/src/app/components/videoChat/videoChat-player/videoChat-player.component.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-videoChat-player',
templateUrl: './videoChat-player.component.html',
styleUrls: ['./videoChat-player.component.scss']
})
export class VideoChatPlayerComponent implements OnInit {
@Input() stream: any;
constructor() { }
ngOnInit() {
}
}
<file_sep>/Front/MediChat-App/src/app/components/agenda/agenda-lista/agenda-lista.component.ts
import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { VideoChat } from '@app/models/VideoChat';
import { VideoChatService } from '@app/services/videoChat.service';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';
import { Router } from '@angular/router';
import { v4 as uuidv4 } from 'uuid';
@Component({
selector: 'app-agenda-lista',
templateUrl: './agenda-lista.component.html',
styleUrls: ['./agenda-lista.component.scss']
})
export class AgendaListaComponent implements OnInit {
modalRef: BsModalRef;
public videoChat: VideoChat[] = [];
public videoChatFiltrada: VideoChat[] = [];
public videoChatId = 0;
medicoId = localStorage.getItem('id');
public mobile: boolean = false;
private _filtroLista: string = '';
public get filtroLista() {
return this._filtroLista;
}
public set filtroLista(value: string) {
this._filtroLista = value;
// Se filtroLista possuir algum valor, filtrarVideoChat == filtrolista
this.videoChatFiltrada = this.filtroLista ? this.filtrarVideoChat(this.filtroLista) : this.videoChat;
}
public filtrarVideoChat(filtrarPor: string): VideoChat[] {
filtrarPor = filtrarPor.toLocaleLowerCase();
return this.videoChat.filter(
videoChat => videoChat.medico.username.toLocaleLowerCase().indexOf(filtrarPor) !== -1 ||
videoChat.paciente.nome.toLocaleLowerCase().indexOf(filtrarPor) !== -1
);
}
constructor(
private videoChatService: VideoChatService,
private modalService: BsModalService,
private toastr: ToastrService,
private spinner: NgxSpinnerService,
private router: Router
) { }
ngOnInit(): void {
this.spinner.show();
if(this.medicoId != "3"){ // Id do ADMINISTRADOR
this.GetVideoChatsByMedicoId();
} else {
this.getVideoChats();
}
if (window.screen.width >= 375) {
this.mobile = true;
}
}
public getVideoChats(): void {
this.videoChatService.getVideoChats().subscribe({
next: (_videoChat: VideoChat[]) => {
this.videoChat = _videoChat;
this.videoChatFiltrada = this.videoChat;
},
error: error => {
this.spinner.hide(),
this.toastr.error('Erro ao carregar as Consultas', 'Erro!')
},
complete: () => this.spinner.hide()
});
}
// Carrega todas as Consultas do medico logado
public GetVideoChatsByMedicoId(): void {
this.videoChatService.getVideoChatsByMedicoId(+this.medicoId).subscribe( // + para converter para int
(videoChatsRetorno: VideoChat[]) => {
videoChatsRetorno.forEach(videoChat => {
this.videoChat = videoChatsRetorno;
this.videoChatFiltrada = this.videoChat;
});
},
(error) => {
this.toastr.error('Erro ao tentar carregar as Consultas', 'Erro')
console.error(error);
},
).add(() => this.spinner.hide());
};
openModal(event: any, template: TemplateRef<any>, videoChatId: number): void {
event.stopPropagation(); // nao propaga o evento do click
this.videoChatId = videoChatId;
this.modalRef = this.modalService.show(template, {class: 'modal-sm'});
}
confirmIniciarConsulta(id: number): void {
this.modalRef.hide();
this.router.navigate([`consulta/${id}/${uuidv4()}`]);
}
confirm(): void {
this.modalRef.hide();
this.spinner.show();
this.videoChatService.deleteVideoChat(this.videoChatId).subscribe(
(resultado: any) => { // NEXT
if(resultado.mensagem == 'Apagado'){
this.toastr.success('A Consulta foi apagada com sucesso!', 'Apagado!');
this.GetVideoChatsByMedicoId(); // volta a buscar todas as consultas do medico
}
},
(error: any) => { // ERROR
console.error(error);
this.toastr.error(`Erro ao tentar Apagar a Consultas ${this.videoChatId}`, 'Erro');
}
).add(() => this.spinner.hide());
}
decline(): void {
this.modalRef.hide();
}
infoVideoChat(id: number): void {
this.router.navigate([`agenda/informacao/${id}`]);
}
editarVideoChat(id: number): void {
this.router.navigate([`agenda/criar/${id}`]);
}
}
<file_sep>/Back/src/MedicChat.Domain/model/Paciente.cs
using System;
using System.Collections.Generic;
namespace MedicChat.Domain.model
{
public class Paciente
{
public int Id { get; set; }
public string Nome { get; set; }
public string Email { get; set; }
public int Telemovel { get; set; }
public string Foto { get; set; }
public DateTime DataNascimento { get; set; }
public string Genero { get; set; }
public string Endereco { get; set; }
public string CodPostal { get; set; }
// Propriedade de Navegação! - Foreing key
public IEnumerable<VideoChat> VideoChats { get; set; }
}
} | d95c7c34df0a2dd9d716a725b1e5421b6c14c9e2 | [
"C#",
"TypeScript"
] | 47 | C# | RenatoasMedeiros/MedicalChat | 4ff4ad93ddb3d4ac7c3dee3ef3effe4072922c60 | 7d2b86324928ef5b0b73ce980d478142b235dc1f |
refs/heads/master | <file_sep>nome = input()
salario = float(input())
vendas = float(input())
comissao = vendas*15/100
print('TOTAL = R${:.2f}'.format(salario+comissao))
<file_sep>n = 10*[0]
v = int(input())
for i in range(len(n)):
n[i] = v
v = v * 2
print(f'N[{i}] = {n[i]}')
<file_sep>n = int(input())
horas_trab = int(input())
valor = float(input())
print('NUMBER = {}'.format(n))
print('SALARY = U$ {:.2f}'.format(horas_trab*valor))
<file_sep>N1,N2,N3,N4 = input().split()
N1,N2,N3,N4 = float(N1),float(N2),float(N3),float(N4)
media = ((N1*2) + (N2*3) + (N3*4) + (N4*1)) / 10
print('Media: {:.1f}'.format(media))
if media >= 7.0:
print('Aluno aprovado.')
elif media >= 5.0 and media < 7.0:
print('Aluno em exame.')
exame = float(input() )
print('Nota do exame: {:.1f}'.format(exame))
media_final = (media + exame) / 2
if media_final >= 5:
print('Aluno aprovado.')
print('Media final: {:.1f}'.format(media_final))
else:
print('Aluno reprovado.')
print('Media final: {:.1f}'.format(media_final))
else:
print('Aluno reprovado.')
<file_sep>a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
par = 0
if a % 2 == 0:
par += 1
if b % 2 == 0:
par += 1
if c % 2 == 0:
par += 1
if d % 2 == 0:
par += 1
if e % 2 == 0:
par += 1
print('{} valores pares'.format(par))
<file_sep>x1,y1 = input().split()
x2,y2 = input().split()
x1 = float(x1)
x2 = float(x2)
y1 = float(y1)
y2 = float(y2)
distancia = ((x2-x1)**2 + (y2-y1)**2) **(1/2)
print('{:.4f}'.format(distancia))
<file_sep>X = int(input())
if 1 <= X <= 1000:
for i in range(X+1):
if i % 2 == 1:
print(i)
<file_sep>total = 0
c = 0
idade = 1
while idade > 0:
idade = int(input())
if idade > 0:
c += 1
total += idade
media = total / c
print(f'{media:.2f}')
<file_sep>n = float(input())
if n >= 0 and n <= 25:
print('Intervalo {}'.format('[0,25]'))
elif n > 25 and n <= 50:
print('Intervalo {}'.format('(25,50]'))
elif n > 50 and n <= 75:
print('Intervalo {}'.format('(50,75]'))
elif n > 75 and n <= 100 :
print('Intervalo {}'.format('(75,100]'))
else:
print('Fora de intervalo')
<file_sep>n = 1000*[0]
v = int(input())
x = 0
for i in range(len(n)):
n[i] = x
x += 1
if x == v:
x = 0
print(f'N[{i}] = {n[i]}')
<file_sep>n = int(input())
x = n -1
f = n
if 0 < n < 13:
while x > 0:
f *= x
x -= 1
print(f)
<file_sep>A = float(input())
A = (A /11 * 3.5)
B = float(input())
B = (B / 11) * 7.5
media = (A + B)
print(f'MEDIA = {media:.5f}')
<file_sep>x = int(input()) #distancia km
y = float(input()) #combustivel
consumo_medio = x/y
print('{:.3f} km/l'.format(consumo_medio))
<file_sep>n = int(input())
c = 0
for i in range(1,n+1):
p = int(input())
for x in range(1,p+1):
if p % x == 0:
c += 1
if c == 2:
print(f'{p} eh primo')
c = 0
else:
print(f'{p} nao eh primo')
c = 0
<file_sep>n = int(input())
for i in range(n):
k = int(input())
for o in range(k):
categoria = input()
if categoria == "1":
print("Rolien")
elif categoria== "2":
print("Naej")
elif categoria == "3":
print("Elehcim")
else:
print("Odranoel")
<file_sep>A,B,C = input().split()
A = float(A)
B = float(B)
C = float(C)
triangulo = (A*C)/2
circulo = (C**2)*3.14159
trapezio = ((A+B)*C)/2
quadrado = B*B
retangulo = A*B
print('TRIANGULO: {:.3f}'.format(triangulo))
print('CIRCULO: {:.3f}'.format(circulo))
print('TRAPEZIO: {:.3f}'.format(trapezio))
print('QUADRADO: {:.3f}'.format(quadrado))
print('RETANGULO: {:.3f}'.format(retangulo))
<file_sep>n = int(input())
c = 1
p = 0
for i in range(n):
x = int(input())
while c < x:
if x % c == 0:
p += c
c += 1
if p == x:
print(f'{x} eh perfeito')
c = 1
p = 0
else:
print(f'{x} nao eh perfeito')
c = 1
p = 0
<file_sep>while True:
try:
n = int(input())
epr = 0
ehd = 0
intruso = 0
if 1<=n<=100000:
for i in range(n):
a = input().lower()
if 'epr' in a:
epr += 1
elif 'ehd' in a:
ehd += 1
else:
intruso += 1
print(f'EPR: {epr}')
print(f'EHD: {ehd}')
print(f'INTRUSOS: {intruso}')
except EOFError:
break
<file_sep>maria = 0
joao = 0
pontos = 0
for i in range(int(input())):
for o in range(3):
a,b = input().split()
a,b = int(a),int(b)
pontos = a*b
joao += pontos
for o in range(3):
a,b = input().split()
a,b = int(a),int(b)
pontos = a*b
maria += pontos
if joao > maria:
print(f'JOAO')
maria = 0
joao = 0
else:
print(f'MARIA')
maria = 0
joao = 0
<file_sep>x = 10*[0]
c = 0
while c < 10:
x[c] = int(input())
if x[c] <= 0:
x[c] = 1
c += 1
for i in range(0,c):
print(f'X[{i}] = {x[i]}')
<file_sep>x = 0
maior = 0
for i in range(0,100):
x = int(input())
if x > maior:
maior = x
posicao = i + 1
print(maior)
print(posicao)
| b1bd72898b2a1cd37650edcb2f5e42775f036bba | [
"Python"
] | 21 | Python | NataliaTavares/Exercicios-URI-Python | 98687758cd89fc6a397534c89c43b80e10816d8d | 55c0cc13c322a570175fc66411467bff817734b8 |
refs/heads/master | <file_sep>package com.w17714m.biblioteca.infraestructura.configuracion;
import com.w17714m.biblioteca.dominio.repositorio.RepositorioLibro;
import com.w17714m.biblioteca.dominio.repositorio.RepositorioPrestamo;
import com.w17714m.biblioteca.dominio.servicio.bibliotecario.ServicioBibliotecario;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanServicio {
@Bean
public ServicioBibliotecario servicioCrearUsuario2(RepositorioLibro repositorioLibro, RepositorioPrestamo repositorioPrestamo) {
return new ServicioBibliotecario(repositorioLibro, repositorioPrestamo);
}
}
<file_sep>
package com.w17714m.biblioteca.dominio.unitaria;
import com.w17714m.biblioteca.dominio.Libro;
import com.w17714m.biblioteca.dominio.repositorio.RepositorioLibro;
import com.w17714m.biblioteca.dominio.repositorio.RepositorioPrestamo;
import com.w17714m.biblioteca.dominio.servicio.bibliotecario.ServicioBibliotecario;
import com.w17714m.biblioteca.dominio.util.Utils;
import com.w17714m.biblioteca.testdatabuilder.LibroTestDataBuilder;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ServicioBibliotecarioTest {
@Test
public void libroYaEstaPrestadoTest() {
// arrange
Libro libro = new LibroTestDataBuilder().build();
RepositorioPrestamo repositorioPrestamo = mock(RepositorioPrestamo.class);
RepositorioLibro repositorioLibro = mock(RepositorioLibro.class);
when(repositorioPrestamo.obtenerLibroPrestadoPorIsbn(libro.getIsbn())).thenReturn(libro);
ServicioBibliotecario servicioBibliotecario = new ServicioBibliotecario(repositorioLibro, repositorioPrestamo);
// act
boolean existeProducto = servicioBibliotecario.esPrestado(libro.getIsbn());
//assert
assertTrue(existeProducto);
}
@Test
public void libroNoEstaPrestadoTest() {
// test deploy
// arrange
Libro libro = new LibroTestDataBuilder().build();
RepositorioPrestamo repositorioPrestamo = mock(RepositorioPrestamo.class);
RepositorioLibro repositorioLibro = mock(RepositorioLibro.class);
when(repositorioPrestamo.obtenerLibroPrestadoPorIsbn(libro.getIsbn())).thenReturn(null);
ServicioBibliotecario servicioBibliotecario = new ServicioBibliotecario(repositorioLibro, repositorioPrestamo);
// act
boolean existeProducto = servicioBibliotecario.esPrestado(libro.getIsbn());
//assert
assertFalse(existeProducto);
}
@Test
public void max15DiasTest() {
//assert
assertTrue(
Utils.calcularDiasSinDomingos(
LocalDate.of(2017,05,24),14)
.equals(LocalDate.of(2017,06,9))
);
assertTrue(
Utils.calcularDiasSinDomingos(
LocalDate.of(2017,05,26),14)
.equals(LocalDate.of(2017,06,12))
);
}
}
<file_sep>package com.w17714m.biblioteca.aplicacion.fabrica;
import com.w17714m.biblioteca.aplicacion.comando.ComandoPrestamo;
import com.w17714m.biblioteca.dominio.Prestamo;
public class FabricaPrestamo {
public Prestamo crearPrestamo(ComandoPrestamo comandoPrestamo) {
return new Prestamo(
comandoPrestamo.getFechaSolicitud(),
comandoPrestamo.getLibro(),
comandoPrestamo.getFechaEntregaMaxima(),
comandoPrestamo.getNombreUsuario()
);
}
}
<file_sep>package com.w17714m.biblioteca.aplicacion.manejadores.prestamo;
import com.w17714m.biblioteca.dominio.servicio.bibliotecario.ServicioBibliotecario;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class ManejadorGenerarPrestamo {
private final ServicioBibliotecario servicioBibliotecario;
public ManejadorGenerarPrestamo(ServicioBibliotecario servicioBibliotecario) {
this.servicioBibliotecario = servicioBibliotecario;
}
@Transactional
public void ejecutar(String isbn, String nombreUsuarioPrestamo) {
this.servicioBibliotecario.prestar(isbn,nombreUsuarioPrestamo);
}
}
| b14f6ab175554e29b6714bbba334e262012bb099 | [
"Java"
] | 4 | Java | w17714m/biblioteca | 64c1c7fab492496080c3dc379d1574347437b8ce | 5b63b88fad79e333ec13289d9421c4aeed680f85 |
refs/heads/master | <repo_name>travelingspace/currencySite<file_sep>/routes/index.js
var express = require('express');
var router = express.Router();
var exchangeRates = require('../model/currencyDB');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET about page. */
router.get('/about', function(req, res, next) {
res.render('about', { title: 'About this site' });
});
/* GET convert page. */
router.get('/convert', function(req, res, next) {
var dollars = req.query.dollars;
var toCurrency = req.query.to_currency;
var converted = dollars * exchangeRates[toCurrency];
//res.send(dollars + ' in ' + toCurrency + ' is ' + converted);
res.render('result',{
dollars:dollars,
toCurrency: toCurrency,
converted: converted}
);
});
module.exports = router;
| e7714c53108706d0c59ba1528c149522fbefb7e5 | [
"JavaScript"
] | 1 | JavaScript | travelingspace/currencySite | af51a01c3be02386bfcaab99142b7cc1b781f267 | 53be7cd227fdf30fff3c2cb4c50115ee86b7882a |
refs/heads/master | <file_sep># Your code goes here!
class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
def match(words)
matches = []
word_array = @word.split("").sort
words.each do |word|
original = word.split("")
sorted = word.split("").sort
if sorted == word_array
matches << original.join
end
end
matches
end
end
| 631a6860c4de2b2db2c63c41a2c5a03d367eb151 | [
"Ruby"
] | 1 | Ruby | tomasperez10/anagram-detector-onl01-seng-ft-061520 | a8df0df057e36e8c96a1f10deeb5509881599b12 | 16833652daea2f7507594e42fcbd234b8fa69574 |
refs/heads/master | <file_sep># MedTask
Чтобы запустить проект нужно:
1) В папке с файлом main.go нажать SHIFT+пкм и запустить командную строку.
2) В командной строке ввести следующую уоманду: go run main.go.
3) Перейти по адресу: http://127.0.0.1:8080/all
4) Чтобы просмотреть отдельно категории и медикаменты нужно:
4.1 Перейти по адресу: http://127.0.0.1:8080/cat - можно просмотреть все категории
4.2 Перейти по адресу: http://127.0.0.1:8080/med - можно просмотреть все медикаменты
<file_sep>package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type AllMedicines struct {
Categ Category
Medic []Medicines
}
type Medicines struct {
ID string `json:"id"`
NameMed string `json:"name"`
IDcat string `json: ID category`
}
type Category struct {
ID string `json: "id"`
NameCat string `json: "Name"`
//Medic []Medicines
}
var med = []Medicines{}
var cat = []Category{}
//Получение категорий и медикаментов в них
func getAll(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
//params := mux.Vars(r)
var allMed = []AllMedicines{}
for _, ItemCat := range cat {
newlist := []Medicines{}
for _, ItemMed := range med {
if ItemMed.IDcat == ItemCat.ID {
newlist = append(newlist, ItemMed)
}
}
allMed = append(allMed, AllMedicines{ItemCat, newlist})
}
json.NewEncoder(w).Encode(allMed)
}
//////////////// Работа с медикаментами////////////////////////////////////
// Получение всех медикаментов
func getMed(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(med)
}
//Получение информации о медикаменте
func getMedicines(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for _, item := range med {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Medicines{})
}
//Создание медикамента
func createMedicines(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var medicin Medicines
_ = json.NewDecoder(r.Body).Decode(&medicin)
med = append(med, medicin)
json.NewEncoder(w).Encode(medicin)
}
//редактирование медикаментов
func updateMedicines(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for index, item := range med {
if item.ID == params["id"] {
med = append(med[:index], med[index+1:]...)
var TMed Medicines
_ = json.NewDecoder(r.Body).Decode(&TMed)
TMed.ID = params["id"]
med = append(med, TMed)
json.NewEncoder(w).Encode(TMed)
return
}
}
json.NewEncoder(w).Encode(med)
}
//удаление медикаментов
func deleteMedicines(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for index, item := range med {
if item.ID == params["id"] {
med = append(med[:index], med[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(med)
}
//////////////// Работа с категориями////////////////////////////////////
//Получение всех категорий
func getCat(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(cat)
}
//Получение информации о категории
func getCategory(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for _, item := range cat {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Category{})
}
//Создание Категории
func createCategory(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var categ Category
_ = json.NewDecoder(r.Body).Decode(&categ)
cat = append(cat, categ)
json.NewEncoder(w).Encode(categ)
}
//редактирование категории
func updateCategory(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for index, item := range cat {
if item.ID == params["id"] {
cat = append(cat[:index], cat[index+1:]...)
var TCat Category
_ = json.NewDecoder(r.Body).Decode(&TCat)
TCat.ID = params["id"]
cat = append(cat, TCat)
json.NewEncoder(w).Encode(TCat)
return
}
}
json.NewEncoder(w).Encode(cat)
}
//удаление категории
func deleteCategory(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for index, item := range cat {
if item.ID == params["id"] {
cat = append(cat[:index], cat[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(cat)
}
func main() {
r := mux.NewRouter()
med = append(med, Medicines{ID: "0", NameMed: "Парацетамол", IDcat: "1"})
med = append(med, Medicines{ID: "1", NameMed: "Аскофен", IDcat: "0"})
cat = append(cat, Category{ID: "0", NameCat: "Жаропонижающие"})
cat = append(cat, Category{ID: "1", NameCat: "Анаболики"})
//Получение всей информации
r.HandleFunc("/all", getAll).Methods("GET")
//работа с категориями
r.HandleFunc("/cat", getCat).Methods("GET")
r.HandleFunc("/cat/{id}", getCategory).Methods("GET")
r.HandleFunc("/cat", createCategory).Methods("POST")
r.HandleFunc("/cat/{id}", updateCategory).Methods("PUT")
r.HandleFunc("/cat/{id}", deleteCategory).Methods("DELETE")
//работа с медикаментами
r.HandleFunc("/med", getMed).Methods("GET")
r.HandleFunc("/med/{id}", getMedicines).Methods("GET")
r.HandleFunc("/med", createMedicines).Methods("POST")
r.HandleFunc("/med/{id}", updateMedicines).Methods("PUT")
r.HandleFunc("/med/{id}", deleteMedicines).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8080", r))
}
| f4a2aedec9f863f16c44cff8e265b91a07412f6e | [
"Markdown",
"Go"
] | 2 | Markdown | kykisplin/MedTask | edeb154d04032b7365e8507bb1c312bc31f587bf | a90172594dbb8f08e5be2223636ff6a2bf7ef269 |
refs/heads/master | <file_sep>var ARGOS = {
DESENV_SERVERS:{
ABRILSAC:[
'JBDEV11',
'JBDEV23'
]
},
HOMOLOG_SERVERS:{
ABRILSAC:[
'JBHOM23',
'JBHOM34'
],
CLUBE:[
'JBHOM04',
'JBHOM09'
],
ASSINE:[
'JBHOM01',
'JBHOM02',
'JBHOM06',
'JBHOM07'
],
SERVICOSASS:[
'JBHOM05',
'JBHOM10'
]
},
PROD_SERVERS:{
ABRILSAC:[
'JBPRD23',
'JBPRD34'
],
CLUBE:[
'JBPRD04',
'JBPRD09'
],
ASSINE:[
'JBPRD01',
'JBPRD02',
'JBPRD06',
'JBPRD07',
'JBPRD19',
'JBPRD20'
],
SERVICOSASS:[
'JBPRD05',
'JBPRD10'
]
},
};
| 618c8431610851c6812af42c6d26c8d407d8d6c5 | [
"JavaScript"
] | 1 | JavaScript | carlosvos/argos | 19d6fc070be3e1fb5ef436440988228d4e0aeea3 | 6ccc7a580ab1b16d7906dd09f26fcebd9455f2ff |
refs/heads/master | <repo_name>dxahtepb/ifmo-algo-is<file_sep>/Sem6_Lab_1/is_not_orgraph.py
def check_graph(matrix):
for i in range(len(matrix)):
for j in range(len(matrix)):
if matrix[i][j] != matrix[j][i] or (i == j and matrix[i][j] == 1):
return 'NO'
return 'YES'
if __name__ == '__main__':
with open('input.txt', 'r') as file_in, \
open('output.txt', 'w') as file_out:
nodes = int(file_in.readline().rstrip())
matrix = []
for _ in range(nodes):
line = list(map(int, file_in.readline().rstrip().split()))
matrix.append(line)
file_out.write(check_graph(matrix) + '\n')
<file_sep>/Lab2/anti_qs.cpp
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
void shuffle(vector<int> & a)
{
for (int i = 0; i < a.size(); ++i)
{
swap(a[i], a[i / 2]);
for (auto item : a)
{
cerr << item << " ";
}
cerr << endl;
}
}
int main()
{
ifstream input("antiqs.in");
ofstream output("antiqs.out");
int n = 0;
input >> n;
vector<int> a(n);
for (int i = 1; i <= n; ++i)
{
a[i - 1] = i;
}
shuffle(a);
for (auto item : a)
{
output << item << " ";
}
return 0;
}<file_sep>/Sem6_Lab_2/cycle.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
enum {WHITE, GRAY, BLACK};
int NO_CYCLE = -1;
std::vector<int> parents;
std::vector<int> color;
std::vector< std::vector<int> > graph;
int dfs(int v)
{
color[v] = GRAY;
for (int u : graph[v])
{
if (color[u] == GRAY)
{
parents[u] = v;
return v;
}
if (color[u] == WHITE)
{
parents[u] = v;
int cycle_start = dfs(u);
if (cycle_start != NO_CYCLE)
{
return cycle_start;
}
}
}
color[v] = BLACK;
return NO_CYCLE;
}
int main()
{
std::ifstream file_in("cycle.in");
std::ofstream file_out("cycle.out");
unsigned int n_vertices = 0, n_edges = 0;
file_in >> n_vertices >> n_edges;
graph.resize(n_vertices);
color.resize(n_vertices, WHITE);
parents.resize(n_vertices, -1);
for (int foo = 0; foo < n_edges; foo++)
{
unsigned int from = 0, to = 0;
file_in >> from >> to;
graph[from - 1].push_back(to - 1);
}
for (int i = 0; i < n_vertices; i++)
{
if (color[i] == WHITE)
{
int cycle_start = dfs(i);
if (cycle_start != NO_CYCLE)
{
file_out << "YES\n";
file_out << cycle_start + 1 << ' ';
std::vector<int> cycle;
for (int v = parents[cycle_start]; v != cycle_start; v = parents[v])
{
cycle.push_back(v + 1);
}
std::reverse(cycle.begin(), cycle.end());
for (int v : cycle)
{
file_out << v << ' ';
}
return 0;
}
}
}
file_out << "NO\n";
return 0;
}
<file_sep>/Sem6_Lab_3/vertex_degree.cpp
#include <fstream>
#include <vector>
int main()
{
std::ifstream inp_file("input.txt");
std::ofstream out_file("output.txt");
std::vector<uint32_t> degrees;
uint32_t n_vertices = 0, n_edges = 0;
inp_file >> n_vertices >> n_edges;
degrees.resize(n_vertices, 0);
for (int i = 0; i < n_edges; ++i)
{
uint32_t u = 0, v = 0;
inp_file >> u >> v;
degrees[u - 1]++;
degrees[v - 1]++;
}
for (uint32_t x : degrees)
{
out_file << x << " ";
}
}<file_sep>/Lab3/heapsort.cpp
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
void heapify(vector<int> & a, int i, int end)
{
int l = 2 * i + 1;
int r = 2 * i + 2;
int largest = 0;
if (l <= end && a[l] > a[i])
largest = l;
else
largest = i;
if (r <= end && a[r] > a[largest])
largest = r;
if (largest != i)
{
swap(a[i], a[largest]);
heapify(a, largest, end);
}
}
void build_heap(vector<int> & a)
{
for (int i = a.size() / 2; 0 <= i; --i)
{
heapify(a, i, a.size()-1);
}
}
void heap_sort(vector<int> & a)
{
build_heap(a);
for (int end = a.size() - 1; 0 < end; )
{
swap(a[0], a[end]);
--end;
heapify(a, 0, end);
}
}
int main()
{
ifstream input("sort.in");
ofstream output("sort.out");
int n = 0;
input >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i)
{
input >> a[i];
}
heap_sort(a);
for (auto & item : a)
{
output << item << " ";
}
return 0;
}<file_sep>/Lab3/garland.cpp
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
double optimal_B(int n, double A)
{
double hi = A;
double low = 0;
double B = 0;
double EPS = 0.00000001;
while (hi - low > EPS)
{
double middle = (hi + low) / 2;
double prev_lamp = A;
double curr_lamp = middle;
double possible_B = 0;
int at_ground = 0;
for (int i = 2; i < n; ++i)
{
double next_lamp = 2 * curr_lamp + 2 - prev_lamp;
if (next_lamp == 0)
{
++at_ground;
}
if (next_lamp < 0)
{
at_ground = 2000;
break;
}
prev_lamp = curr_lamp;
curr_lamp = next_lamp;
possible_B = next_lamp;
}
if (at_ground <= 1)
{
hi = middle;
B = possible_B;
}
else
{
low = middle;
}
}
return B;
}
int main()
{
ifstream input("garland.in");
ofstream output("garland.out");
int n = 0;
double A = 0;
input >> n >> A;
output << setprecision(2) << fixed << optimal_B(n, A);
return 0;
}<file_sep>/Lab4/stack.cpp
#include <vector>
#include <fstream>
using namespace std;
struct stack{
vector<int> st;
int size = 0;
explicit stack(int m)
{
st.resize(m + 1);
}
void push(int value)
{
st[++size] = value;
}
int pop()
{
return st[size--];
}
};
int main()
{
ifstream input("stack.in");
ofstream output("stack.out");
int m = 0;
input >> m;
stack a(m);
for (int i = 0; i < m; ++i)
{
string command;
input >> command;
if (command == "+")
{
int x = 0;
input >> x;
a.push(x);
}
else if (command == "-")
{
output << a.pop() << '\n';
}
}
return 0;
}<file_sep>/Sem6_Lab_1/components.py
def find_components(graph):
visited = [0] * n_nodes
n_components = 0
for node in range(len(graph)):
if visited[node] == 0:
n_components += 1
visited[node] = n_components
dfs(graph, node, visited, n_components)
return n_components, visited
def dfs(graph, start, visited, n_components):
stack = [start]
while stack:
children = graph[stack.pop()]
for child in children:
if visited[child] == 0:
visited[child] = n_components
stack.append(child)
if __name__ == '__main__':
with open('components.in', 'r') as file_in, \
open('components.out', 'w') as file_out:
n_nodes, n_edges = map(int, file_in.readline().rstrip().split())
graph = [[] for _ in range(n_nodes)]
for _ in range(n_edges):
vertex_from, vertex_to = map(lambda x: int(x)-1,
file_in.readline().rstrip().split())
graph[vertex_from].append(vertex_to)
graph[vertex_to].append(vertex_from)
n_components, labels = find_components(graph)
file_out.write(str(n_components) + '\n')
file_out.write(' '.join(map(str, labels)))
<file_sep>/Lab1/turtle.cpp
#include <fstream>
#include <vector>
using namespace std;
int turtle(vector<vector<int>> & a, int h, int w) {
for (int i = h-1; i >= 0; i--) {
for (int j = 0; j < w; j++) {
int down_value = 0, left_value = 0;
if (i != h-1) {
down_value = a[i+1][j];
}
if (j != 0) {
left_value = a[i][j-1];
}
a[i][j] += (left_value > down_value ? left_value : down_value);
}
}
return a[0][w-1];
}
int main() {
ios_base::sync_with_stdio(false);
ifstream fin;
fin.open("turtle.in");
int h, w;
fin >> h >> w;
vector<vector<int>> a;
int foo;
for (int i = 0; i < h; i++) {
a.emplace_back(vector<int>());
for (int j = 0; j < w; j++) {
fin >> foo;
a[i].push_back(foo);
}
}
fin.close();
int ans = turtle(a, h, w);
ofstream fout;
fout.open("turtle.out");
fout << ans;
fout.close();
return 0;
}<file_sep>/Lab2/order1.cpp
#include <fstream>
#include <random>
using namespace std;
int * a;
random_device rd; //Will be used to obtain a seed for the random number engine
mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
void swap (int & a, int & b)
{
int tmp = a;
a = b;
b = tmp;
}
int partition(int left, int right, int * il)
{
uniform_int_distribution<> dis(left, right);
int rand_pivot = dis(gen);
// int rand_pivot = (left + right) / 2;
swap(a[right], a[rand_pivot]);
int key = a[right];
int i = left - 1;
for (int j = left; j <= right - 1; ++j)
{
if (a[j] <= key)
{
++i;
swap(a[i], a[j]);
}
}
swap(a[i + 1], a[right]);
*il = i + 1;
while (a[(*il)--] == key) {}
(*il) += 2;
return i + 1;
}
int order_statistic(int left, int right, int i)
{
while (true)
{
int ql;
int q = partition(left, right, &ql);
int k = q - left + 1;
int kl = ql - left + 1;
if ((i >= kl) && (i <= k))
{
return a[q];
}
if (i < k)
{
right = ql - 1;
}
else
{
left = q + 1;
i -= k;
}
}
}
void generate_array(int n, int A, int B, int C,
int a_1, int a_2)
{
a = new int[n + 1];
a[1] = a_1;
a[2] = a_2;
for (int i = 3; i <= n; ++i)
{
a[i] = A*a[i - 2] + B*a[i - 1] + C;
}
}
int main()
{
ifstream input("kth.in");
ofstream output("kth.out");
int n = 0;
int k = 0;
input >> n >> k;
int A = 0;
int B = 0;
int C = 0;
int a_1 = 0;
int a_2 = 0;
input >> A >> B >> C >> a_1 >> a_2;
generate_array(n, A, B, C, a_1, a_2);
output << order_statistic(1, n, k);
return 0;
}<file_sep>/Lab4/priority_queue.cpp
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
struct heap_element {
int value;
int number;
explicit heap_element(int v, int n) : value(v), number(n) {}
heap_element() : value(0), number(0) {}
bool operator< (const heap_element& other) const
{
return this->value < other.value;
}
heap_element& operator= (int other)
{
this->value = other;
return *this;
}
bool operator== (int other) const
{
return this->number == other;
}
};
template <typename T>
class priority_queue
{
vector<T> heap;
void sift_up(int i)
{
while (true)
{
int parent = i == 0 ? 0 : (i - 1) / 2;
if (heap[i] < heap[parent])
{
swap(heap[i], heap[parent]);
i = parent;
}
else
break;
}
}
void sift_down(int i)
{
int l = 2 * i + 1;
int r = 2 * i + 2;
int smallest = i;
if (l < heap.size() && heap[l] < heap[i])
smallest = l;
if (r < heap.size() && heap[r] < heap[smallest])
smallest = r;
if (smallest != i)
{
swap(heap[i], heap[smallest]);
sift_down(smallest);
}
}
int find(int key)
{
for (int i = 0; i < heap.size(); i++)
{
if (heap[i] == key)
{
return i;
}
}
}
public:
bool extract_min(T& min)
{
if (heap.empty())
return false;
min = heap[0];
swap(heap[0], heap[heap.size() - 1]);
heap.pop_back();
sift_down(0);
return true;
}
void push(T elem)
{
heap.push_back(elem);
sift_up(heap.size() - 1);
}
void decrease_key(int key, int new_value)
{
int i = find(key);
heap[i] = new_value;
sift_up(i);
}
};
int main()
{
ifstream input("priorityqueue.in");
ofstream output("priorityqueue.out");
priority_queue<heap_element> queue;
int line_number = 0;
while (!input.eof())
{
line_number++;
string operation;
input >> operation;
if (operation == "push")
{
int key;
input >> key;
queue.push(heap_element(key, line_number));
}
else if (operation == "extract-min")
{
heap_element min_key;
if (queue.extract_min(min_key))
output << min_key.value << endl;
else
output << "*" << endl;
}
else if (operation == "decrease-key")
{
int number, new_value;
input >> number >> new_value;
queue.decrease_key(number, new_value);
}
}
return 0;
}
<file_sep>/Lab6/set.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <memory>
struct Value
{
const int hash;
const int key;
int value;
Value * next;
explicit
Value(int hash, int key, int value) : next(nullptr), hash(hash),
key(key), value(value) {}
// Value() : next(nullptr), hash(0),
// key(0), value(0) {}
};
struct HashSet
{
// const unsigned int MOD = 200001;
const unsigned int MOD = 96557;
std::vector<Value *> table;
HashSet()
{
table.resize(MOD);
}
int hash(int x)
{
x = x ^ (x >> 16);
return x;
}
void add(int key)
{
if (exists(key))
{
return;
}
int h = hash(key);
Value * node = new Value(h, key, key);
node->next = table[h % MOD];
table[h % MOD] = node;
}
Value * get(int key)
{
Value * node = table[hash(key) % MOD];
while (node != nullptr)
{
if (node->key == key)
{
return node;
}
node = node->next;
}
return nullptr;
}
bool exists(int key)
{
return (get(key) != nullptr);
}
void remove(int key)
{
int h = hash(key);
Value * node = table[h % MOD];
Value * prev_node = nullptr;
while (node != nullptr)
{
if (node->key == key)
{
if (prev_node == nullptr)
{
table[h % MOD] = node->next;
}
else
{
prev_node->next = node->next;
node->next = nullptr;
}
return;
}
prev_node = node;
node = node->next;
}
}
};
int main()
{
std::ifstream input("set.in");
std::ofstream output("set.out");
HashSet set;
while (!input.eof())
{
std::string operation;
int key;
input >> operation >> key;
if (operation == "insert")
{
set.add(key);
}
if (operation == "delete")
{
set.remove(key);
}
if (operation == "exists")
{
output << (set.exists(key) ? "true" : "false") << std::endl;
}
}
return 0;
}<file_sep>/Sem6_Lab_1/shortest_way_2.py
from collections import deque
def count_distances(matrix, n, m, start):
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
queue = deque([start])
while queue:
x, y = queue.popleft()
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
if new_x < 0 or new_x >= n or new_y < 0 or new_y >= m:
continue
if matrix[new_x][new_y] < 0:
continue
if matrix[new_x][new_y] > matrix[x][y] + 1:
matrix[new_x][new_y] = matrix[x][y] + 1
queue.append((new_x, new_y))
return matrix
def find_path(matrix, n, m, start, finish):
directions = [(0, 1, 'L'), (1, 0, 'U'), (0, -1, 'R'), (-1, 0, 'D')]
path = []
current_cell = finish
if matrix[finish[0]][finish[1]] == 10**6:
return '-1'
while current_cell != start:
x, y = current_cell
for dx, dy, symbol in directions:
new_x, new_y = x + dx, y + dy
if new_x < 0 or new_x >= n or new_y < 0 or new_y >= m:
continue
if matrix[new_x][new_y] < 0:
continue
if matrix[new_x][new_y] == matrix[x][y] - 1:
path.append(symbol)
current_cell = (new_x, new_y)
break
return path
if __name__ == '__main__':
with open('input.txt', 'r') as file_in, \
open('output.txt', 'w') as file_out:
n, m = map(int, file_in.readline().rstrip().split())
start, finish = 0, 0
matrix = [[10**6] * m for _ in range(n)]
for i in range(n):
row = list(iter(file_in.readline().rstrip()))
for j, cell in enumerate(row):
if cell == 'S':
start = (i, j)
matrix[i][j] = 0
elif cell == 'T':
finish = (i, j)
elif cell == '#':
matrix[i][j] = -100
matrix = count_distances(matrix, n, m, start)
path = find_path(matrix, n, m, start, finish)
if path != '-1':
file_out.write(str(len(path)) + '\n')
file_out.write(''.join(reversed(path)))
else:
file_out.write('-1')
<file_sep>/Lab7/avl_rotate.cpp
#include <fstream>
#include <vector>
#include <queue>
#include <iostream>
enum Side {right=0, left=1};
struct Input_Node
{
int key;
int children[2];
Input_Node(int key, int left, int right) : key(key)
{
children[0] = left;
children[1] = right;
}
};
struct Node
{
int key;
int height;
int inp_num;
Node* children[2];
Node(int key, Node * left, Node * right, int num) : key(key), height(0), inp_num(num)
{
children[0] = left;
children[1] = right;
}
Node(Input_Node * node, int num) : height(0), key(node->key), inp_num(num)
{
children[0] = children[1] = nullptr;
}
};
struct AVL_Tree
{
std::vector<Input_Node *> input_tree;
std::vector<Input_Node *> output_tree;
Node * root = nullptr;
void make_tree()
{
root = new Node(input_tree[0], 0);
dfs_make(root);
}
void dfs_make(Node * v)
{
for (int i = 0; i < 2; i++)
{
if (input_tree[v->inp_num]->children[i] == -1)
{
v->children[i] = nullptr;
}
else
{
v->children[i] =
new Node(input_tree[input_tree[v->inp_num]->children[i]], input_tree[v->inp_num]->children[i]);
dfs_make(v->children[i]);
}
}
}
int count_balance(Node * v)
{
return (v->children[1] != nullptr ? v->children[1]->height : 0) -
(v->children[0] != nullptr ? v->children[0]->height : 0);
}
void count_height()
{
if (input_tree.empty())
{
return ;
}
dfs(root);
}
void fix_height(Node * v)
{
v->height = std::max(height_left(v), height_right(v)) + 1;
}
int height_right(Node * v)
{
return v->children[1] == nullptr ? 0 : v->children[1]->height;
}
int height_left(Node * v)
{
return v->children[0] == nullptr ? 0 : v->children[0]->height;
}
void dfs(Node * v)
{
for (auto child : v->children)
{
if (child != nullptr)
{
dfs(child);
}
}
fix_height(v);
}
Node * rotate(Node * v, int side)
{
Node * u = v->children[side == Side::left ? 1 : 0];
v->children[side == Side::left ? 1 : 0] = u->children[side == Side::left ? 0 : 1];
u->children[side == Side::left ? 0 : 1] = v;
fix_height(v);
fix_height(u);
return u;
}
Node * balance(Node * v)
{
if (count_balance(v->children[1]) < 0)
{
v->children[1] = rotate(v->children[1], Side::right);
}
return rotate(v, Side::left);
}
void make_output_tree()
{
std::queue<Node *> queue;
queue.push(root);
int num = 1;
while (!queue.empty())
{
Node * v = queue.front();
queue.pop();
int children_num[2] = {0, 0};
for (int i = 0; i < 2; i++)
{
if (v->children[i] != nullptr)
{
queue.push(v->children[i]);
children_num[i] = ++num;
}
}
output_tree.push_back(new Input_Node(v->key, children_num[0], children_num[1]));
}
}
};
int main()
{
std::ifstream in("rotation.in");
std::ofstream out("rotation.out");
size_t n;
in >> n;
auto avl = new AVL_Tree();
for (int i = 0; i < n; i++)
{
int key;
int left, right;
in >> key >> left >> right;
avl->input_tree.push_back(new Input_Node(key, left-1, right-1));
}
avl->make_tree();
avl->count_height();
avl->root = avl->balance(avl->root);
avl->make_output_tree();
out << n << std::endl;
for (auto v : avl->output_tree)
{
out << v->key << " " << v->children[0] << " " << v->children[1] << std::endl;
}
}
<file_sep>/Sem6_Lab_6/6C.cpp
#include <iostream>
#include <fstream>
#include <vector>
void prefix_function(std::string const & text, std::vector<int> & prefix)
{
prefix.push_back(0);
for (size_t i = 1; i < text.size(); ++i)
{
int border = prefix[i - 1];
while (border > 0 && text[i] != text[border])
{
border = prefix[border - 1];
}
prefix.push_back(border + static_cast<int>(text[border] == text[i]));
}
}
int main()
{
std::ifstream inp_file("prefix.in");
std::ofstream out_file("prefix.out");
std::string text;
inp_file >> text;
std::vector<int> prefix;
prefix_function(text, prefix);
for (auto x : prefix)
{
out_file << x << ' ';
}
return 0;
}<file_sep>/Sem6_Lab_1/edge_2_matrix.py
if __name__ == '__main__':
with open('input.txt', 'r') as file_in, \
open('output.txt', 'w') as file_out:
nodes, edges = map(int, file_in.readline().rstrip().split())
matrix = []
for _ in range(nodes):
matrix.append([0] * nodes)
for _ in range(edges):
vertex_from, vertex_to = map(lambda x: int(x)-1, file_in.readline().rstrip().split())
matrix[vertex_from][vertex_to] = 1
file_out.write('\n'.join([' '.join(map(str, line)) for line in matrix]))
<file_sep>/Lab4/reverse_polish.cpp
#include <vector>
#include <fstream>
using namespace std;
struct stack{
vector<int> st;
int size = 0;
explicit stack(int m)
{
st.resize(m);
}
void push(int value)
{
st[++size] = value;
}
int pop()
{
return st[size--];
}
};
int eval(int a, char op, int b)
{
if (op == '+')
return a + b;
if (op == '-')
return a - b;
if (op == '*')
return a * b;
}
int main()
{
ifstream input("postfix.in");
ofstream output("postfix.out");
string expression;
getline(input, expression);
stack acc(expression.size());
for (auto & ch : expression)
{
if (ch == ' ')
continue;
if (isdigit(ch))
acc.push(ch - '0');
else
acc.push(eval(acc.pop(), ch, acc.pop()));
}
output << acc.pop();
return 0;
}<file_sep>/Sem6_Lab_1/no_parallel.py
if __name__ == '__main__':
with open('input.txt', 'r') as file_in, \
open('output.txt', 'w') as file_out:
nodes, edges = map(int, file_in.readline().rstrip().split())
matrix = []
for _ in range(nodes):
matrix.append([0] * nodes)
for _ in range(edges):
vertex_from, vertex_to = map(lambda x: int(x)-1,
file_in.readline().rstrip().split())
if matrix[vertex_from][vertex_to] == 1:
file_out.write('YES\n')
break
matrix[vertex_from][vertex_to] = 1
matrix[vertex_to][vertex_from] = 1
else:
file_out.write('NO\n')
<file_sep>/Sem6_Lab_2/strong_connection.cpp
#include <fstream>
#include <vector>
#include <limits>
#include <algorithm>
#include <iostream>
typedef std::vector< std::vector<int> > Graph;
enum {WHITE, GRAY, BLACK};
bool dfs_sort(int v, Graph const & graph, std::vector<int> & color, std::vector<int> & order)
{
color[v] = BLACK;
for (auto to : graph[v])
{
if (color[to] == WHITE)
{
dfs_sort(to, graph, color, order);
}
}
order.push_back(v);
}
bool dfs_transposed(int v, int component, Graph const & graph, std::vector<int> & color,
std::vector<int> & components)
{
color[v] = BLACK;
components[v] = component;
for (auto to : graph[v])
{
if (color[to] == WHITE)
{
dfs_transposed(to, component, graph, color, components);
}
}
}
uint32_t condensation(Graph const & graph, std::vector<int> & components)
{
size_t n_vertices = graph.size();
Graph transposed(n_vertices);
for (int from = 0; from < n_vertices; ++from)
{
for (auto to : graph[from])
{
transposed[to].push_back(from);
}
}
std::vector<int> color(n_vertices, WHITE);
std::vector<int> order;
for (int v = 0; v < n_vertices; ++v)
{
if (color[v] == WHITE)
{
dfs_sort(v, graph, color, order);
}
}
std::reverse(order.begin(), order.end());
color.assign(n_vertices, WHITE);
uint32_t current_component = 0;
for (int v : order)
{
if (color[v] == WHITE)
{
dfs_transposed(v, current_component++, transposed, color, components);
}
}
return current_component;
}
int main()
{
std::ifstream file_in("cond.in");
std::ofstream file_out("cond.out");
unsigned int n_vertices = 0, n_edges = 0;
file_in >> n_vertices >> n_edges;
std::vector<int> components(n_vertices);
std::vector<int> color(n_vertices);
std::vector<int> order(n_vertices);
std::vector< std::vector<int> > graph(n_vertices);
for (int foo = 0; foo < n_edges; ++foo)
{
unsigned int from = 0, to = 0;
file_in >> from >> to;
graph[from - 1].push_back(to - 1);
}
int n_comp = condensation(graph, components);
file_out << n_comp << '\n';
for (int v : components)
{
file_out << v + 1 << ' ';
}
return 0;
}
<file_sep>/Sem6_Lab_5/5A.cpp
#include <iostream>
#include <vector>
#include <unordered_map>
#include <cassert>
#include <algorithm>
#include <fstream>
const int NO_FLOW = -1;
const int NO_PREV = -1;
struct Edge
{
int from, to, cap, flow;
Edge(int from, int to, int cap, int flow)
: from(from), to(to), cap(cap), flow(flow) {}
int available_cap() const
{
return cap - flow;
}
};
struct Graph
{
std::vector< std::vector<int> > adj;
std::vector<Edge> edges;
explicit
Graph(int n)
{
adj.resize(n);
}
std::vector<int> &operator [] (int idx)
{
return adj[idx];
}
void add_edge(int from, int to, int cap)
{
adj[from].push_back(edges.size());
edges.emplace_back(from, to, cap, 0);
adj[to].push_back(edges.size());
edges.emplace_back(to, from, 0, 0);
}
size_t size()
{
return adj.size();
}
};
int64_t push_flow(Graph & graph, int source, int sink)
{
std::vector<int> queue;
std::unordered_map<int, int> prev = {{source, NO_PREV}};
queue.push_back(source);
int idx = 0;
while (idx < queue.size())
{
int u = queue[idx];
idx += 1;
for (auto e : graph[u])
{
auto edge = graph.edges[e];
if (prev.find(edge.to) == prev.end() && edge.available_cap() > 0)
{
queue.push_back(edge.to);
prev.insert({edge.to, e});
}
}
}
if (prev.find(sink) == prev.end())
{
return NO_FLOW;
}
std::vector<int> path;
int curr = sink;
while (prev[curr] != NO_PREV)
{
int e = prev[curr];
path.push_back(e);
curr = graph.edges[e].from;
}
int64_t flow = std::numeric_limits<int64_t>::max();
for (auto e : path)
{
if (graph.edges[e].available_cap() < flow)
{
flow = graph.edges[e].available_cap();
}
}
for (auto e : path)
{
graph.edges[e].flow += flow;
graph.edges[e ^ 1].flow -= flow;
}
return flow;
}
int64_t max_flow(Graph & graph)
{
int64_t total_flow = 0;
while (true)
{
int64_t flow = push_flow(graph, 0, graph.size() - 1);
if (flow == NO_FLOW)
{
break;
}
total_flow += flow;
}
return total_flow;
}
int main()
{
std::ifstream inp_file("maxflow.in");
std::ofstream out_file("maxflow.out");
int n = 0, m = 0;
inp_file >> n >> m;
Graph graph(n);
for (size_t i = 0; i < m; i++)
{
int from = 0, to = 0, cap = 0;
inp_file >> from >> to >> cap;
graph.add_edge(from - 1, to - 1, cap);
}
out_file << max_flow(graph);
return 0;
}<file_sep>/Sem6_Lab_2/game.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
enum {WHITE, GRAY, BLACK};
enum {FIRST, SECOND};
std::vector<int> color;
std::vector<int> winning_pos;
std::vector< std::vector<int> > graph;
void dfs(int v)
{
for (int u : graph[v])
{
if (color[u] == WHITE)
{
dfs(u);
}
}
winning_pos[v] = SECOND;
for (int u : graph[v])
{
if (winning_pos[u] == SECOND)
{
winning_pos[v] = FIRST;
break;
}
}
color[v] = BLACK;
}
int main()
{
std::ifstream file_in("game.in");
std::ofstream file_out("game.out");
unsigned int n_vertices = 0, n_edges = 0, start = 0;
file_in >> n_vertices >> n_edges >> start;
start--;
graph.resize(n_vertices);
color.resize(n_vertices, WHITE);
winning_pos.resize(n_vertices);
for (int foo = 0; foo < n_edges; ++foo)
{
unsigned int from = 0, to = 0;
file_in >> from >> to;
graph[from - 1].push_back(to - 1);
}
dfs(start);
file_out << (winning_pos[start] == FIRST ? "First" : "Second") << " player wins";
return 0;
}
<file_sep>/Lab3/radix.cpp
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void count_sort(vector<string> & a, int digit)
{
vector<int> count((unsigned int) 'z' + 1);
for (auto & s : a)
{
++count[s[digit]];
}
int pos = 0;
for (char i = 'a'; i <= 'z'; ++i)
{
int add_pos = count[i];
count[i] = pos;
pos += add_pos;
}
vector<string> b(a.size());
for (auto & s : a)
{
char d = s[digit];
b[count[d]++] = s;
}
a = b;
}
void radix_sort(vector<string> & a, int m, int k)
{
for (int step = 1; step <= k; ++step)
{
count_sort(a, m - step);
}
}
using namespace std;
int main()
{
ifstream input("radixsort.in");
ofstream output("radixsort.out");
int n = 0;
int m = 0;
int k = 0;
input >> n >> m >> k;
vector<string> a(n);
for (int i = 0; i < n; ++i)
{
input >> a[i];
}
radix_sort(a, m, k);
for (auto & s : a)
{
output << s << '\n';
}
return 0;
}<file_sep>/Sem6_Lab_4/4E.cpp
#include <fstream>
#include <limits>
#include <vector>
#include <queue>
#include <algorithm>
#include <iostream>
const int32_t INF = std::numeric_limits<int32_t>::max();
const int64_t NO_EDGE = 1000000000;
typedef std::vector< std::vector< std::pair<int32_t, int32_t> > > Graph;
bool find_neg_cycle(Graph const & graph, int32_t s, std::vector<int32_t> & neg_cycle)
{
std::vector<int64_t> distances(graph.size(), INF);
std::vector<int32_t> parents(graph.size(), -1);
distances[s] = 0;
int32_t cycle_start = -1;
for (size_t n = 0; n < graph.size(); ++n)
{
for (size_t from = 0; from < graph.size(); ++from)
{
for (auto edge : graph[from])
{
int32_t to = edge.first;
int32_t weight = edge.second;
if (distances[to] > distances[from] + weight)
{
if (n == graph.size() - 1)
{
cycle_start = to;
}
distances[to] = distances[from] + weight;
parents[to] = from;
}
}
}
}
if (cycle_start == -1)
{
return false;
}
else
{
for (int i = 0; i < graph.size(); ++i)
{
cycle_start = parents[cycle_start];
}
auto curr = cycle_start;
while (!(curr == parents[cycle_start] && neg_cycle.size() > 1))
{
neg_cycle.push_back(curr);
curr = parents[curr];
}
std::reverse(neg_cycle.begin(), neg_cycle.end());
return true;
}
}
int main()
{
std::ifstream inp_file("negcycle.in");
std::ofstream out_file("negcycle.out");
uint32_t n_vertex = 0;
inp_file >> n_vertex;
Graph graph(n_vertex);
for (size_t from = 0; from < n_vertex; ++from)
{
for (size_t to = 0; to < n_vertex; ++to)
{
int32_t weight = 0;
inp_file >> weight;
if (weight == NO_EDGE)
{
continue;
}
graph[from].emplace_back(to, weight);
}
}
std::vector<int32_t> neg_cycle;
if (find_neg_cycle(graph, 0, neg_cycle))
{
if (!neg_cycle.empty())
{
out_file << "YES" << std::endl << neg_cycle.size() << std::endl;
for (auto u : neg_cycle)
{
out_file << u + 1 << ' ';
}
out_file << std::endl;
return 0;
}
}
out_file << "NO" << std::endl;
return 0;
}<file_sep>/Sem6_Lab_4/4B.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <limits>
typedef std::vector< std::vector< std::pair<int, int> > > Graph;
int INF = std::numeric_limits<int>::max();
std::vector< std::vector<int64_t> > floyd_warshall(Graph const & graph)
{
std::vector< std::vector<int64_t> > dist(graph.size());
for (size_t i = 0; i < graph.size(); ++i)
{
dist[i].resize(graph.size(), INF);
dist[i][i] = 0;
for (auto edge : graph[i])
{
dist[i][edge.first] = edge.second;
}
}
for (size_t k = 0; k < graph.size(); ++k)
{
for (size_t i = 0; i < graph.size(); ++i)
{
for (size_t j = 0; j < graph.size(); ++j)
{
dist[i][j] = std::min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
return dist;
}
int main()
{
std::ifstream inp_file("pathsg.in");
std::ofstream out_file("pathsg.out");
uint32_t n_vertex = 0, n_edges = 0;
inp_file >> n_vertex >> n_edges;
Graph graph(n_vertex);
for (int i = 0; i < n_edges; ++i)
{
int u = 0, v = 0, w = 0;
inp_file >> u >> v >> w;
graph[u - 1].push_back({v - 1, w});
}
auto dist = floyd_warshall(graph);
for (int i = 0; i < graph.size(); ++i)
{
for (int j = 0; j < graph.size(); ++j)
{
out_file << dist[i][j] << ' ';
}
out_file << std::endl;
}
return 0;
}<file_sep>/Sem6_Lab_4/4C.cpp
#include <fstream>
#include <vector>
#include <queue>
#include <limits>
#include <set>
#include <iostream>
const int64_t INF = std::numeric_limits<int64_t>::max();
typedef std::vector< std::vector< std::pair<uint32_t, int32_t> > > Graph;
std::vector<int64_t>
dijkstra(Graph const &graph, uint32_t start)
{
std::vector<int64_t> dist(graph.size(), INF);
std::set< std::pair<int64_t, uint32_t> > queue;
dist[start] = 0;
queue.insert({0, start});
while (!queue.empty())
{
auto min_edge = *queue.begin();
queue.erase(queue.begin());
auto from = min_edge.second;
for (auto edge : graph[from])
{
uint32_t to = edge.first;
int32_t weight = edge.second;
if (dist[to] > dist[from] + weight)
{
queue.erase({dist[to], to});
dist[to] = dist[from] + weight;
queue.insert({dist[to], to});
}
}
}
return dist;
}
int main()
{
std::ifstream inp_file("pathbgep.in");
std::ofstream out_file("pathbgep.out");
uint32_t n_vertex = 0, n_edges = 0;
inp_file >> n_vertex >> n_edges;
Graph graph(n_vertex);
for (size_t i = 0; i < n_edges; ++i)
{
uint32_t from = 0, to = 0;
int32_t weight = 0;
inp_file >> from >> to >> weight;
graph[from - 1].emplace_back(to - 1, weight);
graph[to - 1].emplace_back(from - 1, weight);
}
auto dist = dijkstra(graph, 0);
for (auto x : dist)
{
out_file << x << ' ';
}
return 0;
}<file_sep>/Sem6_Lab_6/6A.py
import sys
pattern, text = sys.stdin.read().split()
ans = [i + 1 for i in range(len(text) + 1) if text[i:].startswith(pattern)]
print(len(ans))
print(*ans)
<file_sep>/Lab3/is_heap.cpp
#include <vector>
#include <fstream>
using namespace std;
bool is_heap(vector<int> & heap)
{
int n = heap.size();
for (int i = 1; i <= n ; ++i)
{
if ((2 * i < n) && (heap[2 * i] < heap[i]))
{
return false;
}
if ((2 * i + 1 < n) && (heap[2 * i + 1] < heap[i]))
{
return false;
}
}
return true;
}
int main()
{
ifstream input("isheap.in");
ofstream output("isheap.out");
int n = 0;
input >> n;
vector<int> heap(n + 1);
for (int i = 1; i <= n; ++i)
{
input >> heap[i];
}
output << (is_heap(heap) ? "YES" : "NO") << endl;
return 0;
}<file_sep>/Lab4/queue.cpp
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct queue
{
vector<int> q;
int l = 0;
int r = 0;
explicit queue(int size)
{
q.resize(size + 1);
}
void push(int value)
{
q[++r] = value;
}
int pop()
{
return q[++l];
}
};
int main()
{
ifstream input("queue.in");
ofstream output("queue.out");
int m = 0;
input >> m;
queue q(m);
for (int i = 0; i < m; ++i)
{
string command;
input >> command;
if (command == "+")
{
int x = 0;
input >> x;
q.push(x);
}
else if (command == "-")
{
output << q.pop() << '\n';
}
}
return 0;
}<file_sep>/Sem6_Lab_5/5C.cpp
#include <vector>
#include <fstream>
#include <queue>
#include <limits>
#include <iostream>
#include <list>
typedef std::pair< int64_t, std::list<int> > Decomposition;
const int64_t NO_PATH = -1;
struct Edge
{
int from, to, number, id;
int64_t cap, flow;
Edge(int from, int to, int64_t cap, int64_t flow, int number, int id)
: from(from), to(to), cap(cap), flow(flow), number(number), id(id) {}
int64_t available_cap() const
{
return cap - flow;
}
};
struct Graph
{
std::vector< std::vector<int> > adj;
std::vector<Edge> edges;
std::vector<int> levels;
std::vector<int> ptr;
explicit
Graph(int n)
{
adj.resize(n);
levels.resize(n);
ptr.resize(n);
}
std::vector<int> &operator [] (int idx)
{
return adj[idx];
}
void add_edge(int from, int to, int64_t cap, int number)
{
adj[from].push_back(edges.size());
edges.emplace_back(from, to, cap, 0, number, edges.size());
adj[to].push_back(edges.size());
edges.emplace_back(to, from, 0, 0, number, edges.size());
}
size_t size() const
{
return adj.size();
}
};
bool bfs(Graph & graph, int source, int sink)
{
graph.levels.assign(graph.size(), -1);
std::queue<int> queue;
queue.push(source);
graph.levels[source] = 0;
while (!queue.empty() && graph.levels[sink] == -1)
{
int from = queue.front();
queue.pop();
for (auto id : graph[from])
{
int to = graph.edges[id].to;
if (graph.levels[to] == -1 && graph.edges[id].available_cap() > 0)
{
queue.push(to);
graph.levels[to] = graph.levels[from] + 1;
}
}
}
return graph.levels[sink] != -1;
}
int64_t dfs(Graph & graph, int u, int sink, int64_t flow)
{
if (flow == 0)
{
return 0;
}
if (u == sink)
{
return flow;
}
while (graph.ptr[u] < graph[u].size())
{
int id = graph[u][graph.ptr[u]];
int v = graph.edges[id].to;
if (graph.levels[u] + 1 != graph.levels[v])
{
graph.ptr[u]++;
continue;
}
int64_t pushed_flow = dfs(
graph, v, sink, std::min(flow, graph.edges[id].available_cap())
);
if (pushed_flow != 0)
{
graph.edges[id].flow += pushed_flow;
graph.edges[id ^ 1].flow -= pushed_flow;
return pushed_flow;
}
graph.ptr[u]++;
}
return 0;
}
int64_t dinic(Graph & graph, int source, int sink)
{
int64_t max_flow = 0;
while (true)
{
if (!bfs(graph, source, sink))
{
break;
}
graph.ptr.assign(graph.size(), 0);
int64_t flow = dfs(graph, source, sink, std::numeric_limits<int64_t>::max());
while (flow != 0)
{
max_flow += flow;
flow = dfs(graph, source, sink, std::numeric_limits<int64_t>::max());
}
}
return max_flow;
}
void simple_decomposition(Graph & graph, int start,
Decomposition & p)
{
p.first = NO_PATH;
p.second.clear();
std::vector<char> used(graph.size());
int v = start;
while (!used[v])
{
if (v == graph.size() - 1)
{
break;
}
int edge_id = -1;
for (auto u : graph[v])
{
if (graph.edges[u].flow > 0)
{
edge_id = u;
break;
}
}
if (edge_id == -1)
{
p.first = NO_PATH;
p.second.clear();
return;
}
p.second.push_back(edge_id);
used[v] = 1;
v = graph.edges[edge_id].to;
}
if (used[v])
{
while (graph.edges[p.second.front()].from != v)
{
p.second.pop_front();
}
}
int64_t decomp_flow = std::numeric_limits<int64_t>::max();
for (auto edge_id : p.second)
{
if (graph.edges[edge_id].flow < decomp_flow)
{
decomp_flow = graph.edges[edge_id].flow;
}
}
for (auto edge_id : p.second)
{
graph.edges[edge_id].flow -= decomp_flow;
}
p.first = decomp_flow;
}
void full_decomposition(Graph & graph, std::vector<Decomposition> & decompositions,
int start)
{
Decomposition p;
simple_decomposition(graph, start, p);
while (p.first != NO_PATH)
{
decompositions.emplace_back(p.first, p.second);
simple_decomposition(graph, start, p);
}
}
int main()
{
std::ifstream inp_file("decomposition.in");
std::ofstream out_file("decomposition.out");
int n = 0, m = 0;
inp_file >> n >> m;
Graph graph(n);
for (size_t i = 0; i < m; i++)
{
int from = 0, to = 0;
int64_t cap = 0;
inp_file >> from >> to >> cap;
graph.add_edge(from - 1, to - 1, cap, i + 1);
}
dinic(graph, 0, graph.size() - 1);
std::vector<Decomposition> decompositions;
full_decomposition(graph, decompositions, 0);
out_file << decompositions.size() << std::endl;
for (auto const & decomp : decompositions)
{
out_file << decomp.first << ' ' << decomp.second.size() << ' ';
for (auto const & edge_id : decomp.second)
{
out_file << graph.edges[edge_id].number << ' ';
}
out_file << std::endl;
}
return 0;
}
<file_sep>/Lab5/height.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <memory>
using namespace std;
struct Node
{
int key;
size_t children[2];
Node(int key, size_t left, size_t right) : key(key)
{
children[0] = left;
children[1] = right;
}
};
int height(vector<Node*> & tree)
{
if (tree.empty())
{
return 0;
}
int max_distance = 0;
queue<pair<Node*, int>> queue;
queue.push(make_pair(tree[0], 1));
while (!queue.empty())
{
Node* vertex = queue.front().first;
int distance = queue.front().second;
max_distance = max(distance, max_distance);
for (size_t child : vertex->children)
{
if (child != -1)
{
queue.push(make_pair(tree[child], distance + 1));
}
}
queue.pop();
}
return max_distance;
}
int main()
{
ifstream input("height.in");
ofstream output("height.out");
size_t n;
input >> n;
vector<Node*> nodes;
for (size_t i = 0; i < n; i++)
{
int key;
size_t left, right;
input >> key >> left >> right;
nodes.push_back(new Node(key, left-1, right-1));
}
output << height(nodes);
return 0;
}<file_sep>/Sem6_Lab_2/hamilton.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <unordered_set>
enum {WHITE, GRAY, BLACK};
std::vector<int> topsorted;
std::vector<int> color;
std::vector< std::unordered_set<int> > graph;
void dfs(int v)
{
for (auto u : graph[v])
{
if (color[u] == WHITE)
{
dfs(u);
}
}
topsorted.push_back(v);
color[v] = BLACK;
}
int main()
{
std::ifstream file_in("hamiltonian.in");
std::ofstream file_out("hamiltonian.out");
unsigned int n_vertices = 0, n_edges = 0;
file_in >> n_vertices >> n_edges;
graph.resize(n_vertices);
color.resize(n_vertices, WHITE);
for (int i = 0; i < n_edges; ++i)
{
unsigned int from = 0, to = 0;
file_in >> from >> to;
graph[from - 1].insert(to - 1);
}
for (int v = 0; v < n_vertices; ++v)
{
if (color[v] == WHITE)
{
dfs(v);
}
}
std::reverse(topsorted.begin(), topsorted.end());
for (auto it = topsorted.begin() + 1; it != topsorted.end(); ++it)
{
if (graph[*(it-1)].find(*it) == graph[*it].end())
{
file_out << "NO";
return 0;
}
}
file_out << "YES";
return 0;
}<file_sep>/Lab5/is_bst.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
struct Node
{
int key;
size_t children[2];
Node(int key, size_t left, size_t right) : key(key)
{
children[0] = left;
children[1] = right;
}
};
bool check_subtree(vector<Node*> & tree, size_t node, int min_key, int max_key)
{
if (node == -1)
{
return true;
}
if (tree[node]->key <= min_key || tree[node]->key >= max_key)
{
return false;
}
return check_subtree(tree, tree[node]->children[0], min_key, tree[node]->key)
&& check_subtree(tree, tree[node]->children[1], tree[node]->key, max_key);
}
bool is_bst(vector<Node*> & tree)
{
if (tree.empty())
return true;
return check_subtree(tree, 0, -1000000001, 1000000001);
}
int main()
{
ifstream input("check.in");
ofstream output("check.out");
size_t n;
input >> n;
vector<Node*> nodes;
for (size_t i = 0; i < n; i++)
{
int key;
size_t left, right;
input >> key >> left >> right;
nodes.push_back(new Node(key, left-1, right-1));
}
output << (is_bst(nodes) ? "YES" : "NO");
return 0;
}<file_sep>/Lab6/multi_map.cpp
#include <iostream>
#include <vector>
#include <fstream>
struct Node
{
std::string key;
Node* children[2];
Node(std::string key) : key(key)
{
children[0] = children[1] = nullptr;
}
~Node()
{
delete children[0];
delete children[1];
}
};
class Tree
{
Node* root = nullptr;
int size = 0;
Node* search(Node* node, std::string &key)
{
if (node == nullptr || node->key == key)
{
return node;
}
return search(node->children[((key < node->key) ? 0 : 1)], key);
}
Node* insert(Node* node, std::string &key)
{
if (node == nullptr)
{
return new Node(key);
}
node->children[((key < node->key) ? 0 : 1)] =
insert(node->children[((key < node->key) ? 0 : 1)], key);
return node;
}
int children_count(Node* node)
{
int count = 0;
for (int i = 0; i < 2; i++)
{
if (node->children[i] != nullptr)
{
count++;
}
}
return count;
}
Node* remove(Node* node, std::string &key)
{
if (node == nullptr)
{
return node;
}
if (node->key != key)
{
node->children[((key < node->key) ? 0 : 1)] =
remove(node->children[((key < node->key) ? 0 : 1)], key);
}
else
{
int count = children_count(node);
if (count < 2)
{
node = node->children[((node->children[0] != nullptr) ? 0 : 1)];
}
else
{
Node* min_from_right_subtree = minimum(node->children[1]);
node->key = min_from_right_subtree->key;
node->children[1] = remove(node->children[1], node->key);
}
}
return node;
}
Node* minimum(Node* node)
{
if (node->children[0] == nullptr)
{
return node;
}
return minimum(node->children[0]);
}
std::vector<std::string> trav;
void make_trav(Node * v)
{
if (v == nullptr)
{
return;
}
make_trav(v->children[0]);
trav.push_back(v->key);
make_trav(v->children[1]);
}
public:
void insert(std::string &key)
{
if (!exists(key))
{
root = insert(root, key);
size++;
}
}
bool exists(std::string &key)
{
return search(root, key) != nullptr;
}
void remove(std::string &key)
{
if (exists(key))
{
root = remove(root, key);
size--;
}
}
int get_size()
{
return size;
}
std::vector<std::string> traversal()
{
trav.resize(0);
make_trav(root);
return trav;
}
~Tree()
{
delete root;
}
};
struct Value
{
const std::string key;
Tree * tree;
Value * next;
explicit
Value(int hash, std::string key, std::string value) : next(nullptr),
key(key)
{
tree = new Tree();
tree->insert(value);
}
};
struct MultiMap
{
const unsigned int MOD = 96557;
std::vector<Value *> table;
MultiMap()
{
table.resize(MOD);
}
int hash(const std::string& s)
{
int multiplier = 263;
int prime = 1000000007;
unsigned long long hash = 0;
for (int i = s.size() - 1; i >= 0; --i)
hash = (hash * multiplier + s[i]) % prime;
return static_cast<int> (hash);
}
void add(const std::string &key, std::string &value)
{
Value * x = get_value(key);
if (x != nullptr)
{
x->tree->insert(value);
return;
}
int h = hash(key);
Value * node = new Value(h, key, value);
node->next = table[h % MOD];
table[h % MOD] = node;
}
Value * get_value(const std::string &key)
{
Value * node = table[hash(key) % MOD];
while (node != nullptr)
{
if (node->key == key)
{
return node;
}
node = node->next;
}
return nullptr;
}
std::vector<std::string> get(const std::string &key)
{
Value * node = get_value(key);
if (node == nullptr)
{
return std::vector<std::string>();
}
return node->tree->traversal();
}
void remove(const std::string &key, std::string &value)
{
int h = hash(key);
Value * node = table[h % MOD];
Value * prev_node = nullptr;
while (node != nullptr)
{
if (node->key == key)
{
node->tree->remove(value);
if (node->tree->get_size() == 0)
{
if (prev_node == nullptr)
{
table[h % MOD] = node->next;
}
else
{
prev_node->next = node->next;
node->next = nullptr;
}
return;
}
}
prev_node = node;
node = node->next;
}
}
void remove_all(const std::string &key)
{
int h = hash(key);
Value * node = table[h % MOD];
Value * prev_node = nullptr;
while (node != nullptr)
{
if (node->key == key)
{
if (prev_node == nullptr)
{
table[h % MOD] = node->next;
}
else
{
prev_node->next = node->next;
delete node->tree;
node->next = nullptr;
}
return;
}
prev_node = node;
node = node->next;
}
}
};
int main()
{
std::ifstream input("multimap.in");
std::ofstream output("multimap.out");
MultiMap map;
while (!input.eof())
{
std::string operation;
std::string key;
input >> operation >> key;
if (operation == "put")
{
std::string value;
input >> value;
map.add(key, value);
}
if (operation == "delete")
{
std::string value;
input >> value;
map.remove(key, value);
}
if (operation == "deleteall")
{
map.remove_all(key);
}
if (operation == "get")
{
std::vector<std::string> vector = map.get(key);
output << vector.size();
for (std::string s : vector)
{
output << " " << s;
}
output << std::endl;
}
}
return 0;
}<file_sep>/Sem6_Lab_5/5D.cpp
#include <vector>
#include <fstream>
#include <queue>
#include <limits>
#include <iostream>
#include <list>
struct Edge
{
int from, to;
bool true_edge;
int64_t cap, flow;
Edge(int from, int to, int64_t cap, int64_t flow, bool true_edge)
: from(from), to(to), cap(cap), flow(flow), true_edge(true_edge) {}
int64_t available_cap() const
{
return cap - flow;
}
};
struct Graph
{
std::vector< std::vector<int> > adj;
std::vector<Edge> edges;
std::vector<int> levels;
std::vector<int> ptr;
explicit
Graph(int n)
{
adj.resize(n);
levels.resize(n);
ptr.resize(n);
}
std::vector<int> &operator [] (int idx)
{
return adj[idx];
}
void add_edge(int from, int to, int64_t cap)
{
adj[from].push_back(edges.size());
edges.emplace_back(from, to, cap, 0, (from != 0 && to != size() - 1));
adj[to].push_back(edges.size());
edges.emplace_back(to, from, 0, 0, 0);
}
size_t size() const
{
return adj.size();
}
};
bool bfs(Graph & graph, int source, int sink)
{
graph.levels.assign(graph.size(), -1);
std::queue<int> queue;
queue.push(source);
graph.levels[source] = 0;
while (!queue.empty() && graph.levels[sink] == -1)
{
int from = queue.front();
queue.pop();
for (auto id : graph[from])
{
int to = graph.edges[id].to;
if (graph.levels[to] == -1 && graph.edges[id].available_cap() > 0)
{
queue.push(to);
graph.levels[to] = graph.levels[from] + 1;
}
}
}
return graph.levels[sink] != -1;
}
int64_t dfs(Graph & graph, int u, int sink, int64_t flow)
{
if (flow == 0)
{
return 0;
}
if (u == sink)
{
return flow;
}
while (graph.ptr[u] < graph[u].size())
{
int id = graph[u][graph.ptr[u]];
int v = graph.edges[id].to;
if (graph.levels[u] + 1 != graph.levels[v])
{
graph.ptr[u]++;
continue;
}
int64_t pushed_flow = dfs(
graph, v, sink, std::min(flow, graph.edges[id].available_cap())
);
if (pushed_flow != 0)
{
graph.edges[id].flow += pushed_flow;
graph.edges[id ^ 1].flow -= pushed_flow;
return pushed_flow;
}
graph.ptr[u]++;
}
return 0;
}
int64_t dinic(Graph & graph, int source, int sink)
{
int64_t max_flow = 0;
while (true)
{
if (!bfs(graph, source, sink))
{
break;
}
graph.ptr.assign(graph.size(), 0);
int64_t flow = dfs(graph, source, sink, std::numeric_limits<int64_t>::max());
while (flow != 0)
{
max_flow += flow;
flow = dfs(graph, source, sink, std::numeric_limits<int64_t>::max());
}
}
return max_flow;
}
bool circulation(Graph & graph)
{
for (auto edge : graph.edges)
{
if (edge.from == 0)
{
if (edge.flow < edge.cap)
{
return false;
}
}
}
return true;
}
int main()
{
std::ifstream inp_file("circulation.in");
std::ofstream out_file("circulation.out");
int n = 0, m = 0;
inp_file >> n >> m;
Graph graph(n+2);
for (size_t i = 0; i < m; i++)
{
int from = 0, to = 0;
int64_t min_cap = 0, max_cap = 0;
inp_file >> from >> to >> min_cap >> max_cap;
graph.add_edge(0, to, min_cap);
graph.add_edge(from, to, max_cap-min_cap);
graph.add_edge(from, graph.size() - 1, min_cap);
}
dinic(graph, 0, graph.size() - 1);
if (circulation(graph))
{
out_file << "YES" << std::endl;
for (size_t id = 0; id < graph.edges.size(); ++id)
{
auto edge = graph.edges[id];
if (edge.true_edge)
{
out_file << edge.flow + graph.edges[id-2].cap << std::endl;
}
}
}
else
{
out_file << "NO";
}
return 0;
}
<file_sep>/Sem6_Lab_3/china_numba_two.cpp
#include <fstream>
#include <vector>
#include <limits>
#include <queue>
#include <unordered_set>
#include <algorithm>
#include <iostream>
typedef std::vector< std::vector< std::pair<int, int> > > Graph;
enum {WHITE, GRAY, BLACK};
bool bfs(int root, Graph const & graph)
{
std::unordered_set<int> used;
used.insert(root);
std::queue<int> queue;
queue.push(root);
while (!queue.empty())
{
int u = queue.front();
queue.pop();
for (auto v : graph[u])
{
int to = v.first;
if (used.find(to) == used.end())
{
queue.push(to);
used.insert(to);
}
}
}
return used.size() == graph.size();
}
bool dfs_sort(int v, Graph const & graph, std::vector<int> & color, std::vector<int> & order)
{
color[v] = BLACK;
for (auto edge : graph[v])
{
int to = edge.first;
if (color[to] == WHITE)
{
dfs_sort(to, graph, color, order);
}
}
order.push_back(v);
}
bool dfs_transposed(int v, int component, Graph const & graph, std::vector<int> & color,
std::vector<int> & components)
{
color[v] = BLACK;
components[v] = component;
for (auto edge : graph[v])
{
int to = edge.first;
if (color[to] == WHITE)
{
dfs_transposed(to, component, graph, color, components);
}
}
}
uint32_t condensation(Graph const & graph, std::vector<int> & components)
{
size_t n_vertices = graph.size();
Graph transposed(n_vertices);
for (int from = 0; from < n_vertices; ++from)
{
for (auto const & edge : graph[from])
{
int to = edge.first;
int weight = edge.second;
transposed[to].push_back({from, weight});
}
}
std::vector<int> color(n_vertices, WHITE);
std::vector<int> order;
for (int v = 0; v < n_vertices; ++v)
{
if (color[v] == WHITE)
{
dfs_sort(v, graph, color, order);
}
}
std::reverse(order.begin(), order.end());
color.assign(n_vertices, WHITE);
uint32_t current_component = 0;
for (int v : order)
{
if (color[v] == WHITE)
{
dfs_transposed(v, current_component++, transposed, color, components);
}
}
return current_component;
}
int64_t find_mst(Graph & graph, uint32_t n, int root)
{
int64_t res = 0;
std::vector<int> min_edge(n, std::numeric_limits<int>::max());
for (auto const &u : graph)
{
for (auto const &edge : u)
{
int to = edge.first;
int weight = edge.second;
min_edge[to] = std::min(weight, min_edge[to]);
}
}
for (int from = 0; from < graph.size(); ++from)
{
if (from != root)
{
res += min_edge[from];
}
}
Graph zero_graph(n);
for (int from = 0; from < graph.size(); ++from)
{
for (int edge = 0; edge < graph[from].size(); ++edge)
{
int to = graph[from][edge].first;
int weight = graph[from][edge].second;
if (weight == min_edge[to])
{
zero_graph[from].push_back({to, weight - min_edge[to]});
}
}
}
if (bfs(root, zero_graph))
{
return res;
}
std::vector<int> new_components(n);
uint32_t n_comp = condensation(zero_graph, new_components);
Graph new_edges(n_comp);
for (int from = 0; from < graph.size(); ++from)
{
for (auto const &edge : graph[from])
{
int to = edge.first;
int weight = edge.second;
if (new_components[from] != new_components[to])
{
new_edges[new_components[from]].push_back({new_components[to], weight - min_edge[to]});
}
}
}
res += find_mst(new_edges, n_comp, new_components[root]);
return res;
}
int main()
{
std::ifstream inp_file("chinese.in");
std::ofstream out_file("chinese.out");
uint32_t n_vertex = 0, n_edges = 0;
inp_file >> n_vertex >> n_edges;
Graph graph(n_vertex);
for (int i = 0; i < n_edges; ++i)
{
int u = 0, v = 0, w = 0;
inp_file >> u >> v >> w;
graph[u - 1].push_back({v - 1, w});
}
if (bfs(0, graph))
{
int64_t mst = find_mst(graph, n_vertex, 0);
out_file << "YES\n" << mst;
}
else
{
out_file << "NO";
}
return 0;
}<file_sep>/Sem6_Lab_4/4D.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <limits>
#include <queue>
#include <unordered_map>
const __int128 INF = std::numeric_limits<__int128>::max();
typedef std::vector< std::vector< std::pair<uint32_t, int64_t> > > Graph;
void get_shortest_paths(Graph const & graph, uint32_t s, std::vector<__int128> & distance,
std::vector<bool> & reachable, std::vector<bool> & shortest)
{
distance[s] = 0;
reachable[s] = true;
std::queue<uint32_t> queue;
for (size_t n = 0; n < graph.size(); ++n)
{
for (size_t v = 0; v < graph.size(); ++v)
{
for (auto edge : graph[v])
{
uint32_t u = edge.first;
int64_t w = edge.second;
if (distance[v] != INF && distance[u] > distance[v] + w)
{
distance[u] = distance[v] + w;
reachable[u] = true;
if (n == graph.size() - 1)
{
queue.push(u);
}
}
}
}
}
std::vector<bool> used(graph.size(), false);
while (!queue.empty())
{
auto v = queue.front();
queue.pop();
used[v] = true;
shortest[v] = false;
for (auto edge : graph[v])
{
auto u = edge.first;
if (!used[u])
{
queue.push(u);
}
}
}
distance[s] = 0;
reachable[s] = true;
}
int main()
{
std::ifstream inp_file("path.in");
std::ofstream out_file("path.out");
uint32_t n_vertex = 0, n_edges = 0, start_v = 0;
inp_file >> n_vertex >> n_edges >> start_v;
Graph graph(n_vertex);
for (size_t i = 0; i < n_edges; ++i)
{
uint32_t u = 0, v = 0;
int64_t w = 0;
inp_file >> u >> v >> w;
graph[u - 1].emplace_back(v - 1, w);
}
std::vector<__int128> distances(n_vertex, INF);
std::vector<bool> reachable(n_vertex, false);
std::vector<bool> has_shortest(n_vertex, true);
get_shortest_paths(graph, start_v - 1, distances, reachable, has_shortest);
for (size_t i = 0; i < graph.size(); ++i)
{
if (!reachable[i])
{
out_file << '*' << std::endl;
}
else if (!has_shortest[i])
{
out_file << '-' << std::endl;
}
else
{
out_file << static_cast<int64_t>(distances[i]) << std::endl;
}
}
return 0;
}
<file_sep>/Sem6_Lab_2/topsort.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
enum {WHITE, GRAY, BLACK};
std::vector<int> topsorted;
std::vector<int> color;
std::vector< std::vector<int> > graph;
bool dfs(int v)
{
color[v] = GRAY;
for (auto u : graph[v])
{
if (color[u] == GRAY)
{
return true;
}
if (color[u] == WHITE)
{
if (dfs(u))
{
return true;
}
}
}
topsorted.push_back(v);
color[v] = BLACK;
return false;
}
int main()
{
std::ifstream file_in("topsort.in");
std::ofstream file_out("topsort.out");
unsigned int n_vertices = 0, n_edges = 0;
file_in >> n_vertices >> n_edges;
graph.resize(n_vertices);
color.resize(n_vertices, WHITE);
for (int foo = 0; foo < n_edges; foo++)
{
unsigned int from = 0, to = 0;
file_in >> from >> to;
graph[from - 1].push_back(to - 1);
}
for (int i = 0; i < n_vertices; i++)
{
if (color[i] == WHITE)
{
if (dfs(i))
{
file_out << "-1\n";
return 0;
}
}
}
std::reverse(topsorted.begin(), topsorted.end());
for (auto x : topsorted)
{
file_out << x + 1 << " ";
}
return 0;
}<file_sep>/Sem6_Lab_2/bipartite.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <queue>
int NOT_USED = -1;
std::vector<int> color;
std::vector< std::vector<int> > graph;
bool bfs(int v)
{
color[v] = 0;
std::queue<int> queue;
queue.push(v);
while (!queue.empty())
{
v = queue.front();
queue.pop();
for (int u : graph[v])
{
if (color[u] == NOT_USED)
{
color[u] = color[v] ^ 1;
queue.push(u);
}
if (color[u] == color[v])
{
return true;
}
}
}
return false;
}
int main()
{
std::ifstream file_in("bipartite.in");
std::ofstream file_out("bipartite.out");
unsigned int n_vertices = 0, n_edges = 0;
file_in >> n_vertices >> n_edges;
graph.resize(n_vertices);
color.resize(n_vertices, NOT_USED);
for (int foo = 0; foo < n_edges; ++foo)
{
unsigned int from = 0, to = 0;
file_in >> from >> to;
graph[from - 1].push_back(to - 1);
graph[to - 1].push_back(from - 1);
}
for (int i = 0; i < n_vertices; ++i)
{
if (color[i] == NOT_USED)
{
if (bfs(i))
{
file_out << "NO";
return 0;
}
}
}
file_out << "YES";
return 0;
}
<file_sep>/Lab1/aplusb.cpp
#include <fstream>
using namespace std;
int main() {
ifstream in("aplusb.in");
ofstream out("aplusb.out");
int64_t a = 0, b = 0;
in >> a >> b;
out << static_cast<int64_t>(a + b);
}<file_sep>/README.md
# ITMO algorithms and Data Structures course (IS)
C++ used. Not the best, but not the worst code you've ever seen.
TODO: add additional materials about problems (like neerc, wiki, habr etc. links)
[Кормен (второе издание)](https://vk.com/doc141425588_450774270?hash=d1b363ef3a915d77ff&dl=89cbca136d715683fd)
* [Lab1. Знакомство с проверяющей системой PCMS2.](Lab1) - [Problems](http://neerc.ifmo.ru/teaching/is-algorithms/autumn/lab-1.pdf)
* [a + b](Lab1/aplusb.cpp)
* [a + b^2](Lab1/aplusbb.cpp)
* [Черепашка](Lab1/turtle.cpp)
* [Простая сортировка](Lab1/easy_sort.cpp)
* Знакомство с жителями Сортленда (missed)
* [Lab2. Сортировка слиянием и быстрая сортировка.](Lab2) - [Problems](http://neerc.ifmo.ru/teaching/is-algorithms/autumn/lab-2.pdf)
* [Cортировка (!)](Lab2/sort.cpp)
* [Соревнования по бегу](Lab2/2b.cpp)
* [Число инверсий](Lab2/sort_invertions.cpp)
* [Анти-QuickSort](Lab2/anti_qs.cpp)
* [K-ая порядковая статистика](Lab2/order1.cpp)
* [Lab3. Двоичный поиск, пирамидальная сортировка, цифровая сортировка.](Lab3) - [Problems](http://neerc.ifmo.ru/teaching/is-algorithms/autumn/lab-3.pdf)
* [Двоичный поиск (!)](Lab3/bin_search.cpp)
* [Гирлянда](Lab3/garland.cpp)
* [Пирамида ли?](Lab3/is_heap.cpp)
* [Пирамидальная сортировка](Lab3/heapsort.cpp)
* [Цифровая сортировка](Lab3/radix.cpp)
* [Lab4. Цифровая сортировка, стек и очередь.](Lab4) - [Problems](http://neerc.ifmo.ru/teaching/is-algorithms/autumn/lab-4.pdf)
* [Стек (!)](Lab4/stack.cpp)
* [Очередь](Lab4/queue.cpp)
* [Правильная скобочная последовательность](Lab4/brackets.cpp)
* [Постфиксная запись](Lab4/reverse_polish.cpp)
* [Приоритетная очередь](Lab4/priority_queue.cpp)
* [Lab 5. Двоичное дерево поиска. Интерпретатор языка Quack.](Lab5) - [Problems](http://neerc.ifmo.ru/teaching/is-algorithms/autumn/lab-5.pdf)
* [Высота дерева (!)](Lab5/height.cpp)
* [Проверка корректности](Lab5/is_bst.cpp)
* [Простое двоичное дерево поиска](Lab5/bst.cpp)
* [Интерпретатор языка Quack](Lab5/quack.cpp)
* [Lab 6. Хеш-таблицы.](Lab6) - [Problems](http://neerc.ifmo.ru/teaching/is-algorithms/autumn/lab-6.pdf)
* [Set (!)](Lab6/set.cpp)
* [Map](Lab6/map.cpp)
* [LinkedMap](Lab6/linked_map.cpp)
* [MultiMap](Lab6/multi_map.cpp)
* [Lab 7. AVL-дерево.](Lab7) - [Problems](http://neerc.ifmo.ru/teaching/is-algorithms/autumn/lab-7.pdf)
* [Проверка сбалансированности (!)](Lab7/avl_balance.cpp)
* [Делаю я левый поворот](Lab7/avl_rotate.cpp)
* [Вставка в АВЛ-дерево](Lab7/avl_insert.cpp)
* [Удаление из АВЛ-дерева ](Lab7/avl_deletion.cpp)
* [Упорядоченное множество на АВЛ-дереве](Lab7/AVL_set.cpp)
<file_sep>/Lab7/avl_balance.cpp
#include <fstream>
#include <vector>
struct Node
{
int key;
int height;
int children[2];
Node(int key, int left, int right) : key(key), height(0)
{
children[0] = left;
children[1] = right;
}
};
struct AVL_Tree
{
std::vector<Node *> tree;
int balance(int v)
{
return (tree[v]->children[1] != -1 ? tree[tree[v]->children[1]]->height : 0) -
(tree[v]->children[0] != -1 ? tree[tree[v]->children[0]]->height : 0);
}
void count_height()
{
if (tree.empty())
{
return ;
}
dfs(tree[0]);
}
int height_right(Node *v)
{
return v->children[1] == -1 ? 0 : tree[v->children[1]] -> height;
}
int height_left(Node *v)
{
return v->children[0] == -1 ? 0 : tree[v->children[0]] -> height;
}
void dfs(Node * v)
{
for (int child : v->children)
{
if (child != -1)
{
dfs(tree[child]);
}
}
v->height = std::max(height_left(v), height_right(v)) + 1;
}
};
int main()
{
std::ifstream in("balance.in");
std::ofstream out("balance.out");
size_t n;
in >> n;
auto avl = new AVL_Tree();
for (int i = 0; i < n; i++)
{
int key;
int left, right;
in >> key >> left >> right;
avl->tree.push_back(new Node(key, left-1, right-1));
}
avl->count_height();
for (int i = 0; i < avl->tree.size(); i++)
{
out << avl->balance(i) << std::endl;
}
}
<file_sep>/Sem6_Lab_6/6B.cpp
#include <iostream>
#include <fstream>
#include <vector>
void prefix_function(std::string const & text, std::vector<int> & prefix)
{
prefix.push_back(0);
for (size_t i = 1; i < text.size(); ++i)
{
int border = prefix[i - 1];
while (border > 0 && text[i] != text[border])
{
border = prefix[border - 1];
}
prefix.push_back(border + (text[border] == text[i] ? 1 : 0));
}
}
void kmp(std::string const & text, std::string const & pattern, std::vector<int64_t> & pos)
{
std::vector<int> prefix;
std::string super_string;
super_string = pattern + '$' + text;
prefix_function(super_string, prefix);
for (int i = 0; i < static_cast<int>(text.length() - pattern.length() + 1); ++i)
{
if (prefix[i + 2*pattern.size()] == pattern.size())
{
pos.push_back(i + 1);
}
}
}
int main()
{
std::ifstream inp_file("search2.in");
std::ofstream out_file("search2.out");
std::string text, pattern;
inp_file >> pattern >> text;
std::vector<int64_t> pattern_positions;
kmp(text, pattern, pattern_positions);
out_file << pattern_positions.size() << std::endl;
for (auto x : pattern_positions)
{
out_file << x << ' ';
}
return 0;
}
<file_sep>/Lab7/AVL_set.cpp
#include <fstream>
#include <vector>
#include <queue>
#include <iostream>
enum Side {right=0, left=1};
struct Node
{
int key;
int height;
Node* children[2];
Node(int key, Node * left, Node * right) : key(key), height(1)
{
children[0] = left;
children[1] = right;
}
};
struct AVL_Tree
{
Node * root = nullptr;
int count_balance(Node * v)
{
if (v == nullptr)
{
return 0;
}
return (v->children[1] != nullptr ? v->children[1]->height : 0) -
(v->children[0] != nullptr ? v->children[0]->height : 0);
}
void fix_height(Node * v)
{
v->height = std::max(height_left(v), height_right(v)) + 1;
}
int height_right(Node * v)
{
return v->children[1] == nullptr ? 0 : v->children[1]->height;
}
int height_left(Node * v)
{
return v->children[0] == nullptr ? 0 : v->children[0]->height;
}
Node * rotate(Node * v, int side)
{
Node * u = v->children[side == Side::left ? 1 : 0];
v->children[side == Side::left ? 1 : 0] = u->children[side == Side::left ? 0 : 1];
u->children[side == Side::left ? 0 : 1] = v;
fix_height(v);
fix_height(u);
return u;
}
Node * balance(Node * v)
{
fix_height(v);
if (count_balance(v) > 1)
{
if (count_balance(v->children[1]) < 0)
{
v->children[1] = rotate(v->children[1], Side::right);
}
return rotate(v, Side::left);
}
if (count_balance(v) < -1)
{
if (count_balance(v->children[0]) > 0)
{
v->children[0] = rotate(v->children[0], Side::left);
}
return rotate(v, Side::right);
}
return v;
}
Node * insert(Node * root, int key)
{
if (root == nullptr)
{
return new Node(key, nullptr, nullptr);
}
root->children[key < root->key ? 0 : 1] = insert(root->children[key < root->key ? 0 : 1], key);
return balance(root);
}
Node * find_max(Node * root)
{
return root->children[1] == nullptr ? root : find_max(root->children[1]);
}
Node * remove(Node * root, int key)
{
if (root == nullptr)
{
return nullptr;
}
if (key != root->key)
{
root->children[key < root->key ? 0 : 1] = remove(root->children[key < root->key ? 0 : 1], key);
}
else
{
if (root->children[0] == nullptr && root->children[1] == nullptr)
{
return nullptr;
}
if (root->children[0] == nullptr)
{
root = root->children[1];
return balance(root);
}
Node * r = find_max(root->children[0]);
root->key = r->key;
root->children[0] = remove(root->children[0],r->key);
}
return balance(root);
}
Node * search(Node * root, int key)
{
if (root == nullptr || key == root->key)
{
return root;
}
return search(root->children[key < root->key ? 0 : 1], key);
}
};
int main()
{
std::ifstream in("avlset.in");
std::ofstream out("avlset.out");
size_t n;
in >> n;
auto avl = new AVL_Tree();
for (int i = 0; i < n; i++)
{
std::string cmd;
int key;
in >> cmd >> key;
if (cmd == "A")
{
if (avl->search(avl->root, key) == nullptr)
{
avl->root = avl->insert(avl->root, key);
}
out << avl->count_balance(avl->root) << std::endl;
}
if (cmd == "D")
{
if (avl->search(avl->root, key) != nullptr)
{
avl->root = avl->remove(avl->root, key);
}
out << avl->count_balance(avl->root) << std::endl;
}
if (cmd == "C")
{
out << ((avl->search(avl->root, key) != nullptr) ? "Y" : "N") << std::endl;
}
}
}
<file_sep>/Sem6_Lab_5/5B.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
typedef std::vector< std::vector<char> > Graph;
bool dfs(Graph const & graph, int idx_n,
std::vector<int> & match_m, std::vector<char> & busy, int m)
{
for (int idx_m = 0; idx_m < m; ++idx_m)
{
if (graph[idx_n][idx_m] && !busy[idx_m])
{
busy[idx_m] = 1;
if (match_m[idx_m] == -1 ||
dfs(graph, match_m[idx_m], match_m, busy, m))
{
match_m[idx_m] = idx_n;
return true;
}
}
}
return false;
}
int max_matching(Graph const & graph, int n, int m)
{
std::vector<int> match_m(m, -1);
std::vector<char> busy(m, 0);
for (int idx_n = 0; idx_n < n; ++idx_n)
{
busy.assign(m, 0);
dfs(graph, idx_n, match_m, busy, m);
}
return m - std::count(match_m.begin(), match_m.end(), -1);
}
int main()
{
std::ifstream inp_file("matching.in");
std::ofstream out_file("matching.out");
int n = 0, m = 0, k = 0;
inp_file >> n >> m >> k;
Graph graph(n);
for (auto &v : graph)
{
v.resize(m, 0);
}
for (int i = 0; i < k; ++i)
{
int from = 0, to = 0;
inp_file >> from >> to;
graph[from - 1][to - 1] = 1;
}
out_file << max_matching(graph, n, m);
return 0;
}<file_sep>/Lab4/brackets.cpp
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
struct stack{
vector<char> st;
int size = 0;
explicit stack(int m)
{
st.resize(m);
}
void push(char value)
{
st[++size] = value;
}
char pop()
{
return st[size--];
}
char top()
{
return st[size];
}
bool empty()
{
return size == 0;
}
};
char inv_bracket(char bracket)
{
if (bracket == '[')
return ']';
if (bracket == '(')
return ')';
}
bool check_brackets(string sequence)
{
stack st(sequence.size());
for (auto & bracket : sequence)
{
if (bracket == '(' || bracket == '[')
st.push(bracket);
else
if (!st.empty() && bracket == inv_bracket(st.top()))
st.pop();
else
return false;
}
return st.empty();
}
int main()
{
ifstream input("brackets.in");
ofstream output("brackets.out");
string sequence;
while (getline(input, sequence))
{
output << (check_brackets(sequence) ? "YES" : "NO") << '\n';
}
return 0;
}<file_sep>/Sem6_Lab_1/shortest_way.py
from collections import deque
def count_distances(graph, start):
distances = [10 ** 6] * len(graph)
queue = deque([start])
distances[start] = 0
while queue:
node = queue.popleft()
for child in graph[node]:
if distances[child] > distances[node] + 1:
distances[child] = distances[node] + 1
queue.append(child)
return distances
if __name__ == '__main__':
with open('pathbge1.in', 'r') as file_in, \
open('pathbge1.out', 'w') as file_out:
n_nodes, n_edges = map(int, file_in.readline().rstrip().split())
graph = [[] for _ in range(n_nodes)]
for _ in range(n_edges):
vertex_from, vertex_to = map(lambda x: int(x)-1,
file_in.readline().rstrip().split())
graph[vertex_from].append(vertex_to)
graph[vertex_to].append(vertex_from)
distances = count_distances(graph, 0)
file_out.write(' '.join(map(str, distances)))
<file_sep>/Lab5/bst.cpp
#include <vector>
#include <fstream>
#include <iostream>
#include <exception>
using namespace std;
struct Node
{
int key;
Node* children[2];
Node(int key) : key(key)
{
children[0] = children[1] = nullptr;
}
~Node()
{
delete children[0];
delete children[1];
}
};
class Tree
{
Node* root = nullptr;
Node* search(Node* node, int key)
{
if (node == nullptr || node->key == key)
{
return node;
}
return search(node->children[((key < node->key) ? 0 : 1)], key);
}
Node* insert(Node* node, int key)
{
if (node == nullptr)
{
return new Node(key);
}
node->children[((key < node->key) ? 0 : 1)] =
insert(node->children[((key < node->key) ? 0 : 1)], key);
return node;
}
int children_count(Node* node)
{
int count = 0;
for (int i = 0; i < 2; i++)
{
if (node->children[i] != nullptr)
{
count++;
}
}
return count;
}
Node* remove(Node* node, int key)
{
if (node == nullptr)
{
return node;
}
if (node->key != key)
{
node->children[((key < node->key) ? 0 : 1)] =
remove(node->children[((key < node->key) ? 0 : 1)], key);
}
else
{
int count = children_count(node);
if (count < 2)
{
node = node->children[((node->children[0] != nullptr) ? 0 : 1)];
}
else
{
Node* min_from_right_subtree = minimum(node->children[1]);
node->key = min_from_right_subtree->key;
node->children[1] = remove(node->children[1], node->key);
}
}
return node;
}
Node* minimum(Node* node)
{
if (node->children[0] == nullptr)
{
return node;
}
return minimum(node->children[0]);
}
Node* next(Node* node, int key)
{
Node* current = node;
Node* possible = nullptr;
while (current != nullptr)
{
if (current->key <= key)
{
current = current->children[1];
}
else
{
possible = current;
current = current->children[0];
}
}
return possible;
}
Node* prev(Node* node, int key)
{
Node* current = node;
Node* possible = nullptr;
while (current != nullptr)
{
if (key <= current->key)
{
current = current->children[0];
}
else
{
possible = current;
current = current->children[1];
}
}
return possible;
}
public:
void insert(int key)
{
if (!exists(key))
root = insert(root, key);
}
bool exists(int key)
{
return search(root, key) != nullptr;
}
void remove(int key)
{
if (exists(key))
root = remove(root, key);
}
int next(int key)
{
Node* next_node = next(root, key);
if (next_node == nullptr)
{
throw exception();
}
return next_node->key;
}
int prev(int key)
{
Node* prev_node = prev(root, key);
if (prev_node == nullptr)
{
throw exception();
}
return prev_node->key;
}
~Tree()
{
delete root;
}
};
int main()
{
ifstream input("bstsimple.in");
ofstream output("bstsimple.out");
Tree tree;
while (!input.eof())
{
string operation;
int key;
input >> operation >> key;
if (operation == "insert")
{
tree.insert(key);
}
else if (operation == "delete")
{
tree.remove(key);
}
else if (operation == "exists")
{
output << (tree.exists(key) ? "true" : "false") << endl;
}
else if (operation == "next")
{
try
{
output << tree.next(key) << endl;
}
catch (exception & ex)
{
output << "none" << endl;
}
}
else if (operation == "prev")
{
try
{
output << tree.prev(key) << endl;
}
catch (exception & ex)
{
output << "none" << endl;
}
}
}
return 0;
}<file_sep>/Lab2/sort_invertions.cpp
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
vector<int> a;
vector<int> tmp;
long long invertions = 0;
void copy_array(int left, int right)
{
for (int i = left; i < right; ++i)
{
a[i] = tmp[i];
}
}
void merge(int left, int middle, int right)
{
int i = left;
int j = middle;
for (int k = left; k < right; ++k) {
if (j == right || (i < middle && a[i]<=a[j])) {
tmp[k] = a[i];
i++;
} else {
invertions += middle - i;
tmp[k] = a[j];
j++;
}
}
copy_array(left, right);
}
void merge_sort(int left, int right)
{
if (right <= left + 1)
{
return;
}
int middle = (left + right) / 2;
merge_sort(left, middle);
merge_sort(middle, right);
merge(left, middle, right);
}
int main()
{
ifstream input("inversions.in");
ofstream output("inversions.out");
int n = 0;
input >> n;
a.resize(n);
tmp.resize(n);
for (int i = 0; i < n; ++i)
{
input >> a[i];
}
merge_sort(0, n);
output << invertions << endl;
return 0;
}<file_sep>/Sem6_Lab_3/spantree2.cpp
#include <fstream>
#include <vector>
#include <iostream>
#include <algorithm>
struct DSU
{
private:
unsigned int size;
std::vector<unsigned int> parents;
std::vector<unsigned int> set_size;
public:
explicit
DSU(unsigned int size) : size(size)
{
parents.resize(size);
set_size.resize(size, 0);
for (size_t i = 0; i < size; ++i)
{
parents[i] = i;
}
}
void union_set(unsigned int a, unsigned int b)
{
unsigned int set_a = get_set(a);
unsigned int set_b = get_set(b);
if (set_a == set_b)
{
return;
}
if (set_size[set_a] < set_size[set_b])
{
std::swap(set_a, set_b);
}
parents[set_b] = set_a;
set_size[set_a] += set_size[set_b];
}
unsigned int get_set(unsigned int a)
{
return a == parents[a] ? a : parents[a] = get_set(parents[a]);
}
};
int main()
{
std::ifstream inp_file("spantree2.in");
std::ofstream out_file("spantree2.out");
std::vector< std::pair< int, std::pair<int, int> > > graph;
unsigned int n = 0, m = 0;
inp_file >> n >> m;
for (int i = 0; i < m; ++i)
{
int from = 0, to = 0, w = 0;
inp_file >> from >> to >> w;
graph.push_back({w, {from - 1, to - 1}});
}
DSU components(n);
std::sort(graph.begin(), graph.end());
int mst = 0;
for (auto edge : graph)
{
int u = edge.second.first;
int v = edge.second.second;
int w = edge.first;
if (components.get_set(u) != components.get_set(v))
{
components.union_set(u, v);
mst += w;
}
}
out_file << mst;
return 0;
}<file_sep>/Sem6_Lab_3/spantree.cpp
#include <fstream>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <cassert>
#include <limits>
struct Point
{
int x, y;
unsigned int ind;
Point(int x, int y, unsigned int ind) : x(x), y(y), ind(ind)
{}
Point(std::initializer_list<int> list)
{
assert(list.size() == 3);
x = *list.begin();
y = *(list.begin() + 1);
ind = static_cast<unsigned int> (*(list.begin() + 2));
}
bool operator != (const Point & other)
{
return ind != other.ind;
}
bool operator == (const Point & other)
{
return ind == other.ind;
}
};
double get_length(Point a, Point b)
{
return (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y);
}
int main()
{
std::ifstream inp_file("spantree.in");
std::ofstream out_file("spantree.out");
std::vector< Point > graph;
unsigned int n = 0;
inp_file >> n;
for (int i = 0; i < n; ++i)
{
int x = 0, y = 0;
inp_file >> x >> y;
graph.push_back({x, y, i});
}
double mst = 0;
std::vector<double> dist(n, std::numeric_limits<double>::max());
std::vector<bool> used(n, false);
dist[0] = 0;
for (int i = 0; i < n; ++i)
{
int v = -1;
for (int j = 0; j < n; ++j)
{
if (!used[j] && (v == -1 || dist[j] < dist[v]))
{
v = j;
}
}
used[v] = true;
for (int j = 0; j < n; ++j)
{
double len = get_length(graph[j], graph[v]);
if (!used[j] && dist[j] > len)
{
dist[j] = len;
}
}
}
for (auto x : dist)
{
mst += sqrt(x);
}
out_file << std::setprecision(15) << mst;
return 0;
}<file_sep>/Lab3/bin_search.cpp
#include <fstream>
#include <vector>
using namespace std;
int binsearch_right(vector<int> & a, int x)
{
int left = 0;
int right = a.size();
while (left < right)
{
int middle = (left + right) / 2;
if (x < a[middle])
{
right = middle;
}
else
{
left = middle + 1;
}
}
return a[left - 1] == x ? left : -1;
}
int binsearch_left(vector<int> & a, int x)
{
int left = 0;
int right = a.size();
while (left < right)
{
int middle = (left + right) / 2;
if (a[middle] < x)
{
left = middle + 1;
}
else
{
right = middle;
}
}
return a[left] == x ? left + 1 : -1;
}
int main()
{
ifstream input("binsearch.in");
ofstream output("binsearch.out");
int n, m = 0;
input >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i)
{
input >> a[i];
}
input >> m;
for (int i = 0; i < m; ++i)
{
int x = 0;
input >> x;
int leftmost = binsearch_left(a, x);
int rightmost = binsearch_right(a, x);
output << leftmost << " " << rightmost << "\n";
}
}
<file_sep>/Lab2/2b.cpp
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct runner {
int place;
string name;
string country;
};
vector<runner> a;
vector<runner> tmp;
void inline copy_runner_a_tmp(int i)
{
a[i].name = tmp[i].name;
a[i].place = tmp[i].place;
a[i].country = tmp[i].country;
}
void inline copy_runner_tmp_a(int i, int j)
{
tmp[i].name = a[j].name;
tmp[i].place = a[j].place;
tmp[i].country = a[j].country;
}
void copy_array(int left, int right)
{
for (int i = left; i < right; ++i)
{
a[i] = tmp[i];
}
}
bool compare_runner(int i, int j)
{
return a[i].country <= a[j].country;
}
void merge(int left, int middle, int right)
{
int i = left;
int j = middle;
for (int k = left; k < right; ++k) {
if (j == right || (i < middle && compare_runner(i, j)))
{
tmp[k] = a[i];
i++;
} else {
tmp[k] = a[j];
j++;
}
}
copy_array(left, right);
}
void merge_sort(int left, int right)
{
if (right <= left + 1)
{
return;
}
int middle = (left + right) / 2;
merge_sort(left, middle);
merge_sort(middle, right);
merge(left, middle, right);
}
int main()
{
ifstream input("race.in");
ofstream output("race.out");
int n = 0;
input >> n;
a.resize(n);
tmp.resize(n);
string inp_country;
string inp_runner;
for (int i = 0; i < n; ++i)
{
input >> inp_country >> inp_runner;
a[i].name = inp_runner;
a[i].place = i+1;
a[i].country = inp_country;
}
merge_sort(0, n);
string curr_country = "";
for (int i = 0; i < n; i++)
{
if (curr_country != a[i].country)
{
curr_country = a[i].country;
output << "=== " << a[i].country << " ===" << endl;
}
output << a[i].name << endl;
}
return 0;
}<file_sep>/Lab1/easy_sort.cpp
#include <fstream>
#include <vector>
using namespace std;
void bubble_sort(vector<int> & a) {
int n = a.size();
int temp;
bool was_swap = false;
do {
was_swap = false;
for (int i = 0; i < n-1; i++) {
if (a[i] > a[i+1]) {
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
was_swap = true;
}
}
} while(was_swap);
}
int main() {
ios_base::sync_with_stdio(false);
ifstream fin;
fin.open("smallsort.in");
unsigned int n;
fin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
fin >> a[i];
}
fin.close();
bubble_sort(a);
ofstream fout;
fout.open("smallsort.out");
for (int i = 0; i < n; i++) {
fout << a[i] << " ";
}
fout.close();
return 0;
}<file_sep>/Lab6/map.cpp
#include <iostream>
#include <vector>
#include <fstream>
struct Value
{
const std::string key;
std::string value;
Value * next;
explicit
Value(int hash, std::string key, std::string value) : next(nullptr),
key(key), value(value) {}
// Value() : next(nullptr), hash(0),
// key(0), value(0) {}
};
struct HashSet
{
// const unsigned int MOD = 200001;
const unsigned int MOD = 96557;
std::vector<Value *> table;
HashSet()
{
table.resize(MOD);
}
int hash(const std::string& s)
{
int multiplier = 263;
int prime = 1000000007;
unsigned long long hash = 0;
for (int i = s.size() - 1; i >= 0; --i)
hash = (hash * multiplier + s[i]) % prime;
return static_cast<int> (hash);
}
void add(const std::string &key, const std::string &value)
{
Value * x = get_value(key);
if (x != nullptr)
{
x->value = value;
return;
}
int h = hash(key);
Value * node = new Value(h, key, value);
node->next = table[h % MOD];
table[h % MOD] = node;
}
Value * get_value(const std::string &key)
{
Value * node = table[hash(key) % MOD];
while (node != nullptr)
{
if (node->key == key)
{
return node;
}
node = node->next;
}
return nullptr;
}
std::string get(const std::string &key)
{
Value * node = get_value(key);
return node == nullptr ? "none" : node->value;
}
void remove(const std::string &key)
{
int h = hash(key);
Value * node = table[h % MOD];
Value * prev_node = nullptr;
while (node != nullptr)
{
if (node->key == key)
{
if (prev_node == nullptr)
{
table[h % MOD] = node->next;
}
else
{
prev_node->next = node->next;
node->next = nullptr;
}
return;
}
prev_node = node;
node = node->next;
}
}
};
int main()
{
std::ifstream input("map.in");
std::ofstream output("map.out");
HashSet set;
while (!input.eof())
{
std::string operation;
std::string key;
input >> operation >> key;
if (operation == "put")
{
std::string value;
input >> value;
set.add(key, value);
}
if (operation == "delete")
{
set.remove(key);
}
if (operation == "get")
{
output << set.get(key) << std::endl;
}
}
return 0;
} | aa575026c00001180b22354ee1f0ca3db24ea499 | [
"Markdown",
"Python",
"C++"
] | 54 | Python | dxahtepb/ifmo-algo-is | 81610fc86302a71e5f5b9df0f047a6ded66b186d | 17b394637e8b0e530134dfc6b12fe71245b10702 |
refs/heads/master | <file_sep>package processor;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// just infinity loop, it'll stop when user input 0
while (true) {
boolean move = Menu.chooseAction();
if (!move) {
break;
}
}
}
}
<file_sep>package processor;
import java.util.Scanner;
public class InverseMatrix {
static Scanner scanner = new Scanner(System.in);
public static void inverseMatrix() {
// получаем матрицу, т.е. ее параметры
System.out.print("Enter matrix size: ");
int rows = scanner.nextInt();
int columns = scanner.nextInt();
if (rows != columns) {
System.out.printf("%s", "Man, you made mistake. I can't inverse not square matrix");
return;
}
ExampleOfMatrix matrix = new ExampleOfMatrix(rows, columns);
System.out.println("Enter matrix");
matrix.enterMatrix();
double determinant = Determined.findDeterminant(matrix);
// here i try to find determinant
if (determinant == 0) {
System.out.println("Sorry, i can't find inverse matrix");
return;
}
ExampleOfMatrix bufferMatrix = new ExampleOfMatrix(matrix.getRows(), matrix.getColumns());
for (int i = 0; i < matrix.getRows(); i++) {
for (int j = 0; j < matrix.getColumns(); j++) {
ExampleOfMatrix subMatrix = Determined.makeSubMatrix(matrix, i, j);
double value = Determined.findDeterminant(subMatrix);
// находим определитель для каждой позиции
if ((i + j) % 2 == 1) { // if coordinates of minor even, then i
// change sign
value *= -1;
}
bufferMatrix.setElement(i, j, value);
// System.out.println(value);
// subMatrix.printMatrix();
}
}
// here i transpose matrix which i get above
ExampleOfMatrix aHalfAnswer = TransposeMatrix.tMainDiagonal(bufferMatrix);
MultiplyToAConst.giveResultOfMultiply(1 / determinant, aHalfAnswer).printMatrix();
}
}
| 0a6ad0e26b620303a045324aa2ee22f56e0acac3 | [
"Java"
] | 2 | Java | Kageho/Numeric-Matrix-Processor | 4c499eb528546417133d80fccd9b155c6ac02954 | e69e11b9d44ea7f029492e4564d250367a07c7f7 |
refs/heads/master | <file_sep>package com.example.administrator.checkpermissionincode;
import android.content.Context;
import android.content.pm.PackageManager;
/**
* Created by Administrator on 2015/10/1.
*/
public class Hello {
public static final String PERMISSION_SAY_HELLO = "com.example.administrator.checkpermissionincode.permission.SAY_HELLO";
public static void sayHello(Context context){
int checkResult = context.checkCallingOrSelfPermission(PERMISSION_SAY_HELLO);//判断是否具有该权限
if (checkResult!= PackageManager.PERMISSION_GRANTED){
throw new SecurityException("执行sayHELLO方法需要com.example.administrator.checkpermissionincode.permission.SAY_HELLO权限");
}
System.out.println("hello 即可学院");
}
}
| 29c63ceed5591db420e617b70d8b487af3815034 | [
"Java"
] | 1 | Java | shisichao/Android_base | e33be7e1020c1b91b2081dd70bde5a64885f4578 | f8256210e77e670bae10e30c108f97a0ab6fd431 |
refs/heads/master | <file_sep>import React from 'react';
function HomePage() {
return (
<div>
<div class="jumbotron">
<h1 class="display-4"><NAME></h1>
<h6><i class="fas fa-envelope"></i> <EMAIL> | <i class="fas fa-mobile"></i> 437-345-8594 | <i class="fab fa-linkedin"></i> linkedin.com/in/koustubmanchiraju</h6>
<hr class="my-4" />
<h4>ACADEMICS</h4>
<p class="lead"><i class="fas fa-hand-point-right"></i> Post Graduate Diploma in Mobile Application Design and Development
– Lambton College, Toronto-JAN 2019
<br /><i class="fas fa-hand-point-right"></i> Bachelor of Technology in Information Technology – JNTUH, Hyderabad, India-MAY 2016</p>
<hr class="my-4" />
<h4>TECHNICAL SKILLS</h4>
<p class="lead"><i class="fas fa-angle-right"></i> Proficiency in Web Development: JQuery, REST, Bootstrap, PHP, HTML, CSS, Node.js, Express.js, React.js, JEST
<br /><i class="fas fa-angle-right"></i> Academic and professional programming experience: Swift, Java, Algorithmic strategies, Data structures, Design Patterns, Git. Strong backend concepts: MySQL, SQL, MongoDB
<br /><i class="fas fa-angle-right"></i> Expertise in mobile application development: iOS app development. Basic experience: Android SDK
</p>
<hr/>
<h4>EXPERIENCE <i class="fas fa-laptop-code"></i></h4>
<h6>MOBILE APPLICATION DEVELOPER – ALLIANCE CONSULTING NETWORK,<small class='text-muted'>Toronto</small></h6>
<p class='lead'>
<i class="fas fa-angle-right"></i> Developed an e-learning platform native app for iOS that automated learning and Q&A among students and instructors using Swift, iOS Core Data, Location, CoreML thereby reducing manual intervention
<br/> <i class="fas fa-angle-right"></i> Implemented MVC architecture and RESTful API in C#, ASP.NET for backend system
<br/> <i class="fas fa-angle-right"></i> Created UX design mockups, wireframes and storyboards using Material Design for iOS
<br/> <i class="fas fa-angle-right"></i> Worked efficiently in an agile-scrum lifecycle to develop robust software in a timely manner
</p>
</div>
</div>
);
}
export default HomePage;<file_sep>import React from 'react';
function ProjectInfo(props) {
console.log('Entering Project Info components');
const projectCard = {
margin:"20px",
flex:1,
flexDirection:'row',
h5 : {
fontSize:"4vw"
}
}
return (
<div class='jumbotron' style={projectCard}>
<h5 class="card-title text-center " style={projectCard.h5}>{props.ProjectName}</h5>
<p class="card-text lead"><i class="fas fa-angle-right"></i> {props.ProjectDescription}</p>
<p class="card-text lead"><i class="fas fa-angle-right"></i> {props.ProjectDescription2}</p>
<h6 class="display-6 text-right">{props.ProjectDate}</h6>
</div>
);
}
export default ProjectInfo;<file_sep>import React from 'react';
import project from './Projects.json';
import ProjectInfo from './ProjectInfo.js';
function Projects(){
console.log(`[entering projects]`);
return (
<div class='container'>
<h1 class='display-4 text-center'>Projects</h1>
{project.map( project=><div ><ProjectInfo {...project} /></div>)}
</div>
);
}
export default Projects;<file_sep>import React from 'react';
import { Link, useLocation } from "react-router-dom";
function Navbar() {
const location = useLocation();
return (
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<Link to="/" className={location.pathname === "/" ? "nav-link active" : "nav-link"}>
Portfolio <i class="fas fa-id-card"></i>
</Link>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<Link to="/Home" className={location.pathname === "/Home" ? "nav-link active" : "nav-link"}>
Home
</Link>
</li>
<li class="nav-item active">
<Link to="/Project" className={location.pathname === "/Project" ? "nav-link active" : "nav-link"}>
Projects
</Link>
</li>
</ul>
</div>
</nav>
);
}
export default Navbar; | 68d3eb83f22bb69a886fa61020e18e49b414f6cf | [
"JavaScript"
] | 4 | JavaScript | koustub/reactportfolio | 8d061272babf2b03e0bfc21cfa35951dc977bc28 | 65f1cc8fc29bfa681fa6cf6b58224954f9c925c8 |
refs/heads/main | <repo_name>WaltCastillo/elbicho<file_sep>/src/components/App.js
import React, { Component } from "react";
import {Navbar} from './navbar';
export const App = ()=>{
return (
<>
<Navbar/>
<div>
<h1>My React App !</h1>
</div>
</>
)
}
| 54c8de0973436f59b4bcd7908577ffba53abb574 | [
"JavaScript"
] | 1 | JavaScript | WaltCastillo/elbicho | 1fce4af8c122324ec22ed237df2e0f33d7919404 | 95913af59bc0e6e83145ae9afd1e9b8ca22b6330 |
refs/heads/master | <file_sep>#!/usr/bin/env bash
# set -x
set -e
aws sts get-caller-identity 1>/dev/null 2>/dev/null || ( echo "Cannot talk to AWS -- \`aws sts get-caller-identity\` failed -- bailing out." ; exit 99 )
confirm(){
__PROMPT=${1:-"Continue?"}" (y/N) > "
read -p "$__PROMPT" __CONT
if [[ "$__CONT" = "y" ]]; then
echo "continuing..."
else
echo "confirmation negative; bailing out!"
exit 99
fi
}
if [[ -z "$1" ]]; then
read -p "Hosted zone name: " _HOSTED_ZONE_NAME
else
_HOSTED_ZONE_NAME="$1"
fi
if [[ -z "$2" ]]; then
read -p "This computers hostname (or any name to remember it by): " _MY_HOSTNAME
else
_MY_HOSTNAME="$2"
fi
SAFE_HOSTNAME=$( echo "$_MY_HOSTNAME" | sed 's/\./-/g' )
echo "Using hosted zone: $_HOSTED_ZONE_NAME"
echo "Using hostname (this pc): $_MY_HOSTNAME (safe: $SAFE_HOSTNAME)"
confirm
# remove trailing periods if they exist
HOSTED_ZONE_NAME=$( echo "$_HOSTED_ZONE_NAME" | sed 's/\.$//g' )
# trailing period important
HOSTED_ZONE_ID=$( aws route53 list-hosted-zones-by-name | jq -r '.HostedZones | map(select( .Name == "'$HOSTED_ZONE_NAME'." )) | .[0]' )
if [[ "$HOSTED_ZONE_ID" = "null" ]]; then
echo "Error: hosted zone not found. try 'aws route53 list-hosted-zones-by-name'"
exit 2
fi
HOSTED_ZONE_ID=$( echo "$HOSTED_ZONE_ID" | jq -r '.Id' | sed 's/\/hostedzone\///g' )
echo -n "Hosted Zone ID: $HOSTED_ZONE_ID"
HOSTED_ZONE_NAME_SAFE=$( echo "$HOSTED_ZONE_NAME" | sed 's/\./-/g' )
#POLICY_PATH=/ddns/host-$SAFE_HOSTNAME/zone-$HOSTED_ZONE_NAME_SAFE/
POLICY_PATH=/ddns/updater/
POLICY_NAME=ddns-update-zone--$HOSTED_ZONE_NAME_SAFE
POLICY_FULL="$POLICY_PATH$POLICY_NAME"
IAM_USER_NAME="ddns.updater.$HOSTED_ZONE_NAME_SAFE"
echo "Policy: $POLICY_FULL"
echo "Checking if it exists..."
CHECK_EXISTING=$(aws iam list-policies --query "Policies[?PolicyName == '$POLICY_NAME' && Path == '$POLICY_PATH']" | jq -r .[0])
if [[ "$CHECK_EXISTING" != "null" ]]; then
POLICY_ARN=$( echo ${CHECK_EXISTING} | jq -r '.Arn' )
echo "Existing policy: $POLICY_ARN"
echo "Skipping creation of new policy..."
else
confirm "Really set this up?"
POLICY_RESP=$(aws iam create-policy --path "$POLICY_PATH" --policy-name "$POLICY_NAME" --policy-document "$(cat ddns_iam_policy.json | sed 's/{YOUR_ZONEID_HERE}/'$HOSTED_ZONE_ID'/g')")
POLICY_ARN=$( echo "$POLICY_RESP" | jq -r .Policy.Arn )
echo "Policy created! ARN: ${POLICY_ARN}"
GET_POLICY_OUTPUT=$(aws iam get-policy --policy-arn $( echo "$POLICY_RESP" | jq -r .Policy.Arn ))
echo "get-policy: $GET_POLICY_OUTPUT"
fi
echo "Creating user: $IAM_USER_NAME"
IAM_USER_ARN=$( aws iam create-user --user-name $IAM_USER_NAME --query 'User.Arn' --output text || echo 'Error: Failed to create user... continuing.' >&2 )
echo "Attaching policy to IAM user"
aws iam attach-user-policy --user-name $IAM_USER_NAME --policy-arn ${POLICY_ARN} || echo "Error: Failed to attach policy... continuing."
echo "Creating access keys"
ACCESS_KEY_OUTPUT=$( aws iam create-access-key --user-name $IAM_USER_NAME --query 'AccessKey' | jq -r )
echo "Created keys: $ACCESSS_KEY_OUTPUT"
AAKI=$( echo "$ACCESS_KEY_OUTPUT" | jq -r '.AccessKeyId' )
ASAK=$( echo "$ACCESS_KEY_OUTPUT" | jq -r '.SecretAccessKey' )
PROFILE_NAME="ddns-$HOSTED_ZONE_NAME_SAFE"
aws configure --profile $PROFILE_NAME set aws_access_key_id ${AAKI}
aws configure --profile $PROFILE_NAME set aws_secret_access_key ${ASAK}
echo -e "add to cron or where-ever:\n */3 * * * * /usr/bin/env bash -l -c 'cd $PWD && python3 dns_update.py --profile $PROFILE_NAME --zone $HOSTED_ZONE_ID --domain $HOSTED_ZONE_NAME --ttl 180 --record YOUR.SUB.DOMAIN'"
echo -e "\nDONE!"
echo "aws user $IAM_USER_NAME configured under profile $PROFILE_NAME."
| 3a8c8195f27c3a860b74678eb5bf7e25c3bed8b3 | [
"Shell"
] | 1 | Shell | XertroV/aws-dyndns | 2de66b008a410ff50d868f0e04109a9905d28e7a | cc2978c483d6b584d4515c50ddb890ad1e98be65 |
refs/heads/master | <repo_name>bachan37/javascript_design_pattern<file_sep>/001_chain.js
var Calc = function(){
var s = 0;
this.add = function(arg){
s += arg;
return this;
};
this.sub = function(arg){
s -= arg;
return this;
};
this.mul = function(arg){
s *= arg;
return this;
};
this.eql = function(){
return s;
};
};
new Calc().
add(1).
add(2).
sub(1).
mul(3).
eql();
<file_sep>/argument_object.js
var x = function(){
var s = 0;
for(var i = 0; i < arguments.length; i++)
s += arguments[i];
return s;
}
| 6651f788c4206c7b8a0c1a14b28fbcd683592f24 | [
"JavaScript"
] | 2 | JavaScript | bachan37/javascript_design_pattern | 773dd1fc1cfafdba5beba277fe559c81abdfe389 | 11ce570f1089d363e15f2ca467faba21a6c00e32 |
refs/heads/master | <file_sep>#include <iostream>
float convert (float);
int main()
{
float farenheit;
float celsius;
std::cout << "Please enter the temperature in Farenheit: ";
std::cin >> farenheit;
celsius = convert(farenheit);
std::cout << "\nHere's the temperature in Celsius: ";
std::cout << celsius << "\n";
return 0;
}
// function to convert farenheit to celsius
float convert(float farenheit)
{
float celsius;
celsius = ((farenheit -32) * 5) / 9;
return celsius;
}<file_sep>#include <iostream>
int main()
{
int input;
std::cout << "Pick a number between 1 and 10!: ";
std::cin >> input;
if (input >= 5)
{
if (input == 6)
{
std::cout << "\nYou picked 6.\n";
return 0;
}
if (input == 7)
{
std::cout << "\nYou picked 7.\n";
return 0;
}
if (input == 8)
{
std::cout << "\nYou picked 8.\n";
return 0;
}
if (input == 9)
{
std::cout << "\nYou picked 9.\n";
return 0;
}
if (input == 10)
{
std::cout << "\nYou picked 10.\n";
return 0;
}
}
else
std::cout << "\nYou picked 5 or less\n";
return 0;
}<file_sep>#include <iostream>
int findArea(int length, int width); // function prototype
int main()
{
int length;
int width;
int area;
std::cout << "\nHow wide is your yard? ";
std::cin >> width;
std::cout << "\nHow long is your yard? ";
std::cin >> length;
area = findArea(length, width);
std::cout << "\nYour yard is ";
std::cout << area;
std::cout << " square feet\n\n";
return 0;
}
// function definition
int findArea(int l, int w)
{
return l * w;
}
<file_sep>#include <iostream>
int main()
{
// set up enumeration
enum Direction { North, Northeast, East, Southeast, South,
Southwest, West, Northwest };
// create a variable to hold it
Direction heading;
//initialize that variable
heading = Southeast;
std::cout << "Moving " << heading << std::endl;
return 0;
}
<file_sep>Hello!
This repo is my first first repo as a Github user.
I'm currently learning C++ and am reading through a book about the language.
I'm following along with the activities in the book.
I decided to upload all of my plain text files onto this repo as a make them,
that way i can review them when i'm away from my main computer.
If you stumbled onto this repo, just ignore it.
It's only for me and i'm not an experienced Github user so i don't know how to make it private.
Thank you!
<file_sep>#include <iostream>
int main()
{
int grade;
std::cout << "Enter a grade (1-100): ";
std::cin >> grade;
if (grade >= 70)
{
if (grade >= 90)
{
std::cout << "\nYou got an A. Great Job!\n";
return 0;
}
if (grade >= 80)
{
std::cout << "\nYou got a B. Good work!\n";
return 0;
}
std::cout << "\nYou got a C. Perfectly adequate!\n";
}
else
std::cout << "\nYou got an F. I failed as a parent!\n";
return 0;
}<file_sep>#include <iostream>
int main()
{
//define character values
auto strength = 80;
auto accuracy = 45.5;
auto dexterity = 24.0;
//define constants
const auto MAXIMUM = 50;
//calculate character combat stats
auto attack = strength * (accuracy / MAXIMUM);
auto damage = strength * (dexterity / MAXIMUM);
std::cout << "\nAttack rating: " << attack << "\n";
std::cout << "Damage rating: " << damage << "\n";
}<file_sep>#include <iostream>
int main()
{
std::cout << "The size of an integer:\t\t";
std::cout << sizeof(int) << " bytes\n";
std::cout << "The size of a short integer:\t";
std::cout << sizeof(short) << " bytes\n";
std::cout << "The size of a long integer:\t";
std::cout << sizeof(long) << " bytes\n";
std::cout << "The size of a character:\t";
std::cout << sizeof(char) << " bytes\n";
std::cout << "The size of a boolean:\t\t";
std::cout << sizeof(bool) << " bytes\n";
std::cout << "The size of a float:\t\t";
std::cout << sizeof(float) << " bytes\n";
std::cout << "The size of a double float:\t";
std::cout << sizeof(double) << " bytes\n";
std::cout << "The size of a long long int:\t";
std::cout << sizeof(long long int) << " bytes\n";
return 0;
}<file_sep>#include <iostream>
int add(int x, int y)
{
// add the numbers x and y together and return the sum
std::cout << "Running calculator ...\n";
return (x+y);
}
int main()
{
/* this program calls an add() function to add two different
sets of numbers together and display the results. The
add() function doesn't do anything unless it is called by
a line in the main() function. */
std::cout << "What is 867 + 5309?\n";
std::cout << "The sum is " << add(867, 5309) << "\n\n";
std::cout << "What is 777 + 9311?\n";
std::cout << "The sum is " << add(777, 9311) << "\n";
return 0;
}<file_sep>#include <iostream>
int main()
{
// set up width and length
unsigned short width = 26, length;
length = 40;
//create an unsigned short initialized with the
// result of multiplying width by length
unsigned short area = width * length;
std::cout << "Width: " << width << "\n";
std::cout << "Length: " << length << "\n";
std::cout << "Area: " <<area << "\n";
return 0;
}
<file_sep>#include <iostream>
int main()
{
// create a type definition
typedef unsigned short USHORT;
//set up width and length
USHORT width = 26;
USHORT length = 40;
//Create an unsigned short initialized with the
//result of multiplying width by length
USHORT area = width * length;
std::cout << "Width: " << width << "\n";
std::cout << "Length: " << length << "\n";
std::cout << "Area: " << area << "\n";
return 0;
}<file_sep>#include <iostream>
int main()
{
int grade;
std::cout << "Enter a grade (1-100): ";
std::cin >> grade;
if (grade >= 70)
std::cout << "\nYou passed. Hooray!\n";
else
std::cout << "\nYou failed. Sigh.\n";
return 0;
}<file_sep>#include <iostream>
int main()
{
int x = 12, y = 42, z = 88;
std::cout << "Before -- x: " << x << " y: " << y;
std::cout << " z: " << z << "\n\n";
z = x = y + 13;
std::cout << "After -- x: " << x << " y: " << y;
std::cout << " z: " << z << "\n";
return 0;
}<file_sep>#include <iostream>
void convert();
float farenheit;
float celsius;
int main()
{
std::cout << "Please enter the temperature in Farenheit: ";
std::cin >> farenheit;;
convert();
std::cout << "\nHere's the temperature in Celsius: ";
std::cout << celsius << "\n";
return 0;
}
// function to convert farenheit to celsius
void convert()
{
celsius = ((farenheit -32) * 5) / 9;
}<file_sep>#include <iostream>
int main()
{
int year = 2016;
std::cout << "The year " << ++year << " passes.\n";
std::cout << "The year " << ++year << " passes.\n";
std::cout << "The year " << ++year << " passes.\n";
std::cout << "\nIt is now " << year << ".";
std::cout << " Have the Chicago Cubs won the World Series yet?\n";
std::cout << "\nThe year " << year++ << " passes.\n";
std::cout << "The year " << year++ << " passes.\n";
std::cout << "The year " << year++ << " passes.\n";
std::cout << "\nSurely the Cubs have won the World Series by now.\n";
return 0;
} | 81f5a99f1f9b16016f2aa6d4860527239a0845a7 | [
"Markdown",
"C++"
] | 15 | C++ | Mvrd0ChF3/First-Repo | b20e5e526a7abb3975ecc269ff2f7178dcfe7875 | c0c43f2ce0c81713cd6464fe69f1ad7e111aeec2 |
refs/heads/master | <repo_name>jameson75/XFileViewer<file_sep>/XViewLib/World/PathTracker.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.Animation;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.Utils;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.World
{
public class PathTracker
{
private Path _path = null;
public ITransformable Target { get; set; }
public Path Path { get { return _path; } }
public float PathNodeMinDistance { get; set; }
public PathTracker()
{
_path = new Path();
_path.SmoothingEnabled = false;
}
public void Update(SimTime simTime)
{
PathNode lastNode = Path.GetNodes().LastOrDefault();
if (lastNode == null || PathNodeMinDistance < Vector3.Distance(Target.Transform.Translation, lastNode.Transform.Translation) )
Path.AddNode(new PathNode() { Transform = Target.Transform }, true);
}
}
}
<file_sep>/XViewLib/ContentManagement/ContentImporter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.IO;
using SharpDX;
using SharpDX.Direct3D11;
using CoreTransform = OpenJelly.XFileViewer.Core.Animation.Transform;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.Animation;
using OpenJelly.XFileViewer.Core.Animation.Controllers;
using OpenJelly.XFileViewer.Core.Utils.Toolkit;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Content
{
public static class ContentImporter
{
public static SpriteFont LoadFont(Device graphicsDevice, string resource)
{
SpriteFont font = new SpriteFont(graphicsDevice, resource);
return font;
}
public static Texture2D LoadTexture(DeviceContext deviceContext, string fileName)
{
IntPtr _nativeTextureResource = UnsafeNativeMethods.CreateTextureFromFile(deviceContext.NativePointer, fileName);
return new Texture2D(_nativeTextureResource);
}
public static Texture2D LoadTextureCube(DeviceContext deviceContext, string[] fileNames)
{
if (fileNames.Length != 6)
throw new InvalidOperationException("Number of specified file names is less or greater than 6");
Texture2D[] _textures = new Texture2D[6];
Texture2D[] _stagingTextures = new Texture2D[6];
DataBox[] _dataBoxes = new DataBox[6];
for(int i = 0; i < _textures.Length; i++)
_textures[i] = LoadTexture(deviceContext, fileNames[i]);
//NOTE: We have to first copy the textures into a "staging" area because the textures
//returned by LoadTexture() are all GPU-only.
Texture2DDescription stagingTextureDesc = _textures[0].Description;
stagingTextureDesc.BindFlags = BindFlags.None;
stagingTextureDesc.CpuAccessFlags = CpuAccessFlags.Read;
stagingTextureDesc.Usage = ResourceUsage.Staging;
for (int i = 0; i < _textures.Length; i++)
{
_stagingTextures[i] = new Texture2D(deviceContext.Device, stagingTextureDesc);
deviceContext.CopyResource(_textures[i], _stagingTextures[i]);
}
//NOTE: we create a separate loop so that the DeviceContext.CopyResource() operation in the prior loop
//can finish as many async operations as possible before we call DeviceContext.MapSubResource() on each
//respective texture.
for (int i = 0; i < _textures.Length; i++)
_dataBoxes[i] = deviceContext.MapSubresource(_stagingTextures[i], 0, MapMode.Read, MapFlags.None);
Texture2DDescription cubeDescription = _textures[0].Description;
cubeDescription.ArraySize = 6;
cubeDescription.OptionFlags = ResourceOptionFlags.TextureCube;
cubeDescription.Usage = ResourceUsage.Default;
cubeDescription.CpuAccessFlags = CpuAccessFlags.None;
Texture2D cubeTexture = new Texture2D(deviceContext.Device, cubeDescription, _dataBoxes );
for (int i = 0; i < _textures.Length; i++)
deviceContext.UnmapSubresource(_stagingTextures[i], 0);
return cubeTexture;
}
public static Model ImportX(IVisualization context, string fileName, byte[] shaderByteCode, XFileChannels channels, XFileImportOptions options = XFileImportOptions.None, List<string> textureNames = null)
{
Model result = null;
Mesh mesh = null;
Frame rootBoneFrame = null;
List<KeyframeAnimationController> animationControllers = null;
List<SkinOffset> skinOffsets = null;
XFileTextDocument doc = new XFileTextDocument();
//Throw an error for unsupported channels.
//----------------------------------------
if ((channels & XFileChannels.MeshNormals) != 0 ||
(channels & XFileChannels.DeclTextureCoords2) != 0 ||
(channels & XFileChannels.MeshTextureCoords1) != 0 ||
(channels & XFileChannels.MeshTextureCoords2) != 0 ||
(channels & XFileChannels.MeshVertexColors) != 0)
throw new NotSupportedException("One or more of the specified channels is not supported.");
//Throw an error for conflicting channels and/or options
//Conflict 1: Both color and texture channel specified.
//Conflict 2: Instancing enabled for skinned mesh (we don't support this yet).
//-----------------------------------------------------------------------------
if (((channels & XFileChannels.MeshVertexColors) != 0 ||
(channels & XFileChannels.DefaultMaterialColor) != 0 ||
(channels & XFileChannels.DeclColor) != 0) &&
((channels & XFileChannels.MeshTextureCoords1) != 0 ||
(channels & XFileChannels.MeshTextureCoords2) != 0) ||
(channels.HasFlag(XFileChannels.Skinning) && options.HasFlag(XFileImportOptions.EnableInstancing)))
throw new NotSupportedException("Conflicting channels specified.");
//Read X-File Data/DOM
//--------------------
doc.Load(System.IO.File.Open(fileName, FileMode.Open, FileAccess.ReadWrite));
//Access X-File's first mesh Data and it's frame
//----------------------------------------------
XFileFrameObject xMeshFrame = (XFileFrameObject)doc.DataObjects.GetDataObject<XFileFrameObject>(1);
XFileMeshObject xMesh = xMeshFrame.Meshes[0];
//Calculate mesh bounding box from mesh Data
//------------------------------------------
BoundingBox boundingBox = BoundingBox.FromPoints(xMesh.Vertices.Select(v => new Vector3(v.X, v.Y, v.Z)).ToArray());
//Construct model vertex indices from mesh data
//----------------------------------------------
short[] _indices = xMesh.Faces.SelectMany(e => e.FaceVertexIndices.Select(x => (short)x)).ToArray();
//Extract texture coords from mesh data
//-------------------------------------
Vector2[] texCoords = null;
if ((channels & XFileChannels.DeclTextureCoords1) != 0)
{
texCoords = xMesh.DeclData.GetTextureCoords();
if (texCoords == null)
{
if (!options.HasFlag(XFileImportOptions.IgnoreMissingTexCoords))
throw new InvalidOperationException("Expected texture coordinate data was not present.");
else
texCoords = xMesh.Vertices.Select(v => Vector2.Zero).ToArray();
}
else
{
if (textureNames != null)
textureNames.AddRange(doc.GetMeshMaterials(xMesh)
.Where(m => m.TextureFilename != null)
.Select(m => m.TextureFilename));
}
}
//Extract normals.
//----------------
Vector3[] normals = null;
if ((channels & XFileChannels.DeclNormals) != 0)
{
normals = xMesh.DeclData.GetNormals();
if (normals == null)
{
if (!options.HasFlag(XFileImportOptions.IgnoreMissingNormals))
throw new InvalidOperationException("Expected normal data was not present.");
else
normals = xMesh.Vertices.Select(v=> Vector3.Zero).ToArray();
}
}
//Extract Color from default material
//-----------------------------------
Color[] colors = null;
if ((channels & XFileChannels.DefaultMaterialColor) != 0)
{
XFileMaterialObject defaultMaterial = null;
if (xMesh.MeshMaterialList != null)
{
if (xMesh.MeshMaterialList.MaterialRefs != null)
defaultMaterial = doc.DataObjects.GetDataObject<XFileMaterialObject>(0);
else if (xMesh.MeshMaterialList.Materials != null)
defaultMaterial = xMesh.MeshMaterialList.Materials[0];
colors = xMesh.Vertices.Select(v => new Color(defaultMaterial.FaceColor.Red,
defaultMaterial.FaceColor.Green,
defaultMaterial.FaceColor.Blue,
1.0f)).ToArray();
}
if (colors == null)
{
if (!options.HasFlag(XFileImportOptions.IgnoreMissingColors))
throw new InvalidOperationException("Expected material color data was not present.");
else
colors = xMesh.Vertices.Select(v => Color.Transparent).ToArray();
}
}
if ((channels & XFileChannels.Skinning) != 0)
{
if (xMesh.SkinWeightsCollection.Count == 0)
throw new InvalidOperationException("Expected skin data was not present.");
//Construct skinned model vertices from mesh data
//-----------------------------------------------
VertexPositionNormalTextureSkin[] _vertices = xMesh.Vertices.Select((v, i) => new VertexPositionNormalTextureSkin()
{
Position = new Vector4(v.X, v.Y, v.Z, 1.0f),
Normal = normals[i],
TextureCoord = texCoords[i]
}).ToArray();
//Convert skinning information in .x file to skinning information required by a skinning shader.
//(A skinning shader associates each vertex with 4 bone indices and 4 bone weights - we extract this
//information from SkinWeights data object).
//-------------------------------------------------------------------------------------------------
List<float>[] weights = new List<float>[_vertices.Length];
List<int>[] boneIndices = new List<int>[_vertices.Length];
List<string>[] boneNames = new List<string>[_vertices.Length];
skinOffsets = new List<SkinOffset>();
for (int i = 0; i < xMesh.SkinWeightsCollection.Count; i++)
{
XFileSkinWeightsObject xSkinWeights = xMesh.SkinWeightsCollection[i];
CoreTransform skinOffsetTransform = new CoreTransform(new Matrix(xSkinWeights.MatrixOffset.m));
skinOffsets.Add(new SkinOffset() { Name = xSkinWeights.TransformNodeName, Transform = skinOffsetTransform });
for (int j = 0; j < xSkinWeights.NWeights; j++)
{
int k = xSkinWeights.VertexIndices[j];
if (boneIndices[k] == null)
boneIndices[k] = new List<int>();
boneIndices[k].Add(i);
if (weights[k] == null)
weights[k] = new List<float>();
weights[k].Add(xSkinWeights.Weights[j]);
}
}
for (int i = 0; i < _vertices.Length; i++)
{
float[] weightValues = new float[4] { 0, 0, 0, 0 };
int[] boneIndicesValues = new int[4] { 0, 0, 0, 0 };
if (weights[i] != null)
{
float[] _weights = weights[i].ToArray();
//TODO: assert that _weights.Length <= weightValues.Length (we assume the .x file will have no more than 4 per vertex).
Array.Copy(_weights, weightValues, _weights.Length);
}
if (boneIndices[i] != null)
{
int[] _boneIndices = boneIndices[i].ToArray();
//TODO: assert that _bondIndices.Length <= boneIndicesValues.Length (we assume the .x file will have no more than 4 per vertex).
Array.Copy(_boneIndices, boneIndicesValues, _boneIndices.Length);
}
_vertices[i].Weights = new Vector4(weightValues);
_vertices[i].BoneIndices = new Int4(boneIndicesValues);
}
//Construct bone hierarchy (skeleton) from frame data
//----------------------------------------------------
//****************************************************
//NOTE: It is assumed that
//there is only one bone at the root and, therefore,
//one bone-frame at the root level of the X-File
//****************************************************
XFileFrameObject xRootBoneFrame = doc.DataObjects.GetDataObject<XFileFrameObject>(2);
rootBoneFrame = new Frame() { Name = xRootBoneFrame.Name, Transform = new CoreTransform(new Matrix(xRootBoneFrame.FrameTransformMatrix.m)) };
BuildBoneFrameHierarchy(xRootBoneFrame, rootBoneFrame, skinOffsets);
if ((channels & XFileChannels.Animation) != 0)
{
//Construct animation data from frame data
//----------------------------------------
XFileAnimationSetObject xAnimationSet = doc.DataObjects.GetDataObject<XFileAnimationSetObject>(1);
if (xAnimationSet == null)
throw new InvalidOperationException("Execpted animation data was not present.");
List<Frame> targetFrames = rootBoneFrame.FlattenToList();
animationControllers = BuildAnimationRig(xAnimationSet, targetFrames);
}
mesh = ContentBuilder.BuildMesh<VertexPositionNormalTextureSkin>(context.GraphicsDevice, shaderByteCode, _vertices, _indices, VertexPositionNormalTextureSkin.InputElements, VertexPositionNormalTextureSkin.ElementSize, boundingBox);
RiggedModel riggedModel = new RiggedModel(context);
riggedModel.Mesh = mesh;
riggedModel.SkinOffsets.AddRange(skinOffsets);
riggedModel.FrameTree = rootBoneFrame;
riggedModel.AnimationRig.AddRange(animationControllers);
result = riggedModel;
}
else if ((channels & XFileChannels.Animation) != 0)
{
mesh = BuildMeshForChannels(channels, context.GraphicsDevice, shaderByteCode, xMesh.Vertices, _indices, texCoords, normals, colors, boundingBox, options.HasFlag(XFileImportOptions.EnableInstancing));
ComplexModel complexModel = new ComplexModel(context);
complexModel.Meshes.Add(mesh);
complexModel.FrameTree = rootBoneFrame;
complexModel.AnimationRig.AddRange(animationControllers);
result = complexModel;
}
else
{
mesh = BuildMeshForChannels(channels, context.GraphicsDevice, shaderByteCode, xMesh.Vertices, _indices, texCoords, normals, colors, boundingBox, options.HasFlag(XFileImportOptions.EnableInstancing));
BasicModel basicModel = new BasicModel(context);
basicModel.Mesh = mesh;
result = basicModel;
}
return result;
}
private static List<KeyframeAnimationController> BuildAnimationRig(XFileAnimationSetObject xAnimationSet, List<Frame> targetFrames)
{
List<KeyframeAnimationController> animationControllers = new List<KeyframeAnimationController>();
for (int i = 0; i < xAnimationSet.Animations.Count; i++)
{
XFileAnimationObject xAnimation = xAnimationSet.Animations[i];
Frame animationTarget = targetFrames.Find(f => f.Name == xAnimation.FrameRef);
if (animationTarget != null)
{
Dictionary<long, Matrix> matrixTransformKeys = new Dictionary<long, Matrix>();
for (int j = 0; j < xAnimation.Keys.Count; j++)
{
XFileAnimationKeyObject xAnimationKey = xAnimation.Keys[j];
switch (xAnimationKey.KeyType)
{
case KeyType.Matrix:
for (int k = 0; k < xAnimationKey.NKeys; k++)
{
matrixTransformKeys.Add(xAnimationKey.TimedFloatKeys[k].Time,
new Matrix(xAnimationKey.TimedFloatKeys[k].Values));
}
break;
}
}
TransformAnimation modelAnimation = new TransformAnimation();
foreach (long time in matrixTransformKeys.Keys)
modelAnimation.SetKeyFrame(new AnimationKeyFrame((ulong)time, new CoreTransform(matrixTransformKeys[time])));
animationControllers.Add(new KeyframeAnimationController(modelAnimation, animationTarget));
}
}
return animationControllers;
}
private static Mesh BuildMeshForChannels(XFileChannels channels, Device device, byte[] shaderByteCode, XFileVector[] vertices, short[] indices, Vector2[] texCoords, Vector3[] normals, Color[] colors, BoundingBox boundingBox, bool enableInstancing = false)
{
const int DefaultInstanceSize = 1000;
if ((channels & XFileChannels.MeshVertexColors) != 0 ||
(channels & XFileChannels.DefaultMaterialColor) != 0)
{
if ((channels & XFileChannels.MeshNormals) != 0 ||
(channels & XFileChannels.DeclNormals) != 0)
{
if (!enableInstancing)
{
//VERTEXPOSITIONNORMALCOLOR
//-------------------------
VertexPositionNormalColor[] _vertices = vertices.Select((v, i) => new VertexPositionNormalColor()
{
Position = new Vector4(v.X, v.Y, v.Z, 1.0f),
Normal = normals[i],
Color = colors[i].ToVector4()
}).ToArray();
return ContentBuilder.BuildMesh<VertexPositionNormalColor>(device, shaderByteCode, _vertices, indices, VertexPositionNormalColor.InputElements, VertexPositionNormalColor.ElementSize, boundingBox);
}
else
{
//INSTANCEVERTEXPOSITIONNORMALCOLOR
//---------------------------------
InstanceVertexPositionNormalColor[] _vertices = vertices.Select((v, i) => new InstanceVertexPositionNormalColor()
{
Position = new Vector4(v.X, v.Y, v.Z, 1.0f),
Normal = normals[i],
Color = colors[i].ToVector4()
}).ToArray();
return ContentBuilder.BuildDynamicInstancedMesh<InstanceVertexPositionNormalColor, Matrix>(device, shaderByteCode, _vertices, indices, indices.Length, InstanceVertexPositionNormalColor.InputElements, InstanceVertexPositionNormalColor.ElementSize, null, DefaultInstanceSize, InstanceVertexPositionNormalColor.InstanceSize, boundingBox);
}
}
else
{
if (!enableInstancing)
{
//VERTEXPOSITIONCOLOR
//-------------------
VertexPositionColor[] _vertices = vertices.Select((v, i) => new VertexPositionColor()
{
Position = new Vector4(v.X, v.Y, v.Z, 1.0f),
Color = colors[i].ToVector4()
}).ToArray();
return ContentBuilder.BuildMesh<VertexPositionColor>(device, shaderByteCode, _vertices, indices, VertexPositionColor.InputElements, VertexPositionColor.ElementSize, boundingBox);
}
else
{
//INSTANCEVERTEXPOSITIONCOLOR
//---------------------------
InstanceVertexPositionColor[] _vertices = vertices.Select((v, i) => new InstanceVertexPositionColor()
{
Position = new Vector4(v.X, v.Y, v.Z, 1.0f),
Color = colors[i].ToVector4()
}).ToArray();
return ContentBuilder.BuildDynamicInstancedMesh<InstanceVertexPositionColor, Matrix>(device, shaderByteCode, _vertices, indices, indices.Length, InstanceVertexPositionColor.InputElements, InstanceVertexPositionColor.ElementSize, null, DefaultInstanceSize, InstanceVertexPositionColor.InstanceSize, boundingBox);
}
}
}
else if((channels & XFileChannels.DeclTextureCoords1) != 0 ||
(channels & XFileChannels.MeshTextureCoords1) != 0 )
{
if ((channels & XFileChannels.DeclNormals) != 0 ||
(channels & XFileChannels.MeshNormals) != 0)
{
if (!enableInstancing)
{
//VERTEXPOSITIONNORMALTEXTURE
//---------------------------
VertexPositionNormalTexture[] _vertices = vertices.Select((v, i) => new VertexPositionNormalTexture()
{
Position = new Vector4(v.X, v.Y, v.Z, 1.0f),
Normal = normals[i],
TextureCoord = texCoords[i]
}).ToArray();
return ContentBuilder.BuildMesh<VertexPositionNormalTexture>(device, shaderByteCode, _vertices, indices, VertexPositionNormalTexture.InputElements, VertexPositionNormalTexture.ElementSize, boundingBox);
}
else
{
//INSTANCEVERTEXPOSITIONNORMALTEXTURE
//-----------------------------------
InstanceVertexPostionNormalTexture[] _vertices = vertices.Select((v, i) => new InstanceVertexPostionNormalTexture()
{
Position = new Vector4(v.X, v.Y, v.Z, 1.0f),
Normal = normals[i],
TextureCoord = texCoords[i]
}).ToArray();
return ContentBuilder.BuildDynamicInstancedMesh<InstanceVertexPostionNormalTexture, Matrix>(device, shaderByteCode, _vertices, indices, indices.Length, InstanceVertexPostionNormalTexture.InputElements, InstanceVertexPostionNormalTexture.ElementSize, null, DefaultInstanceSize, InstanceVertexPostionNormalTexture.InstanceSize, boundingBox);
}
}
else
{
if (!enableInstancing)
{
//VERTEXPOSITIONTEXTURE
//---------------------
VertexPositionTexture[] _vertices = vertices.Select((v, i) => new VertexPositionTexture()
{
Position = new Vector4(v.X, v.Y, v.Z, 1.0f),
TextureCoord = texCoords[i]
}).ToArray();
return ContentBuilder.BuildMesh<VertexPositionTexture>(device, shaderByteCode, _vertices, indices, VertexPositionTexture.InputElements, VertexPositionTexture.ElementSize, boundingBox);
}
else
{
//INSTANCEVERTEXPOSITIONTEXTURE
//-----------------------------------
InstanceVertexPositionTexture[] _vertices = vertices.Select((v, i) => new InstanceVertexPositionTexture()
{
Position = new Vector4(v.X, v.Y, v.Z, 1.0f),
TextureCoord = texCoords[i]
}).ToArray();
return ContentBuilder.BuildDynamicInstancedMesh<InstanceVertexPositionTexture, Matrix>(device, shaderByteCode, _vertices, indices, indices.Length, InstanceVertexPositionTexture.InputElements, InstanceVertexPositionTexture.ElementSize, null, DefaultInstanceSize, InstanceVertexPositionTexture.InstanceSize, boundingBox);
}
}
}
else
//UNSUPPORTED-VERTEX-FORMAT
//-------------------------
throw new InvalidOperationException("No color nor texture channel was specified.");
}
private static void BuildBoneFrameHierarchy(XFileFrameObject xBoneFrame, Frame boneframe, List<SkinOffset> skinOffsets)
{
foreach (XFileFrameObject xChildBoneFrame in xBoneFrame.ChildFrames)
{
SkinOffset skinOffset = skinOffsets.Find(b => b.Name == xChildBoneFrame.Name);
Frame childBoneFrame = new Frame() { Name = xChildBoneFrame.Name, Transform = new CoreTransform(new Matrix(xChildBoneFrame.FrameTransformMatrix.m)) };
if (skinOffset != null)
skinOffset.BoneReference = childBoneFrame;
boneframe.Children.Add(childBoneFrame);
BuildBoneFrameHierarchy(xChildBoneFrame, childBoneFrame, skinOffsets);
}
}
private static VoiceData LoadVoiceDataFromWav(string filePath)
{
VoiceDataThunk vdt = new VoiceDataThunk();
VoiceData voiceData = new VoiceData();
ContentImporter.UnsafeNativeMethods.LoadVoiceDataFromWav(filePath, ref vdt);
voiceData.Format = vdt.Format;
voiceData.AudioBytes = vdt.AudioBytes;
voiceData.AudioData = new MemoryStream(vdt.MarshalFromAudioData());
vdt.Dispose();
return voiceData;
}
private static class UnsafeNativeMethods
{
[DllImport("NativeToolkit.dll", EntryPoint = "ContentImporter_LoadVoiceDataFromWav")]
public static extern int LoadVoiceDataFromWav([MarshalAs(UnmanagedType.LPWStr)] string fileName, ref VoiceDataThunk voiceData);
[DllImport("NativeToolkit.dll", EntryPoint = "ContentImporter_CreateTextureFromFile")]
public static extern IntPtr CreateTextureFromFile(IntPtr deviceContext, [MarshalAs(UnmanagedType.LPTStr)] string fileName);
[DllImport("NativeToolkit.dll", EntryPoint = "ContentImporter_LoadFBX")]
public static extern IntPtr LoadFBX([MarshalAs(UnmanagedType.LPWStr)] string fileName, ref FBXMeshThunk fbxMesh);
[DllImport("NativeToolkit.dll", EntryPoint = "ContentImporter_LoadStreamingAudio")]
public static extern IntPtr LoadStreamingAudio([MarshalAs(UnmanagedType.LPWStr)] string fileName);
}
}
[Flags]
public enum FBXFileChannels
{
Default = Position | Color,
Position = 0x01,
Normal = 0x02,
Color = 0x04,
Texture0 = 0x08,
Texture1 = 0x10,
PositionColor = Position | Color,
PositionTexture = Position | Texture0,
PositionNormalColor = Position | Normal | Color,
PositionNormalTexture = Position | Normal | Texture0,
PositionMultiTexture = Position | Texture0 | Texture1,
PositionNormalMultiTexture = Position | Normal | Texture0 | Texture1
}
[Flags]
public enum XFileChannels
{
Mesh = 0x0001, //NOTE: Mesh is always an assumed channel.
Skinning = 0x0002,
Frames = 0x0004,
Animation = 0x0008,
MeshTextureCoords1 = 0x0010,
MeshTextureCoords2 = 0x0020,
MeshVertexColors = 0x0040,
DeclTextureCoords1 = 0x0080,
DeclTextureCoords2 = 0x0100,
MeshNormals = 0x0200,
DeclNormals = 0x0400,
DefaultMaterialColor = 0x0800,
DeclColor = 0x1000,
CommonAlinBasic = Mesh,
CommonAlinRigged = Mesh | Skinning | Frames | Animation,
CommonAlinRiggedTexture1 = CommonAlinRigged | DeclTextureCoords1,
CommonAlinRiggedLitTexture1 = CommonAlinRiggedTexture1 | DeclNormals,
CommonAlinRiggedTexture2 = CommonAlinRiggedTexture1 | DeclTextureCoords2,
CommonAlinRiggedLitTexture2 = CommonAlinRiggedTexture2 | DeclNormals,
CommonAlinComplex = Mesh |Frames | Animation,
CommonAlinComplexTexture1 = CommonAlinComplex | DeclTextureCoords1,
CommonAlinComplexTexture2 = CommonAlinComplexTexture1 | DeclTextureCoords2,
CommonLegacyRigged = Skinning | Frames | Animation,
CommonLegacyRiggedTexture1 = CommonLegacyRigged | MeshTextureCoords1,
CommonLegacyRiggedTexture2 = CommonLegacyRiggedTexture1 | MeshTextureCoords2,
CommonLegacyComplex = Mesh | Frames | Animation,
CommonLegacyComplexTexture1 = CommonLegacyComplex | MeshTextureCoords1,
CommonLegacyComplexTexture2 = CommonLegacyComplexTexture1 | MeshTextureCoords2
}
[Flags]
public enum XFileImportOptions
{
None = 0,
IgnoreMissingTexCoords = 0x0001,
IgnoreMissingNormals = 0x0002,
IgnoreMissingColors = 0x0004,
EnableInstancing = 0x0008
}
[StructLayout(LayoutKind.Sequential)]
internal struct FBXMeshThunk : IDisposable
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public float[] m;
public IntPtr Vertices;
public int VertexCount;
public IntPtr Indices;
public int IndexCount;
public IntPtr Children;
public int ChildCount;
public IntPtr AnimationTakes;
public int TakeCount;
public void Dispose()
{
FBXMeshThunk.DisposeMeshTree(ref this);
}
private static void DisposeMeshTree(ref FBXMeshThunk parent)
{
if (parent.Children != IntPtr.Zero)
{
FBXMeshThunk[] children = parent.MarshalChildren();
for (int i = 0; i < children.Length; i++)
FBXMeshThunk.DisposeMeshTree(ref children[i]);
Marshal.FreeHGlobal(parent.Children);
parent.Children = IntPtr.Zero;
}
if (parent.Vertices != IntPtr.Zero)
{
Marshal.FreeHGlobal(parent.Vertices);
parent.Vertices = IntPtr.Zero;
}
if (parent.Indices != IntPtr.Zero)
{
Marshal.FreeHGlobal(parent.Indices);
parent.Indices = IntPtr.Zero;
}
}
public FBXMeshThunk[] MarshalChildren()
{
if (Children == IntPtr.Zero)
return null;
else
{
//FBXMeshThunk[] structures = new FBXMeshThunk[ChildCount];
//int sizeofTypeT = Marshal.SizeOf(typeof(FBXMeshThunk));
//for (int i = 0; i < ChildCount; i++)
//{
// IntPtr cursor = IntPtr.Add(Children, i * sizeofTypeT);
// //structures[i].m = new float[16];
// structures[i] = (FBXMeshThunk)Marshal.PtrToStructure(cursor, typeof(FBXMeshThunk));
//}
//return structures;
return MarshalHelper.PtrToStructures<FBXMeshThunk>(Children, ChildCount);
}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct FBXKeyFrame
{
public XVECTOR4 Transform;
public XVECTOR4 Rotation;
}
public struct VoiceData
{
public WaveFormatEx Format;
public int AudioBytes;
public Stream AudioData;
}
[StructLayout(LayoutKind.Sequential)]
internal struct VoiceDataThunk : IDisposable
{
public WaveFormatEx Format;
public int AudioBytes;
public IntPtr AudioDataPtr;
public byte[] MarshalFromAudioData()
{
if (AudioDataPtr == IntPtr.Zero)
return null;
else
{
byte[] audioData = new byte[AudioBytes];
Marshal.Copy(AudioDataPtr, audioData, 0, audioData.Length);
return audioData;
}
}
public void MarshalToAudioData(byte[] data)
{
if (AudioDataPtr != IntPtr.Zero)
Marshal.FreeHGlobal(AudioDataPtr);
if (data == null)
AudioDataPtr = IntPtr.Zero;
else
{
AudioDataPtr = Marshal.AllocHGlobal(data.Length);
Marshal.Copy(data, 0, AudioDataPtr, data.Length);
}
}
#region IDisposable Members
public void Dispose()
{
this.MarshalToAudioData(null);
}
#endregion
}
}<file_sep>/XViewLib/World/Geometry/ComplexModel.cs
using System.Collections.Generic;
using System.Linq;
using SharpDX;
using OpenJelly.XFileViewer.Core.Animation;
using OpenJelly.XFileViewer.Core.Animation.Controllers;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.World.Geometry
{
/// <summary>
///
/// </summary>
public class ComplexModel : Model, IAnimatedModel
{
private List<Mesh> _meshes = new List<Mesh>();
private List<KeyframeAnimationController> _animationControllers = new List<KeyframeAnimationController>();
public List<Mesh> Meshes { get { return _meshes; } }
public List<MeshTextures> MeshTextures { get; set; }
public override BoundingBox BoundingBox
{
get
{
Vector3 min = Meshes.Min(m => m.BoundingBox.Minimum);
Vector3 max = Meshes.Max(m => m.BoundingBox.Maximum);
return new BoundingBox(min, max);
}
}
#region IAnimatedModel
/// <summary>
///
/// </summary>
public Frame FrameTree { get; set; }
public List<KeyframeAnimationController> AnimationRig { get { return _animationControllers; } }
#endregion
public ComplexModel(IVisualization context)
: base(context)
{ }
public override void Draw(SimTime simTime)
{
List<Frame> frameList = null;
if (FrameTree != null)
frameList = FrameTree.FlattenToList();
if (Effect != null)
{
OnApplyingEffect();
Effect.Apply();
foreach (Mesh mesh in Meshes)
{
//*************************************************************************************************
//NOTES: It is expectected that the World (and Projection) matrix of the Effect has already been
//set before calling this method.
//*************************************************************************************************
//We need to combine the mesh's frame-tree transformation to the current world matrix.
//We cache the world matrix specified before this call and apply the mesh's frame transformation
//be fore drawing. We restore the orginal world matrix after drawing is complete.
Matrix originalWorld = Effect.World;
Frame meshFrame = frameList.First(f => f.Name == mesh.Name);
Effect.World = meshFrame != null ? Effect.World * meshFrame.WorldTransform().ToMatrix() : Effect.World;
mesh.Draw(simTime);
Effect.World = originalWorld;
}
Effect.Restore();
}
}
protected override void OnApplyingEffect()
{
base.OnApplyingEffect();
}
}
}
<file_sep>/XViewLib/ContentManagement/ContentBuilder.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenJelly.XFileViewer.Core.World.Geometry;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Direct3D;
using DXBuffer = SharpDX.Direct3D11.Buffer;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Content
{
public static class ContentBuilder
{
#region Skybox
public static Mesh[] CreateSkyBox(Device device, byte[] shaderByteCode, float distanceFromViewPoint)
{
VertexPositionTexture[] front = new VertexPositionTexture[4];
VertexPositionTexture[] back = new VertexPositionTexture[4];
VertexPositionTexture[] left = new VertexPositionTexture[4];
VertexPositionTexture[] right = new VertexPositionTexture[4];
VertexPositionTexture[] top = new VertexPositionTexture[4];
VertexPositionTexture[] bottom = new VertexPositionTexture[4];
Vector2[] _textureCoords = new Vector2[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1) };
//front quad...
front[0] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[0]);
front[1] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[1]);
front[2] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, -distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[2]);
front[3] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, -distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[3]);
//back quad...
back[0] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, distanceFromViewPoint, distanceFromViewPoint), _textureCoords[0]);
back[1] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, distanceFromViewPoint, distanceFromViewPoint), _textureCoords[1]);
back[2] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, -distanceFromViewPoint, distanceFromViewPoint), _textureCoords[2]);
back[3] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, -distanceFromViewPoint, distanceFromViewPoint), _textureCoords[3]);
//left quad...
left[0] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, distanceFromViewPoint, distanceFromViewPoint), _textureCoords[0]);
left[1] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[1]);
left[2] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, -distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[2]);
left[3] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, -distanceFromViewPoint, distanceFromViewPoint), _textureCoords[3]);
//right quad...
right[0] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[0]);
right[1] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, distanceFromViewPoint, distanceFromViewPoint), _textureCoords[1]);
right[2] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, -distanceFromViewPoint, distanceFromViewPoint), _textureCoords[2]);
right[3] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, -distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[3]);
//top quad...
top[0] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[0]);
top[1] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[1]);
top[2] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, distanceFromViewPoint, distanceFromViewPoint), _textureCoords[2]);
top[3] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, distanceFromViewPoint, distanceFromViewPoint), _textureCoords[3]);
//bottom quad...
bottom[0] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, -distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[0]);
bottom[1] = new VertexPositionTexture(new Vector3(-distanceFromViewPoint, -distanceFromViewPoint, distanceFromViewPoint), _textureCoords[1]);
bottom[2] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, -distanceFromViewPoint, distanceFromViewPoint), _textureCoords[2]);
bottom[3] = new VertexPositionTexture(new Vector3(distanceFromViewPoint, -distanceFromViewPoint, -distanceFromViewPoint), _textureCoords[3]);
BoundingBox boundingBox = new BoundingBox(new Vector3(-distanceFromViewPoint, -distanceFromViewPoint, -distanceFromViewPoint), new Vector3(distanceFromViewPoint, distanceFromViewPoint, distanceFromViewPoint));
short[] indices = new short[] { 0, 1, 2, 0, 2, 3 };
Mesh frontQuad = BuildMesh<VertexPositionTexture>(device, shaderByteCode, front, indices, VertexPositionTexture.InputElements, VertexPositionTexture.ElementSize, boundingBox);
Mesh backQuad = BuildMesh<VertexPositionTexture>(device, shaderByteCode, back, indices, VertexPositionTexture.InputElements, VertexPositionTexture.ElementSize, boundingBox);
Mesh leftQuad = BuildMesh<VertexPositionTexture>(device, shaderByteCode, left, indices, VertexPositionTexture.InputElements, VertexPositionTexture.ElementSize, boundingBox);
Mesh rightQuad = BuildMesh<VertexPositionTexture>(device, shaderByteCode, right, indices, VertexPositionTexture.InputElements, VertexPositionTexture.ElementSize, boundingBox);
Mesh topQuad = BuildMesh<VertexPositionTexture>(device, shaderByteCode, top, indices, VertexPositionTexture.InputElements, VertexPositionTexture.ElementSize, boundingBox);
Mesh bottomQuad = BuildMesh<VertexPositionTexture>(device, shaderByteCode, bottom, indices, VertexPositionTexture.InputElements, VertexPositionTexture.ElementSize, boundingBox);
return new Mesh[] { frontQuad, backQuad, leftQuad, rightQuad, topQuad, bottomQuad };
}
#endregion
#region Mesh
public static Mesh BuildMesh<T>(Device device, byte[] shaderByteCode, T[] verts, InputElement[] inputElements, int vertexSize, BoundingBox boundingBox, PrimitiveTopology topology = PrimitiveTopology.TriangleList) where T : struct
{
return BuildMesh<T>(device, shaderByteCode, verts, null, inputElements, vertexSize, boundingBox, topology);
}
public static Mesh BuildMesh<T>(Device device, byte[] shaderByteCode, T[] verts, short[] indices, InputElement[] inputElements, int vertexSize, BoundingBox boundingBox, PrimitiveTopology topology = PrimitiveTopology.TriangleList) where T : struct
{
MeshDescription meshDesc = new MeshDescription();
if (verts == null)
throw new ArgumentNullException("verts");
//Vertices...
BufferDescription vertexBufferDesc = new BufferDescription();
vertexBufferDesc.BindFlags = BindFlags.VertexBuffer;
vertexBufferDesc.CpuAccessFlags = CpuAccessFlags.None;
vertexBufferDesc.SizeInBytes = verts.Length * vertexSize;
vertexBufferDesc.OptionFlags = ResourceOptionFlags.None;
vertexBufferDesc.StructureByteStride = 0;
DXBuffer vBuffer = DXBuffer.Create<T>(device, verts, vertexBufferDesc);
meshDesc.VertexBuffer = vBuffer;
meshDesc.VertexCount = verts.Length;
meshDesc.VertexLayout = new InputLayout(device, shaderByteCode, inputElements);
meshDesc.VertexStride = vertexSize;
//Optional Indices...
if (indices != null)
{
BufferDescription indexBufferDesc = new BufferDescription();
indexBufferDesc.BindFlags = BindFlags.IndexBuffer;
indexBufferDesc.CpuAccessFlags = CpuAccessFlags.None;
indexBufferDesc.SizeInBytes = indices.Length * sizeof(short);
indexBufferDesc.OptionFlags = ResourceOptionFlags.None;
DXBuffer iBuffer = DXBuffer.Create<short>(device, indices, indexBufferDesc);
meshDesc.IndexCount = indices.Length;
meshDesc.IndexBuffer = iBuffer;
}
meshDesc.Topology = topology; // SharpDX.Direct3D.PrimitiveTopology.TriangleList;
meshDesc.BoundingBox = boundingBox;
return new Mesh(device, meshDesc);
}
public static Mesh BuildDynamicMesh<T>(Device device, byte[] shaderByteCode, T[] verts, int maxVertices, short[] indices, int maxIndices, InputElement[] inputElements, int vertexSize, BoundingBox boundingBox, PrimitiveTopology topology = PrimitiveTopology.TriangleList) where T : struct
{
MeshDescription meshDesc = new MeshDescription();
if (maxVertices <= 0)
throw new ArgumentOutOfRangeException("maxVertices");
if (indices != null && maxIndices <= 0)
throw new ArgumentOutOfRangeException("maxIndices");
//Vertices...
BufferDescription vertexBufferDesc = new BufferDescription();
vertexBufferDesc.BindFlags = BindFlags.VertexBuffer;
vertexBufferDesc.CpuAccessFlags = CpuAccessFlags.Write;
vertexBufferDesc.SizeInBytes = maxVertices * vertexSize;
vertexBufferDesc.OptionFlags = ResourceOptionFlags.None;
vertexBufferDesc.StructureByteStride = 0;
vertexBufferDesc.Usage = ResourceUsage.Dynamic;
DXBuffer vBuffer = (verts != null) ? DXBuffer.Create<T>(device, verts, vertexBufferDesc) : new DXBuffer(device, vertexBufferDesc);
meshDesc.VertexCount = (verts != null) ? verts.Length : 0;
meshDesc.VertexBuffer = vBuffer;
meshDesc.VertexLayout = new InputLayout(device, shaderByteCode, inputElements);
meshDesc.VertexStride = vertexSize;
//Optional Indices...
if (maxIndices != 0)
{
BufferDescription indexBufferDesc = new BufferDescription();
indexBufferDesc.BindFlags = BindFlags.IndexBuffer;
indexBufferDesc.CpuAccessFlags = CpuAccessFlags.Write;
indexBufferDesc.SizeInBytes = maxIndices * sizeof(short);
indexBufferDesc.OptionFlags = ResourceOptionFlags.None;
indexBufferDesc.Usage = ResourceUsage.Dynamic;
DXBuffer iBuffer = (indices != null) ? DXBuffer.Create<short>(device, indices, indexBufferDesc) : new DXBuffer(device, indexBufferDesc);
meshDesc.IndexCount = (indices != null) ? indices.Length : 0;
meshDesc.IndexBuffer = iBuffer;
}
meshDesc.Topology = topology;
meshDesc.BoundingBox = boundingBox;
return new Mesh(device, meshDesc);
}
public static Mesh BuildInstancedMesh<Tv, Ti>(Device device, byte[] shaderByteCode, Tv[] verts, short[] indices,
InputElement[] vertexInputElements, int vertexSize, Ti[] instances,
int instanceSize) where Ti : struct where Tv : struct
{
MeshDescription meshDesc = new MeshDescription();
//Vertices..
BufferDescription vertexBufferDesc = new BufferDescription();
vertexBufferDesc.BindFlags = BindFlags.VertexBuffer;
vertexBufferDesc.CpuAccessFlags = CpuAccessFlags.None;
vertexBufferDesc.SizeInBytes = verts.Length * vertexSize;
vertexBufferDesc.OptionFlags = ResourceOptionFlags.None;
vertexBufferDesc.StructureByteStride = 0;
DXBuffer vBuffer = DXBuffer.Create<Tv>(device, verts, vertexBufferDesc);
meshDesc.VertexBuffer = vBuffer;
meshDesc.VertexCount = verts.Length;
meshDesc.VertexLayout = new InputLayout(device, shaderByteCode, vertexInputElements);
meshDesc.VertexStride = vertexSize;
//Instances...
//NOTE: We always make the instance buffer a dynamic/writable one.
BufferDescription instanceBufferDesc = new BufferDescription();
instanceBufferDesc.BindFlags = BindFlags.VertexBuffer;
instanceBufferDesc.CpuAccessFlags = CpuAccessFlags.None;
instanceBufferDesc.SizeInBytes = instanceSize * instances.Length;
instanceBufferDesc.OptionFlags = ResourceOptionFlags.None;
instanceBufferDesc.StructureByteStride = 0;
DXBuffer nBuffer = DXBuffer.Create<Ti>(device, instances, instanceBufferDesc);
meshDesc.InstanceBuffer = nBuffer;
meshDesc.InstanceCount = instances.Length;
meshDesc.InstanceStride = instanceSize;
//Optional Indices...
if (indices != null)
{
BufferDescription indexBufferDesc = new BufferDescription();
indexBufferDesc.BindFlags = BindFlags.IndexBuffer;
indexBufferDesc.CpuAccessFlags = CpuAccessFlags.None;
indexBufferDesc.SizeInBytes = indices.Length * sizeof(short);
indexBufferDesc.OptionFlags = ResourceOptionFlags.None;
DXBuffer iBuffer = DXBuffer.Create<short>(device, indices, indexBufferDesc);
meshDesc.IndexCount = indices.Length;
meshDesc.IndexBuffer = iBuffer;
}
meshDesc.Topology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
return new Mesh(device, meshDesc);
}
public static Mesh BuildDynamicInstancedMesh<Tv, Ti>(Device device, byte[] shaderByteCode, Tv[] verts, short[] indices,
int maxIndices, InputElement[] vertexInputElements, int vertexSize, Ti[] instances, int maxInstances,
int instanceSize, BoundingBox boundingBox)
where Ti : struct
where Tv : struct
{
MeshDescription meshDesc = new MeshDescription();
if (maxInstances <= 0)
throw new ArgumentOutOfRangeException("maxVertices");
if (indices != null && maxIndices <= 0)
throw new ArgumentOutOfRangeException("maxIndices");
//Vertices...
BufferDescription vertexBufferDesc = new BufferDescription();
vertexBufferDesc.BindFlags = BindFlags.VertexBuffer;
vertexBufferDesc.CpuAccessFlags = CpuAccessFlags.None;
vertexBufferDesc.SizeInBytes = verts.Length * vertexSize;
vertexBufferDesc.OptionFlags = ResourceOptionFlags.None;
vertexBufferDesc.StructureByteStride = 0;
DXBuffer vBuffer = DXBuffer.Create<Tv>(device, verts, vertexBufferDesc);
meshDesc.VertexBuffer = vBuffer;
meshDesc.VertexCount = verts.Length;
meshDesc.VertexLayout = new InputLayout(device, shaderByteCode, vertexInputElements);
meshDesc.VertexStride = vertexSize;
//Instances...
//NOTE: We always make the instance buffer a dynamic/writable one.
BufferDescription instanceBufferDesc = new BufferDescription();
instanceBufferDesc.BindFlags = BindFlags.VertexBuffer;
instanceBufferDesc.CpuAccessFlags = CpuAccessFlags.Write;
instanceBufferDesc.SizeInBytes = instanceSize * maxInstances;
instanceBufferDesc.OptionFlags = ResourceOptionFlags.None;
instanceBufferDesc.Usage = ResourceUsage.Dynamic;
instanceBufferDesc.StructureByteStride = 0;
DXBuffer nBuffer = (instances != null) ? DXBuffer.Create<Ti>(device, instances, instanceBufferDesc) : new DXBuffer(device, instanceBufferDesc);
meshDesc.InstanceCount = (instances != null) ? instances.Length : 0;
meshDesc.InstanceBuffer = nBuffer;
meshDesc.InstanceStride = instanceSize;
//Optional Indices...
if (indices != null)
{
BufferDescription indexBufferDesc = new BufferDescription();
indexBufferDesc.BindFlags = BindFlags.IndexBuffer;
indexBufferDesc.CpuAccessFlags = CpuAccessFlags.Write;
indexBufferDesc.SizeInBytes = maxIndices * sizeof(short);
indexBufferDesc.OptionFlags = ResourceOptionFlags.None;
indexBufferDesc.Usage = ResourceUsage.Dynamic;
DXBuffer iBuffer = /*(indices != null) ?*/ DXBuffer.Create<short>(device, indices, indexBufferDesc) /*: new DXBuffer(device, indexBufferDesc)*/;
meshDesc.IndexCount = /*(indices != null) ?*/ indices.Length /*: 0*/;
meshDesc.IndexBuffer = iBuffer;
}
meshDesc.Topology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
meshDesc.BoundingBox = boundingBox;
return new Mesh(device, meshDesc);
}
#endregion
public static Mesh BuildBasicViewportQuad(Device device, byte[] shaderByteCode)
{
//NOTE: Viewport coords
//Left = -1
//Top = 1
//Right = 1
//Bottom = -1
RectangleF dimension = new RectangleF(-1, 1, 2, -2);
Vector2[] textureCoords = { new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1) };
ScreenVertex[] verts = new ScreenVertex[6];
verts[0] = new ScreenVertex(new Vector2(dimension.Left, dimension.Top), textureCoords[0]);
verts[1] = new ScreenVertex(new Vector2(dimension.Right, dimension.Top), textureCoords[1]);
verts[2] = new ScreenVertex(new Vector2(dimension.Right, dimension.Bottom), textureCoords[2]);
verts[3] = new ScreenVertex(new Vector2(dimension.Right, dimension.Bottom), textureCoords[2]);
verts[4] = new ScreenVertex(new Vector2(dimension.Left, dimension.Bottom), textureCoords[3]);
verts[5] = new ScreenVertex(new Vector2(dimension.Left, dimension.Top), textureCoords[0]);
Vector3[] positions = (from v in verts select new Vector3(v.Position.X, v.Position.Y, 0)).ToArray();
BoundingBox boundingBox = BoundingBox.FromPoints(positions);
return BuildMesh<ScreenVertex>(device, shaderByteCode, verts, ScreenVertex.InputElements, ScreenVertex.ElementSize, boundingBox);
}
public static Vector3[] GenerateNormals(Vector3[] positions, short[] indices)
{
Vector3[] normals = new Vector3[positions.Length];
short[] _indices = (indices != null) ? indices : Enumerable.Range(0, positions.Length).Select((r) => (short)r).ToArray();
if (_indices != null)
{
List<Vector3>[] positionNormals = new List<Vector3>[positions.Length];
for (int i = 0; i < positionNormals.Length; i++)
positionNormals[i] = new List<Vector3>();
for (int i = 0; i < _indices.Length; i += 3)
{
Vector3 v1 = positions[_indices[i + 1]] - positions[_indices[i + 2]];
Vector3 v2 = positions[_indices[i + 1]] - positions[_indices[i]];
v1.Normalize();
v2.Normalize();
Vector3 n = Vector3.Cross(v1, v2);
for (int j = 0; j < 3; j++)
if (!positionNormals[_indices[i + j]].Contains(n))
positionNormals[_indices[i + j]].Add(n);
}
for (int i = 0; i < positionNormals.Length; i++)
{
Vector3 v = Vector3.Zero;
for (int j = 0; j < positionNormals[i].Count; j++)
v += positionNormals[i][j];
normals[i] = v / positionNormals[i].Count;
normals[i].Normalize();
}
return normals;
}
else
throw new NotSupportedException();
}
}
}
<file_sep>/XViewLib/World/Camera.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.Utils;
using OpenJelly.XFileViewer.Core.Animation;
using OpenJelly.XFileViewer.Core.Effects;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.World
{
public class Camera
{
private PostEffectChain _postEffectChain = null;
private IVisualization _context = null;
public Camera(IVisualization context)
{
_context = context;
//_postEffectChain = PostEffectChain.Create(context);
ViewMatrix = Matrix.Identity;
ProjectionMatrix = Matrix.Identity;
}
public Camera(IVisualization context, Matrix viewMatrix, Matrix projectionMatrix)
{
_context = context;
_postEffectChain = PostEffectChain.Create(context);
ViewMatrix = viewMatrix;
ProjectionMatrix = projectionMatrix;
}
public IVisualization context { get { return _context; } }
public Matrix ViewMatrix { get; set; }
public Vector3 Location
{
get
{
return Camera.ViewMatrixToTransform(this.ViewMatrix).Translation;
}
}
public Matrix ProjectionMatrix { get; set; }
public PostEffectChain PostEffectChain { get { return _postEffectChain; } }
public static Transform ViewMatrixToTransform(Matrix viewMatrix)
{
Matrix viewRotation = viewMatrix * Matrix.Translation(-viewMatrix.TranslationVector);
Vector3 viewTranslation = (viewMatrix * Matrix.Invert(viewRotation)).TranslationVector;
Quaternion q = Quaternion.RotationMatrix(viewRotation);
Quaternion cameraRotation = new Quaternion(q.X, q.Y, q.Z, -q.W);
Vector3 cameraTranslation = -viewTranslation;
return new Transform(cameraRotation, cameraTranslation);
}
public static Matrix TransformToViewMatrix(Transform transform)
{
Quaternion q = new Quaternion(transform.Rotation.X, transform.Rotation.Y, transform.Rotation.Z, -transform.Rotation.W);
Matrix viewRotation = Matrix.RotationQuaternion(q);
Matrix viewTranslation = Matrix.Translation(-transform.Translation);
return viewTranslation * viewRotation;
}
}
}
<file_sep>/XViewLib/Utils/Interop/ContentImporter.cs
using System;
using System.Linq;
using System.Xml.Linq;
using System.Runtime.InteropServices;
using System.IO;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Direct3D;
using SharpDX.Multimedia;
using System.Xml.XPath;
using DXBuffer = SharpDX.Direct3D11.Buffer;
using System.Text.RegularExpressions;
using CipherPark.AngelJacket.Core.World.Geometry;
namespace CipherPark.AngelJacket.Core.Utils.Interop
{
public static class ContentImporter
{
private const string vertexPositionColorPattern = @"\G\s*(?<x>[0-9]+(?:\.[0-9]+)?)\s+(?<y>[0-9]+(?:\.[0-9]+)?)\s+(?<z>[0-9]+(?:\.[0-9]+)?)\s+(?<c>[0-9]+)\s*(?:,|$)";
private const string indexPattern = @"\G\s*(?<i>[0-9]+)(?:\s+|$)";
public static Model LoadModel(ISharpDXContext context, string filePath)
{
XDocument xmlDoc = XDocument.Load(filePath);
var meshInfo = (from element in xmlDoc.Descendants("mesh")
select new
{
IndexCount = element.Attribute("IndexCount") != null ? Convert.ToInt32(element.Attribute("IndexCount").Value) : 0,
VertexCount = Convert.ToInt32(element.Attribute("VertexCount").Value)
}).First();
int vertexElementSize = VertexPositionColor.ElementSize;
InputElement[] vertexInputElements = VertexPositionColor.InputElements; ;
VertexPositionColor[] vertexData = (from Match m in Regex.Matches(xmlDoc.XPathSelectElement("model/mesh/vertices").Value, vertexPositionColorPattern)
select new VertexPositionColor()
{
Position = new Vector4(Convert.ToSingle(m.Groups["x"].Value),
Convert.ToSingle(m.Groups["y"].Value),
Convert.ToSingle(m.Groups["z"].Value),
1.0f),
Color = new Color(Convert.ToInt32(m.Groups["c"].Value)).ToVector4()
}).ToArray();
BasicEffect effect = new BasicEffect(context.GraphicsDevice);
effect.SetWorld(Matrix.Identity);
effect.SetVertexColorEnabled(true);
byte[] shaderCode = effect.SelectShaderByteCode();
MeshDescription meshDesc = new MeshDescription();
BufferDescription vertexBufferDesc = new BufferDescription();
vertexBufferDesc.BindFlags = BindFlags.VertexBuffer;
vertexBufferDesc.CpuAccessFlags = CpuAccessFlags.None;
vertexBufferDesc.SizeInBytes = meshInfo.VertexCount * vertexElementSize;
vertexBufferDesc.OptionFlags = ResourceOptionFlags.None;
vertexBufferDesc.StructureByteStride = 0;
meshDesc.VertexBuffer = DXBuffer.Create<VertexPositionColor>(context.GraphicsDevice, vertexData, vertexBufferDesc);
if(meshInfo.IndexCount > 0)
{
short[] indexData = (from Match m in Regex.Matches(xmlDoc.XPathSelectElement("model/mesh/indices").Value, indexPattern)
select Convert.ToInt16(m.Groups[0].Value)).ToArray();
BufferDescription indexBufferDesc = new BufferDescription();
indexBufferDesc.BindFlags = BindFlags.IndexBuffer;
indexBufferDesc.CpuAccessFlags = CpuAccessFlags.None;
indexBufferDesc.SizeInBytes = meshInfo.IndexCount * sizeof(short);
indexBufferDesc.OptionFlags = ResourceOptionFlags.None;
indexBufferDesc.StructureByteStride = 0;
meshDesc.IndexBuffer = DXBuffer.Create<short>(context.GraphicsDevice, indexData, indexBufferDesc);
}
meshDesc.VertexCount = meshInfo.VertexCount;
meshDesc.VertexLayout = new InputLayout(context.GraphicsDevice, shaderCode, vertexInputElements);
meshDesc.VertexStride = vertexElementSize;
meshDesc.Topology = PrimitiveTopology.TriangleList;
Mesh mesh = new Mesh(context.GraphicsDevice, meshDesc);
Model model = new Model(context);
model.Mesh = mesh;
model.Effect = effect;
return model;
}
public static SpriteFont LoadFont(Device graphicsDevice, string resource)
{
//ShaderResourceView fontShaderResourceView = new ShaderResourceView(game.GraphicsDevice, resource);
SpriteFont font = new SpriteFont(graphicsDevice, resource);
return font;
}
public static Texture2D LoadTexture(DeviceContext deviceContext, string fileName)
{
IntPtr _nativeShaderResourceView = UnsafeNativeMethods.CreateTextureFromFile(deviceContext.NativePointer, fileName);
return new Texture2D(_nativeShaderResourceView);
}
private static class UnsafeNativeMethods
{
[DllImport("AngelJacketNative.dll", EntryPoint = "ContentImporter_LoadVoiceDataFromWav")]
public static extern int LoadVoiceDataFromWav([MarshalAs(UnmanagedType.LPWStr)] string fileName, ref VoiceDataThunk voiceData);
[DllImport("AngelJacketNative.dll", EntryPoint = "ContentImporter_CreateTextureFromFile")]
public static extern IntPtr CreateTextureFromFile(IntPtr deviceContext, [MarshalAs(UnmanagedType.LPTStr)] string fileName);
}
}
public struct VoiceData
{
public WaveFormatEx Format;
public int AudioBytes;
public Stream AudioData;
}
[StructLayout(LayoutKind.Sequential)]
internal struct VoiceDataThunk : IDisposable
{
public WaveFormatEx Format;
public int AudioBytes;
public IntPtr AudioDataPtr;
public byte[] MarshalFromAudioData()
{
if (AudioDataPtr == IntPtr.Zero)
return null;
else
{
byte[] audioData = new byte[AudioBytes];
Marshal.Copy(AudioDataPtr, audioData, 0, audioData.Length);
return audioData;
}
}
public void MarshalToAudioData(byte[] data)
{
if (AudioDataPtr != IntPtr.Zero)
Marshal.FreeHGlobal(AudioDataPtr);
if (data == null)
AudioDataPtr = IntPtr.Zero;
else
{
AudioDataPtr = Marshal.AllocHGlobal(data.Length);
Marshal.Copy(data, 0, AudioDataPtr, data.Length);
}
}
#region IDisposable Members
public void Dispose()
{
this.MarshalToAudioData(null);
}
#endregion
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct WaveFormatEx
{
public UInt16 FormatTag;
public UInt16 Channels;
public UInt32 SamplesPerSec;
public UInt32 AvgBytesPerSec;
public UInt16 BlockAlign;
public UInt16 BitsPerSample;
public UInt16 PaddingSize;
}
}<file_sep>/XViewLib/Effects/Common/Light.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.Utils;
using OpenJelly.XFileViewer.Core.Animation;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Effects
{
public class Light
{
public Color Diffuse { get; set; }
}
public class PointLight : Light, ITransformable
{
public Transform Transform { get; set; }
public ITransformable TransformableParent { get; set; }
}
public class DirectionalLight : Light
{
public Vector3 Direction { get; set; }
}
}
<file_sep>/XViewLib/Utils/MatrixStack.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Utils
{
public class MatrixStack
{
private List<Matrix> _innerList = new List<Matrix>();
public Matrix Transform
{
get
{
Matrix t = Matrix.Identity;
foreach (Matrix m in _innerList)
t *= m;
return t;
}
}
public Matrix ReverseTransform
{
get
{
Matrix t = Matrix.Identity;
for (int i = _innerList.Count - 1; i >= 0; i--)
t *= _innerList[i];
return t;
}
}
public void Push(Matrix m)
{
_innerList.Add(m);
}
public Matrix Pop()
{
if (_innerList.Count == 0)
throw new InvalidOperationException("Matrix stack is empty.");
int lastIndex = _innerList.Count - 1;
Matrix m = _innerList[lastIndex];
_innerList.RemoveAt(lastIndex);
return m;
}
public Matrix Top
{
get
{
if (_innerList.Count == 0)
return Matrix.Identity;
else
return _innerList.Last();
}
}
}
}
<file_sep>/XViewLib/Effects/PassThruPostEffect.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.Utils;
using OpenJelly.XFileViewer.Core.Content;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Effects
{
public class PassThruPostEffect : PostEffect
{
private Mesh _quad = null;
private byte[] _vertexShaderByteCode = null;
private SamplerState _samplerState = null;
private VertexShader _vertexShaderNoFix = null;
private PixelShader _pixelShader = null;
private VertexShader _vertexShaderWithFix = null;
public bool EnableTexelFix { get; set; }
public BlendState BlendState { get; set; }
public PassThruPostEffect(IVisualization context)
: base(context)
{
string psFileName = "Resources\\Shaders\\postpassthru-ps.cso";
string vsFileName = "Resources\\Shaders\\postpassthru-vs.cso";
string vsFixFileName = "Resources\\Shaders\\postpassthru-fix-vs.cso";
//Load Shaders
//------------
_vertexShaderByteCode = System.IO.File.ReadAllBytes(vsFileName);
_samplerState = new SamplerState(context.GraphicsDevice, SamplerStateDescription.Default());
_vertexShaderNoFix = new VertexShader(context.GraphicsDevice, _vertexShaderByteCode);
_pixelShader = new PixelShader(context.GraphicsDevice, System.IO.File.ReadAllBytes(psFileName));
_vertexShaderWithFix = new VertexShader(context.GraphicsDevice, System.IO.File.ReadAllBytes(vsFixFileName));
//Create Scree Quad
//------------------
_quad = ContentBuilder.BuildBasicViewportQuad(context.GraphicsDevice, _vertexShaderByteCode);
}
public override void Apply()
{
BlendState oldBlendState = null;
//Setup Shaders
//-------------
if (!EnableTexelFix)
Context.GraphicsDevice.ImmediateContext.VertexShader.Set(_vertexShaderNoFix);
else
Context.GraphicsDevice.ImmediateContext.VertexShader.Set(_vertexShaderWithFix);
Context.GraphicsDevice.ImmediateContext.PixelShader.Set(_pixelShader);
Context.GraphicsDevice.ImmediateContext.PixelShader.SetShaderResource(0, InputTexture);
Context.GraphicsDevice.ImmediateContext.PixelShader.SetSampler(0, _samplerState);
//Setup states
//------------
if (BlendState != null)
{
oldBlendState = Context.GraphicsDevice.ImmediateContext.OutputMerger.BlendState;
Context.GraphicsDevice.ImmediateContext.OutputMerger.BlendState = BlendState;
}
//Render Screen quad
//------------------
_quad.Draw(null);
//Clean Up Shader
//---------------
Context.GraphicsDevice.ImmediateContext.PixelShader.SetShaderResource(0, null);
Context.GraphicsDevice.ImmediateContext.PixelShader.SetSampler(0, null);
//Clean Up State
//--------------
if (BlendState != null)
Context.GraphicsDevice.ImmediateContext.OutputMerger.BlendState = oldBlendState;
}
}
//public static class CommonBlendStates
//{
// public static BlendState Create(Device context.GraphicsDevice, BlendStatePresets preset)
// {
// BlendStateDescription desc = BlendStateDescription.Default();
// switch (preset)
// {
// case BlendStatePresets.Premultiplied:
// desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
// desc.RenderTarget[0].BlendOperation = BlendOperation.Add;
// desc.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
// desc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
// desc.RenderTarget[0].DestinationBlend = BlendOption.DestinationColor;
// desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha;
// break;
// case BlendStatePresets.NonPremultiplied:
// desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
// desc.RenderTarget[0].BlendOperation = BlendOperation.Add;
// desc.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
// desc.RenderTarget[0].SourceAlphaBlend = BlendOption.SourceAlpha;
// desc.RenderTarget[0].DestinationBlend = BlendOption.DestinationColor;
// desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha;
// break;
// case BlendStatePresets.Additive:
// desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
// desc.RenderTarget[0].BlendOperation = BlendOperation.Add;
// desc.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
// desc.RenderTarget[0].SourceAlphaBlend = BlendOption.SourceAlpha;
// desc.RenderTarget[0].DestinationBlend = BlendOption.DestinationColor;
// desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.One;
// break;
// case BlendStatePresets.Multiplicative:
// desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
// desc.RenderTarget[0].BlendOperation = BlendOperation.Add;
// desc.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
// desc.RenderTarget[0].SourceAlphaBlend = BlendOption.Zero;
// desc.RenderTarget[0].DestinationBlend = BlendOption.DestinationColor;
// desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.SourceColor;
// break;
// }
// return new BlendState(graphicsDevice, desc);
// }
//}
//public enum BlendStatePresets
//{
// Premultiplied,
// NonPremultiplied,
// Additive,
// Multiplicative
//}
}
<file_sep>/XViewLib/Effects/BlinnPhongEffect.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.Utils;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Effects
{
public class BlinnPhongEffect : SurfaceEffect
{
private SharpDX.Direct3D11.Buffer _vertexConstantsBuffer = null;
private SharpDX.Direct3D11.Buffer _pixelConstantsBuffer = null;
private int VertexConstantBufferSize = 272;
private int PixelConstantBufferSize = 64;
private PixelShader _pixelShader = null;
private VertexShader _vertexShader = null;
private byte[] _vertexShaderByteCode = null;
public Matrix WorldInverseTranspose
{
get
{ //return Matrix.Invert(Matrix.Transpose(this.World)); }
return Matrix.Transpose(Matrix.Invert(this.World));
}
}
public Matrix ViewInverse
{
get { return Matrix.Invert(this.View); }
}
public Matrix WorldViewProjection
{
get { return World * View * Projection; }
}
public Vector3 LampDirPos { get; set; }
public Color LampColor { get; set; }
public Color AmbientColor { get; set; }
public float SpecularPower { get; set; }
public float Eccentricity { get; set; }
public BlinnPhongEffect(IVisualization context)
: base(context)
{
_vertexShaderByteCode = LoadVertexShader("Content\\Shaders\\blinnphong-vs.cso", out _vertexShader);
LoadPixelShader("Content\\Shaders\\blinnphong-ps.cso", out _pixelShader);
_vertexConstantsBuffer = new SharpDX.Direct3D11.Buffer(context.GraphicsDevice, VertexConstantBufferSize, ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
_pixelConstantsBuffer = new SharpDX.Direct3D11.Buffer(context.GraphicsDevice, PixelConstantBufferSize, ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
}
public override void Apply()
{
WriteVertexConstants();
WritePixelConstants();
Context.GraphicsDevice.ImmediateContext.VertexShader.Set(_vertexShader);
Context.GraphicsDevice.ImmediateContext.PixelShader.Set(_pixelShader);
Context.GraphicsDevice.ImmediateContext.VertexShader.SetConstantBuffer(0, _vertexConstantsBuffer);
Context.GraphicsDevice.ImmediateContext.PixelShader.SetConstantBuffer(0, _pixelConstantsBuffer);
}
public override byte[] SelectShaderByteCode()
{
return _vertexShaderByteCode;
}
private void WriteVertexConstants()
{
DataBox dataBox = Context.GraphicsDevice.ImmediateContext.MapSubresource(_vertexConstantsBuffer, 0, MapMode.WriteDiscard, MapFlags.None);
DataBuffer dataBuffer = new DataBuffer(dataBox.DataPointer, VertexConstantBufferSize);
int offset = 0;
Matrix worldITXf = this.WorldInverseTranspose;
worldITXf.Transpose();
dataBuffer.Set(offset, worldITXf);
offset += sizeof(float) * 16;
Matrix world = this.World;
world.Transpose();
dataBuffer.Set(offset, world);
offset += sizeof(float) * 16;
Matrix viewIXf = this.ViewInverse;
viewIXf.Transpose();
dataBuffer.Set(offset, viewIXf);
offset += sizeof(float) * 16;
Matrix wvpXf = this.WorldViewProjection;
wvpXf.Transpose();
dataBuffer.Set(offset, wvpXf);
offset += sizeof(float) * 16;
dataBuffer.Set(offset, new Vector4(LampDirPos, 1));
Context.GraphicsDevice.ImmediateContext.UnmapSubresource(_vertexConstantsBuffer, 0);
}
private void WritePixelConstants()
{
DataBox dataBox = Context.GraphicsDevice.ImmediateContext.MapSubresource(_pixelConstantsBuffer, 0, MapMode.WriteDiscard, MapFlags.None);
DataBuffer dataBuffer = new DataBuffer(dataBox.DataPointer, PixelConstantBufferSize);
int offset = 0;
dataBuffer.Set(offset, LampColor.ToVector4());
offset += sizeof(float) * 4;
dataBuffer.Set(offset, AmbientColor.ToVector3());
offset += sizeof(float) * 3;
dataBuffer.Set(offset, SpecularPower);
offset += sizeof(float);
dataBuffer.Set(offset, Eccentricity);
Context.GraphicsDevice.ImmediateContext.UnmapSubresource(_pixelConstantsBuffer, 0);
}
}
}
<file_sep>/XFileViewer/SharpDXContext.cs
using System;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Direct3D;
using SharpDX.DXGI;
using SharpDX.Mathematics.Interop;
using DXBuffer = SharpDX.Direct3D11.Buffer;
using DXDevice = SharpDX.Direct3D11.Device;
using DXGIResource = SharpDX.DXGI.Resource;
using DXResource = SharpDX.Direct3D11.Resource;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.World;
using OpenJelly.XFileViewer.Core;
using OpenJelly.XFileViewer.Core.Effects;
using OpenJelly.XFileViewer.Core.Content;
using OpenJelly.XFileViewer.Core.Utils;
using OpenJelly.XFileViewer.Core.Utils.Toolkit;
namespace XFileViewer
{
public class SharpDXContext : ISharpDXContext
{
private DriverType _driverType = DriverType.Null;
private DXDevice _d3dDevice = null;
private RenderTargetView _renderTargetView = null;
private ShaderResourceView _renderTargetShaderResourceView = null;
private int _width = 0;
private int _height = 0;
private WorldSimulator _simulator = null;
private OpenJelly.XFileViewer.Core.World.Camera _mainCamera = null;
private DXBuffer _vertexBuffer = null;
private DXBuffer _indexBuffer = null;
private DXBuffer _constantBuffer = null;
private Matrix _world;
private Matrix _view;
private Matrix _projection;
private VertexShader _vertexShader = null;
private PixelShader _pixelShader = null;
private InputLayout _layout = null;
private Camera _camera = new Camera();
RiggedModel Model { get; set; }
public DeviceContext GraphicsDeviceContext
{
get { return _d3dDevice.ImmediateContext; }
}
public DXDevice GraphicsDevice
{
get { return _d3dDevice; }
}
public RenderTargetView RenderTarget
{
get { return _renderTargetView; }
}
public ShaderResourceView RenderTargetShaderResourceView
{
get { return _renderTargetShaderResourceView; }
}
public DepthStencilView DepthStencil => throw new NotImplementedException();
public void Init2()
{
#if USE_VERSION2_CONTEXT
DriverType[] driverTypes = new[]
{
DriverType.Hardware,
DriverType.Warp,
DriverType.Reference
};
// DX10 or 11 devices are suitable
FeatureLevel[] featureLevels = new[]
{
FeatureLevel.Level_11_0,
FeatureLevel.Level_10_1,
FeatureLevel.Level_10_0,
};
for (int driverTypeIndex = 0; driverTypeIndex < driverTypes.Length; driverTypeIndex++)
{
try
{
_d3dDevice = new DXDevice(driverTypes[driverTypeIndex], DeviceCreationFlags.BgraSupport, featureLevels);
_driverType = driverTypes[driverTypeIndex];
}
catch (Exception ex)
{
throw new InvalidOperationException("Could not create a Direct3D 10 or 11 device", ex);
}
if (_d3dDevice != null)
break;
}
_simulator = new WorldSimulator(this);
LoadTestModel();
#else
Init();
#endif
}
public void LoadTestModel()
{
//Load Isis Model...
//------------------
//Step 1: let's create the model's shader
//---------------------------------------
BlinnPhongEffect2 isisEffect = new BlinnPhongEffect2(new BlinnPhongShader(this, BlinnPhongShaderVertexType.Skin));
isisEffect.LampColorArray[0] = new Color(192.0f / 255, 191.0f / 255, 173.0f / 255, 1.0f);
isisEffect.AmbientColor = Color.Black;
isisEffect.LampDirPosArray[0] = Vector3.UnitY * 150.0f;
isisEffect.SpecularPower = 0.4f;
isisEffect.Eccentricity = 0.3f;
//Step 2: let's load the model's texture.
//---------------------------------------
string modelTexturePath = @"Resources\Textures\Final.png";
ShaderResourceView isisTexture = new ShaderResourceView(this.GraphicsDevice, ContentImporter.LoadTexture(this.GraphicsDeviceContext, modelTexturePath));
isisEffect.Texture = isisTexture;
//Step 3: load the model (mesh + animation data) from .X file.
//------------------------------------------------------------
string modelPath = @"Resources\Models\isis_x2.X";
RiggedModel isisModel = (RiggedModel)ContentImporter.ImportX(this, modelPath, isisEffect.SelectShaderByteCode(), XFileChannels.CommonAlinRiggedLitTexture1);
isisModel.Effect = isisEffect;
Model = isisModel;
//Setp 4: Add the model's animation to the simulator.
//---------------------------------------------------
_simulator.AnimationControllers.AddRange(isisModel.AnimationRig);
}
public void Init()
{
DriverType[] driverTypes = new[]
{
DriverType.Hardware,
DriverType.Warp,
DriverType.Reference
};
// DX10 or 11 devices are suitable
FeatureLevel[] featureLevels = new[]
{
FeatureLevel.Level_11_0,
FeatureLevel.Level_10_1,
FeatureLevel.Level_10_0,
};
for (int driverTypeIndex = 0; driverTypeIndex < driverTypes.Length; driverTypeIndex++)
{
try
{
_d3dDevice = new DXDevice(driverTypes[driverTypeIndex], DeviceCreationFlags.BgraSupport, featureLevels);
_driverType = driverTypes[driverTypeIndex];
}
catch (Exception ex)
{
throw new InvalidOperationException("Could not create a Direct3D 10 or 11 device", ex);
}
if (_d3dDevice != null)
break;
}
try
{
LoadShaders();
}
catch (Exception ex)
{
throw new InvalidOperationException("Could not load shaders", ex);
}
SimpleVertex[] vertices = new[]
{
new SimpleVertex { Position = new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), Color = new Vector4(0.0f, 0.0f, 1.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(1.0f, 1.0f, -1.0f, 1.0f), Color = new Vector4(0.0f, 1.0f, 0.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(1.0f, 1.0f, 1.0f, 1.0f), Color = new Vector4(0.0f, 1.0f, 1.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), Color = new Vector4(1.0f, 0.0f, 0.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), Color = new Vector4(1.0f, 0.0f, 1.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(1.0f, -1.0f, -1.0f, 1.0f), Color = new Vector4(1.0f, 1.0f, 0.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(1.0f, -1.0f, 1.0f, 1.0f), Color = new Vector4(1.0f, 1.0f, 1.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), Color = new Vector4(0.0f, 0.0f, 0.0f, 0.5f) },
};
BufferDescription bd = new BufferDescription
{
Usage = ResourceUsage.Default,
SizeInBytes = SimpleVertex.SizeInBytes * vertices.Length, //vertices.Length == 8
BindFlags = BindFlags.VertexBuffer,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None,
StructureByteStride = 0,
};
_vertexBuffer = DXBuffer.Create(_d3dDevice, vertices, bd);
// Set vertex buffer
_d3dDevice.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding
{
Buffer = _vertexBuffer,
Stride = SimpleVertex.SizeInBytes,
Offset = 0,
});
// Create index buffer
ushort[] indices = new ushort[]
{
3, 1, 0,
2, 1, 3,
0, 5, 4,
1, 5, 0,
3, 4, 7,
0, 4, 3,
1, 6, 5,
2, 6, 1,
2, 7, 6,
3, 7, 2,
6, 4, 5,
7, 4, 6,
};
bd.Usage = ResourceUsage.Default;
bd.SizeInBytes = sizeof(ushort) * indices.Length; //indices.Length == 36
bd.BindFlags = BindFlags.IndexBuffer;
bd.CpuAccessFlags = 0;
bd.OptionFlags = ResourceOptionFlags.None;
bd.StructureByteStride = 0;
_indexBuffer = DXBuffer.Create(_d3dDevice, indices, bd);
// Set index buffer
_d3dDevice.ImmediateContext.InputAssembler.SetIndexBuffer(_indexBuffer, Format.R16_UInt, 0);
// Set primitive topology
_d3dDevice.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
// Create the constant buffer
bd.Usage = ResourceUsage.Default;
bd.SizeInBytes = Matrix.SizeInBytes * 3; //Size of World, View and Projection matrices.
bd.BindFlags = BindFlags.ConstantBuffer;
bd.CpuAccessFlags = CpuAccessFlags.None;
_constantBuffer = new DXBuffer(_d3dDevice, bd);
_world = Matrix.Identity;
Vector3 eye = new Vector3(0.0f, 1.0f, -5.0f);
Vector3 at = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 up = new Vector3(0.0f, 1.0f, 0.0f);
_view = Matrix.LookAtLH(eye, at, up);
}
public void Cleanup()
{
_d3dDevice?.ImmediateContext?.ClearState();
_indexBuffer?.Dispose();
_indexBuffer = null;
_pixelShader?.Dispose();
_pixelShader = null;
_vertexBuffer.Dispose();
_vertexBuffer = null;
_layout?.Dispose();
_layout = null;
_vertexShader?.Dispose();
_vertexShader = null;
_d3dDevice.Dispose();
_d3dDevice = null;
}
private float t = 0.0f;
private ulong dwTimeStart = 0;
private float[] clearColor = new[] { 0.0f, 0.0f, 0.0f, 1.0f };
OpenJelly.XFileViewer.Core.SimTime simTime = new OpenJelly.XFileViewer.Core.SimTime(true);
public void Render2(IntPtr pResource, bool isNewSurface)
{
#if USE_VERSION2_CONTEXT
simTime.Update();
//if(simTime.IsNextFrameReady)
_simulator.Update(simTime);
// If we've gotten a new Surface, need to initialize the renderTarget.
// One of the times that this happens is on a resize.
if (isNewSurface)
{
_d3dDevice.ImmediateContext.OutputMerger.SetRenderTargets(null, (RenderTargetView)null);
InitRenderTarget(pResource);
_mainCamera = new OpenJelly.XFileViewer.Core.World.Camera(this);
_mainCamera.ViewMatrix = Matrix.LookAtLH(new Vector3(0, 500, -50), Vector3.Zero, Vector3.UnitY);
_mainCamera.ProjectionMatrix = Matrix.PerspectiveFovLH(MathUtil.DegreesToRadians(60), _width / _height, 0.1f, 10000.0f);
}
_d3dDevice.ImmediateContext.ClearRenderTargetView(_renderTargetView, new Color4(clearColor));
if (Model != null)
{
Model.Effect.World = Matrix.Identity;
Model.Effect.View = _mainCamera.ViewMatrix;
Model.Effect.Projection = _mainCamera.ProjectionMatrix;
Model.Draw(simTime);
}
_d3dDevice.ImmediateContext.Flush();
#else
Render(pResource, isNewSurface);
#endif
}
public void Render(IntPtr pResource, bool isNewSurface)
{
// If we've gotten a new Surface, need to initialize the renderTarget.
// One of the times that this happens is on a resize.
if (isNewSurface)
{
_d3dDevice.ImmediateContext.OutputMerger.SetRenderTargets(null, (RenderTargetView)null);
InitRenderTarget(pResource);
}
// Update our time
if (_driverType == DriverType.Reference)
{
t += (float)Math.PI * 0.0125f;
}
else
{
ulong dwTimeCur = (ulong)Environment.TickCount;
if (dwTimeStart == 0)
dwTimeStart = dwTimeCur;
t = (dwTimeCur - dwTimeStart) / 1000.0f;
}
_world = Matrix.RotationX(t) * Matrix.RotationY(t);
_d3dDevice.ImmediateContext.ClearRenderTargetView(_renderTargetView, new Color4(clearColor));
_camera.Update();
//TODO: Update this line of code when camera implementation is complete.
Matrix viewProjection = _projection; //Matrix.Multiply(_camera.View, _projection);
ConstantBufferData cbd = new ConstantBufferData()
{
World = Matrix.Transpose(_world),
View = Matrix.Transpose(_view),
Projection = Matrix.Transpose(viewProjection)
};
_d3dDevice.ImmediateContext.UpdateSubresource(ref cbd, _constantBuffer);
//Renders a triangle.
_d3dDevice.ImmediateContext.VertexShader.Set(_vertexShader);
_d3dDevice.ImmediateContext.VertexShader.SetConstantBuffer(0, _constantBuffer);
_d3dDevice.ImmediateContext.PixelShader.Set(_pixelShader);
_d3dDevice.ImmediateContext.DrawIndexed(36, 0, 0); //36 is the number of triangle indices of the cube (6 sides x 2 trianges per side x 3 vertices per triangle)
_d3dDevice.ImmediateContext.Flush();
}
private void LoadShaders()
{
//*****************************************************************************
// NOTE: For Vertex Shader and Pixel Shader creation, I chose to deviate,
// slightly, from the D3DVisualization.cpp logic.
// Instead of compiling the shaders inline, I chose to pre-compile the shaders.
// Vertex and Pixel shaders are created with the pre-compiled byte code
//*****************************************************************************
string vsFileName = "Resources\\position_color-vs.cso";
byte[] vertexShaderBlob = System.IO.File.ReadAllBytes(vsFileName);
_vertexShader = new VertexShader(_d3dDevice, vertexShaderBlob);
string psFileName = "Resources\\position_color-ps.cso";
byte[] pixelShaderBlob = System.IO.File.ReadAllBytes(psFileName);
_pixelShader = new PixelShader(_d3dDevice, pixelShaderBlob);
// Define the input layout
var inputElements = SimpleVertex.InputElements;
// Create the input layout
_layout = new InputLayout(_d3dDevice, vertexShaderBlob, inputElements);
// Set the input layout
_d3dDevice.ImmediateContext.InputAssembler.InputLayout = _layout;
}
private void InitRenderTarget(IntPtr pResource)
{
DXGIResource resource = ComObject.As<DXGIResource>(pResource);
IntPtr sharedHandle = resource.SharedHandle;
DXResource tempResource11 = _d3dDevice.OpenSharedResource<DXResource>(sharedHandle);
Texture2D outputResource = ComObject.As<Texture2D>(tempResource11.NativePointer);
RenderTargetViewDescription rtDesc = new RenderTargetViewDescription();
rtDesc.Format = Format.B8G8R8A8_UNorm;
rtDesc.Dimension = RenderTargetViewDimension.Texture2D;
rtDesc.Texture2D.MipSlice = 0;
_renderTargetView = new RenderTargetView(_d3dDevice, outputResource, rtDesc);
_renderTargetShaderResourceView = new ShaderResourceView(_d3dDevice, outputResource);
if (outputResource.Description.Width != _height || outputResource.Description.Height != _height)
{
_width = outputResource.Description.Width;
_height = outputResource.Description.Height;
SetupViewport();
}
_d3dDevice.ImmediateContext.OutputMerger.SetRenderTargets(null, _renderTargetView);
}
private void SetupViewport()
{
ViewportF vp;
vp.Width = (float)_width;
vp.Height = (float)_height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.X = 0;
vp.Y = 0;
_d3dDevice.ImmediateContext.Rasterizer.SetViewport(vp);
//Initialize the projection matrix
_projection = Matrix.PerspectiveFovLH(MathEx.XM_PIDIV4, _width / (float)_height, 0.01f, 100.0f);
}
}
public class Camera
{
public void Update()
{
}
}
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct SimpleVertex
{
public Vector4 Position;
public Vector4 Color;
private static InputElement[] _inputElements = null;
private static int _sizeInBytes = 0;
public static InputElement[] InputElements { get { return _inputElements; } }
public static int SizeInBytes { get { return _sizeInBytes; } }
static SimpleVertex()
{
_inputElements = new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
};
_sizeInBytes = 32;
}
}
public static class MathEx
{
public const float XM_2PI = 6.283185307f;
public const float XM_1DIVPI = 0.318309886f;
public const float XM_1DIV2PI = 0.159154943f;
public const float XM_PIDIV2 = 1.570796327f;
public const float XM_PIDIV4 = 0.785398163f;
}
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct ConstantBufferData
{
public RawMatrix World;
public RawMatrix View;
public RawMatrix Projection;
}
}
<file_sep>/XViewLib/Effects/Effect.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.Utils;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Effects
{
public abstract class Effect
{
protected const int SizeOfMatrix = 64;
protected const int SizeOfVector4 = 16;
protected const int SizeOfFloat = 4;
private IVisualization _context = null;
private List<EffectPass> _passes = new List<EffectPass>();
protected Effect(IVisualization context)
{
_context = context;
}
public IVisualization Context { get { return _context; } }
public Device GraphicsDevice { get { return _context.GraphicsDevice; } }
public List<EffectPass> Passes { get { return _passes; } }
public virtual void Apply()
{
OnBeginApply();
for (int i = 0; i < _passes.Count; i++)
_passes[i].Execute();
OnEndApply();
}
protected virtual void OnBeginApply()
{ }
protected virtual void OnEndApply()
{ }
protected byte[] LoadVertexShader(string fileName, out VertexShader shader)
{
byte[] shaderByteCode = System.IO.File.ReadAllBytes(fileName);
shader = new VertexShader(Context.GraphicsDevice, shaderByteCode);
return shaderByteCode;
}
protected byte[] LoadPixelShader(string fileName, out PixelShader shader)
{
byte[] shaderByteCode = System.IO.File.ReadAllBytes(fileName);
shader = new PixelShader(Context.GraphicsDevice, shaderByteCode);
return shaderByteCode;
}
protected byte[] LoadGeometryShader(string fileName, out GeometryShader shader)
{
byte[] shaderByteCode = System.IO.File.ReadAllBytes(fileName);
shader = new GeometryShader(Context.GraphicsDevice, shaderByteCode);
return shaderByteCode;
}
}
public abstract class SurfaceEffect : Effect
{
protected SurfaceEffect(IVisualization context)
: base(context)
{ }
public virtual Matrix World { get; set; }
public virtual Matrix View { get; set; }
public virtual Matrix Projection { get; set; }
public virtual byte[] SelectShaderByteCode()
{
return null;
}
public virtual void Restore()
{
for (int i = 0; i < Passes.Count; i++)
((SurfaceEffectPass)Passes[i]).CleanUp();
}
}
}
<file_sep>/XViewLib/World/Geometry/Model.cs
using System;
using System.Collections.Generic;
using System.Linq;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.Utils;
using OpenJelly.XFileViewer.Core.Effects;
//using CoreEffect = JalenCode.AngelJacket.Core.Effects.SurfaceEffect;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.World.Geometry
{
/// <summary>
///
/// </summary>
public abstract class Model
{
private IVisualization _context = null;
public Model(IVisualization context)
{
_context = context;
}
/// <summary>
///
/// </summary>
public string Name { get; set; }
/// <summary>
///
/// </summary>
public IVisualization Context { get { return _context; } }
/// <summary>
///
/// </summary>
public SurfaceEffect Effect { get; set; }
/// <summary>
///
/// </summary>
public abstract BoundingBox BoundingBox { get; }
/// <summary>
///
/// </summary>
/// <param name="simTime"></param>
public abstract void Draw(SimTime simTime);
/// <summary>
///
/// </summary>
protected virtual void OnApplyingEffect()
{ }
/// <summary>
///
/// </summary>
protected virtual void OnApplyEffect()
{ }
}
public class BasicModel : Model
{
public Mesh Mesh { get; set; }
public override BoundingBox BoundingBox
{
get
{
return (Mesh != null) ? Mesh.BoundingBox : BoundingBoxExtension.Empty;
}
}
public BasicModel(IVisualization context) : base(context)
{
}
public override void Draw(SimTime simTime)
{
if (Effect != null)
{
OnApplyingEffect();
Effect.Apply();
OnApplyEffect();
if (Mesh != null)
Mesh.Draw(simTime);
Effect.Restore();
}
}
protected virtual void OnMeshChanged()
{ }
}
/// <summary>
///
/// </summary>
public class MeshTextures
{
public string MeshName { get; set; }
public Texture2D Texture { get; set; }
public ModelTextureChannel Channel { get; set; }
}
/// <summary>
///
/// </summary>
public enum ModelTextureChannel
{
Diffuse = 0,
Normal,
Alpha
}
public static class ModelExtension
{
public static void UpdateInstanceData(this ComplexModel model, string meshName, IEnumerable<Matrix> data)
{
Mesh mesh = model.Meshes.FirstOrDefault(m => m.Name == meshName);
if (mesh.IsInstanced == false || mesh.IsDynamic == false)
throw new InvalidOperationException("Cannot set instance data to a mesh that is not both dynamic and instanced.");
if (data.Count() > 0)
mesh.UpdateVertexStream<InstanceVertexData>(data.Select(m => new InstanceVertexData() { Matrix = Matrix.Transpose(m) }).ToArray());
}
public static void UpdateInstanceData(this BasicModel model, IEnumerable<Matrix> data)
{
if (model.Mesh.IsInstanced == false || model.Mesh.IsDynamic == false)
throw new InvalidOperationException("Cannot set instance data to a mesh that is not both dynamic and instanced.");
if (data.Count() > 0)
model.Mesh.UpdateVertexStream<InstanceVertexData>(data.Select(m => new InstanceVertexData() { Matrix = Matrix.Transpose(m) }).ToArray());
}
public static void UpdateInstanceData(this RiggedModel model, IEnumerable<Matrix> orientationData, IEnumerable<SkinOffset> skinningData)
{
throw new NotImplementedException();
}
}
}
<file_sep>/XFileViewer/SharpDXVIsualization.cs
using System;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Direct3D;
using SharpDX.DXGI;
using SharpDX.Mathematics.Interop;
using DXBuffer = SharpDX.Direct3D11.Buffer;
using DXDevice = SharpDX.Direct3D11.Device;
using DXGIResource = SharpDX.DXGI.Resource;
using DXResource = SharpDX.Direct3D11.Resource;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.World;
using OpenJelly.XFileViewer.Core;
using OpenJelly.XFileViewer.Core.Effects;
using OpenJelly.XFileViewer.Core.Content;
using OpenJelly.XFileViewer.Core.Utils;
using OpenJelly.XFileViewer.Core.Utils.Toolkit;
namespace XFileViewer
{
public class Visualization : IVisualization
{
private DriverType _driverType = DriverType.Null;
private DXDevice _d3dDevice = null;
private RenderTargetView _renderTargetView = null;
private ShaderResourceView _renderTargetShaderResourceView = null;
private int _width = 0;
private int _height = 0;
private SimTime _simTime = new SimTime(true);
private bool _finalInit = false;
private bool IsInitialized { get; set; }
public DeviceContext GraphicsDeviceContext
{
get { return _d3dDevice.ImmediateContext; }
}
public DXDevice GraphicsDevice
{
get { return _d3dDevice; }
}
public RenderTargetView RenderTarget
{
get { return _renderTargetView; }
}
public ShaderResourceView RenderTargetShaderResourceView
{
get { return _renderTargetShaderResourceView; }
}
protected int Width { get { return _width; } }
protected int Height { get { return _height; } }
protected SimTime SimTime { get { return _simTime; } }
public void Init()
{
DriverType[] driverTypes = new[]
{
DriverType.Hardware,
DriverType.Warp,
DriverType.Reference
};
// DX10 or 11 devices are suitable
FeatureLevel[] featureLevels = new[]
{
FeatureLevel.Level_11_0,
FeatureLevel.Level_10_1,
FeatureLevel.Level_10_0,
};
for (int driverTypeIndex = 0; driverTypeIndex < driverTypes.Length; driverTypeIndex++)
{
try
{
_d3dDevice = new DXDevice(driverTypes[driverTypeIndex], DeviceCreationFlags.BgraSupport, featureLevels);
_driverType = driverTypes[driverTypeIndex];
}
catch (Exception ex)
{
throw new InvalidOperationException("Could not create a Direct3D 10 or 11 device", ex);
}
if (_d3dDevice != null)
break;
}
}
public void Cleanup()
{
OnCleanup();
_d3dDevice?.ImmediateContext?.ClearState();
_d3dDevice.Dispose();
_d3dDevice = null;
}
private float[] clearColor = new[] { 0.0f, 0.0f, 0.0f, 1.0f };
public void Render(IntPtr pResource, bool isNewSurface)
{
// If we've gotten a new Surface, need to initialize the renderTarget.
// One of the times that this happens is on a resize.
if (isNewSurface)
{
_d3dDevice.ImmediateContext.OutputMerger.SetRenderTargets(null, (RenderTargetView)null);
InitRenderTarget(pResource);
}
_d3dDevice.ImmediateContext.ClearRenderTargetView(_renderTargetView, new Color4(clearColor));
_OnUpdate();
OnDraw();
_d3dDevice.ImmediateContext.Flush();
}
private void InitRenderTarget(IntPtr pResource)
{
DXGIResource resource = ComObject.As<DXGIResource>(pResource);
IntPtr sharedHandle = resource.SharedHandle;
DXResource tempResource11 = _d3dDevice.OpenSharedResource<DXResource>(sharedHandle);
Texture2D outputResource = ComObject.As<Texture2D>(tempResource11.NativePointer);
RenderTargetViewDescription rtDesc = new RenderTargetViewDescription();
rtDesc.Format = Format.B8G8R8A8_UNorm;
rtDesc.Dimension = RenderTargetViewDimension.Texture2D;
rtDesc.Texture2D.MipSlice = 0;
_renderTargetView = new RenderTargetView(_d3dDevice, outputResource, rtDesc);
_d3dDevice.ImmediateContext.OutputMerger.SetRenderTargets(null, _renderTargetView);
if (!_finalInit)
{
OnFinalInit();
_finalInit = true;
}
if (outputResource.Description.Width != _height || outputResource.Description.Height != _height)
{
_width = outputResource.Description.Width;
_height = outputResource.Description.Height;
OnSetupViewport();
}
}
private void _OnUpdate()
{
_simTime.Update();
OnUpdate(_simTime);
}
protected virtual void OnDraw() { }
protected virtual void OnUpdate(SimTime simTime) { }
protected virtual void OnSetupViewport() { }
protected virtual void OnFinalInit() { }
protected virtual void OnCleanup() { }
/*
private void SetupViewport()
{
ViewportF vp;
vp.Width = (float)_width;
vp.Height = (float)_height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.X = 0;
vp.Y = 0;
_d3dDevice.ImmediateContext.Rasterizer.SetViewport(vp);
//Initialize the projection matrix
_projection = Matrix.PerspectiveFovLH(MathEx.XM_PIDIV4, _width / (float)_height, 0.01f, 100.0f);
}
*/
}
}
<file_sep>/XViewLib/ISharpDXContext.cs
using System;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core
{
public interface IVisualization
{
DeviceContext GraphicsDeviceContext { get; }
SharpDX.Direct3D11.Device GraphicsDevice { get; }
RenderTargetView RenderTarget { get; }
ShaderResourceView RenderTargetShaderResourceView { get; }
}
}
<file_sep>/XViewLib/Animation/Controllers/CompositeAnimationController.cs
using System.Collections.Generic;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Animation.Controllers
{
/// <summary>
///
/// </summary>
public class CompositeAnimationController : AnimationController
{
List<IAnimationController> _children = new List<IAnimationController>();
public CompositeAnimationController()
{ }
public CompositeAnimationController(IEnumerable<IAnimationController> children)
{
_children.AddRange(children);
}
public override void Reset()
{
_children.ForEach(c => c.Reset());
}
public override void UpdateAnimation(SimTime simTime)
{
//**********************************************************************************
//NOTE: We use an auxilary controller collection to enumerate through, in
//the event that an updated controller alters this Simulator's Animation Controllers
//collection.
//**********************************************************************************
List<IAnimationController> auxAnimationControllers = new List<IAnimationController>(_children);
foreach (IAnimationController controller in auxAnimationControllers)
{
controller.UpdateAnimation(simTime);
if (controller.IsAnimationComplete)
_children.Remove(controller);
}
if (_children.Count == 0 && !IsAnimationComplete)
OnAnimationComplete();
}
public List<IAnimationController> Children { get { return _children; } }
}
}
<file_sep>/XFileViewer/MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Interop;
using Microsoft.Wpf.Interop.DirectX;
namespace XFileViewer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Magnifier Image Settings
private const double MagImageScale = 1.25; // Scale of image to magnified ellipse
private const double MagImageOffset = 0.12; // Offset of magnified ellipse within image
Visualization visualization = new VisualizationTest(VisualizationTest.TestMode.Model);
// Unit conversion
private const float DegreesToRadians = (float)Math.PI / 180;
// State Management
//private bool magnify = true;
TimeSpan lastRender;
bool lastVisible;
// Magnifier Settings (filled by default slider vlaues)
private double magSize;
private double magScale;
private D3D11Image InteropImage = null;
public MainWindow()
{
InteropImage = new Microsoft.Wpf.Interop.DirectX.D3D11Image();
this.InitializeComponent();
this.host.Loaded += new RoutedEventHandler(this.Host_Loaded);
this.host.SizeChanged += new SizeChangedEventHandler(this.Host_SizeChanged);
}
private bool Init()
{
//bool initSucceeded = NativeMethods.InvokeWithDllProtection(() => NativeMethods.Init()) >= 0;
bool initSucceeded = false;
try
{
visualization.Init();
initSucceeded = true;
}
catch (Exception ex)
{
}
if (!initSucceeded)
{
MessageBox.Show("Failed to initialize.", "WPF D3D Interop", MessageBoxButton.OK, MessageBoxImage.Error);
if (Application.Current != null)
{
Application.Current.Shutdown();
}
}
return initSucceeded;
}
private void Cleanup()
{
//NativeMethods.InvokeWithDllProtection(NativeMethods.Cleanup);
visualization.Cleanup();
}
private int Render(IntPtr resourcePointer, bool isNewSurface)
{
//return NativeMethods.InvokeWithDllProtection(() => NativeMethods.Render(resourcePointer, isNewSurface));
visualization.Render(resourcePointer, isNewSurface);
return 0;
}
/*
private static int SetCameraRadius(float radius)
{
return NativeMethods.InvokeWithDllProtection(() => NativeMethods.SetCameraRadius(radius));
}
private static int SetCameraTheta(float theta)
{
return NativeMethods.InvokeWithDllProtection(() => NativeMethods.SetCameraTheta(theta));
}
private static int SetCameraPhi(float phi)
{
return NativeMethods.InvokeWithDllProtection(() => NativeMethods.SetCameraPhi(phi));
}
*/
#region Callbacks
private void Host_Loaded(object sender, RoutedEventArgs e)
{
ImageHost.Source = InteropImage;
Init();
this.InitializeRendering();
CompositionTarget.Rendering += CompositionTarget_Rendering;
}
private void Host_SizeChanged(object sender, SizeChangedEventArgs e)
{
double dpiScale = 1.0; // default value for 96 dpi
// determine DPI
// (as of .NET 4.6.1, this returns the DPI of the primary monitor, if you have several different DPIs)
var hwndTarget = PresentationSource.FromVisual(this).CompositionTarget as HwndTarget;
if (hwndTarget != null)
{
dpiScale = hwndTarget.TransformToDevice.M11;
}
int surfWidth = (int)(host.ActualWidth < 0 ? 0 : Math.Ceiling(host.ActualWidth * dpiScale));
int surfHeight = (int)(host.ActualHeight < 0 ? 0 : Math.Ceiling(host.ActualHeight * dpiScale));
// Notify the D3D11Image of the pixel size desired for the DirectX rendering.
// The D3DRendering component will determine the size of the new surface it is given, at that point.
InteropImage.SetPixelSize(surfWidth, surfHeight);
// Stop rendering if the D3DImage isn't visible - currently just if width or height is 0
// TODO: more optimizations possible (scrolled off screen, etc...)
bool isVisible = (surfWidth != 0 && surfHeight != 0);
if (lastVisible != isVisible)
{
lastVisible = isVisible;
if (lastVisible)
{
CompositionTarget.Rendering += CompositionTarget_Rendering;
}
else
{
CompositionTarget.Rendering -= CompositionTarget_Rendering;
}
}
}
private void Scale_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
this.magScale = e.NewValue;
}
private void Size_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
this.magSize = e.NewValue;
}
private void MagBox_Checked(object sender, RoutedEventArgs e)
{
//this.magnify = true;
host.Cursor = System.Windows.Input.Cursors.None;
}
private void MagBox_Unchecked(object sender, RoutedEventArgs e)
{
//this.magnify = false;
host.Cursor = System.Windows.Input.Cursors.Arrow;
}
#endregion Callbacks
#region Helpers
private void InitializeRendering()
{
InteropImage.WindowOwner = (new System.Windows.Interop.WindowInteropHelper(this)).Handle;
InteropImage.OnRender = this.DoRender;
// Start rendering now!
InteropImage.RequestRender();
}
void CompositionTarget_Rendering(object sender, EventArgs e)
{
RenderingEventArgs args = (RenderingEventArgs)e;
// It's possible for Rendering to call back twice in the same frame
// so only render when we haven't already rendered in this frame.
if (this.lastRender != args.RenderingTime)
{
InteropImage.RequestRender();
this.lastRender = args.RenderingTime;
}
}
private void UninitializeRendering()
{
Cleanup();
CompositionTarget.Rendering -= this.CompositionTarget_Rendering;
}
#endregion Helpers
private void DoRender(IntPtr surface, bool isNewSurface)
{
Render(surface, isNewSurface);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
this.UninitializeRendering();
}
}
}
<file_sep>/XViewLib/World/Geometry/RiggedModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.Animation;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.Utils;
using OpenJelly.XFileViewer.Core.Effects;
using OpenJelly.XFileViewer.Core.Animation.Controllers;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.World.Geometry
{
/// <summary>
///
/// </summary>
public class RiggedModel : BasicModel, IAnimatedModel
{
private SkinOffsets _bones = new SkinOffsets();
private List<KeyframeAnimationController> _animationControllers = new List<KeyframeAnimationController>();
/// <summary>
///
/// </summary>
/// <param name="device"></param>
public RiggedModel(IVisualization context)
: base(context)
{ }
/// <summary>
///
/// </summary>
public SkinOffsets SkinOffsets { get { return _bones; } }
#region IAnimatedModel
/// <summary>
///
/// </summary>
public Frame FrameTree { get; set; }
/// <summary>
///
/// </summary>
public List<KeyframeAnimationController> AnimationRig
{ get { return _animationControllers; } }
#endregion
protected override void OnApplyingEffect()
{
ISkinEffect skinEffect = this.Effect as ISkinEffect;
if (skinEffect != null)
{
if (SkinOffsets != null)
{
Matrix[] finalBoneMatrices = new Matrix[SkinOffsets.Count];
for (int i = 0; i < SkinOffsets.Count; i++ )
{
Frame bone = SkinOffsets[i].BoneReference;
finalBoneMatrices[i] = SkinOffsets[i].Transform.ToMatrix() * bone.WorldTransform().ToMatrix(); // /*REPLACED WITH SHORT CUT TO SAME BEHAVIOR* bone.ParentToWorld(bone.Transform.ToMatrix());
}
skinEffect.BoneTransforms = finalBoneMatrices;
}
}
base.OnApplyingEffect();
}
}
/// <summary>
///
/// </summary>
public class SkinOffset
{
/// <summary>
///
/// </summary>
public string Name { get; set; }
public Transform Transform { get; set; }
public Frame BoneReference { get; set; }
}
public class SkinOffsets : List<SkinOffset>
{
public SkinOffset this[string name]
{
get
{
SkinOffset result = this.Find(b => b.Name == name);
if (result != null)
return result;
throw new IndexOutOfRangeException();
}
}
}
}
<file_sep>/XViewLib/World/Scene/NullSceneNode.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.Animation;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.Utils;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.World.Scene
{
public class NullSceneNode : SceneNode
{
public NullSceneNode(IVisualization context)
: base(context)
{ }
public NullSceneNode(IVisualization context, string name)
: base(context, name)
{ }
}
}
<file_sep>/XViewLib/World/Scene/ModelSceneNode.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.Animation;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.Utils;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.World.Scene
{
public class ModelSceneNode : SceneNode
{
private Transform _transform = Transform.Identity;
public ModelSceneNode(IVisualization context)
: base(context)
{ }
public ModelSceneNode(Model model, string name = null)
: base(model.Context, name)
{
Model = model;
}
public Model Model { get; set; }
public override void Draw(SimTime simTime)
{
if (Model != null)
{
Model.Effect.World = this.WorldTransform().ToMatrix();
Model.Effect.View = Camera.TransformToViewMatrix(Scene.CameraNode.ParentToWorld(Scene.CameraNode.Transform)); //ViewMatrix;
Model.Effect.Projection = Scene.CameraNode.Camera.ProjectionMatrix;
Model.Draw(simTime);
}
base.Draw(simTime);
}
}
}
<file_sep>/XViewLib/Animation/Controllers/KeyframeAnimationController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.World.Geometry;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Animation.Controllers
{
/// <summary>
///
/// </summary>
public class KeyframeAnimationController : AnimationController
{
private long? _animationStartTime = null;
public bool Loop { get; set; }
public KeyframeAnimationController()
: base()
{ }
public KeyframeAnimationController(TransformAnimation animation, ITransformable target)
{
Target = target;
Animation = animation;
}
public override void Reset()
{
_animationStartTime = null;
}
public override void UpdateAnimation(SimTime simTime)
{
if (_animationStartTime == null)
_animationStartTime = simTime.GetTotalSimtime();
ulong elapsedTime = (ulong)(simTime.GetTotalSimtime() - _animationStartTime.Value);
if (Target != null && Animation != null)
{
Target.Transform = Animation.GetValueAtT(elapsedTime);
//check whether we've updated the target with the last key frame.
if (elapsedTime >= Animation.RunningTime && !IsAnimationComplete)
{
//if Loop is specified, we start the animation over by resetting the animationStartTime.
if (Loop)
_animationStartTime = null;
//otherwise, we signal this animation as complete
else
OnAnimationComplete();
}
}
else
throw new InvalidOperationException("Target or Animation was not initialized.");
}
public ITransformable Target { get; set; }
public TransformAnimation Animation { get; set; }
}
}
<file_sep>/XViewLib/Animation/AnimationKeyFrame.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Animation
{
public class AnimationKeyFrame
{
private ulong _time = 0;
public AnimationKeyFrame(ulong time)
{
_time = time;
}
public AnimationKeyFrame(ulong time, object value)
{
_time = time;
Value = value;
}
public ulong Time { get { return _time; } }
public object Value { get; set; }
public AnimationInterpolationPoint[] InterpolationCurve { get; set; }
public Vector2? EaseOutTangent { get; set; }
public Vector2? EaseInTangent { get; set; }
}
public class AnimationKeyFrames : SortedList<ulong, AnimationKeyFrame>
{ }
}
<file_sep>/XViewLib/World/WorldSimulator.cs
using System.Collections.Generic;
using OpenJelly.XFileViewer.Core.Animation;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.World
{
public class WorldSimulator
{
private IVisualization _context = null;
private List<IAnimationController> _animationControllers = new List<IAnimationController>();
public IVisualization Context { get { return _context; } }
public List<IAnimationController> AnimationControllers { get { return _animationControllers; } }
public WorldSimulator(IVisualization context)
{
_context = context;
}
public void Update(SimTime simTime)
{
//I. Update animation controllers
//-------------------------------
//**********************************************************************************
//NOTE: We use an auxilary controller collection to enumerate through, in
//the event that an updated controller alters this Simulator's Animation Controllers
//collection.
//**********************************************************************************
List<IAnimationController> auxAnimationControllers = new List<IAnimationController>(_animationControllers);
foreach (IAnimationController controller in auxAnimationControllers)
{
controller.UpdateAnimation(simTime);
if (controller.IsAnimationComplete)
_animationControllers.Remove(controller);
}
}
}
}
<file_sep>/XViewLib/Animation/AnimationInterpolationPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Animation
{
public class AnimationInterpolationPoint
{
private float _timeOffset = 0;
public AnimationInterpolationPoint(float timeOffset)
{
_timeOffset = timeOffset;
}
public AnimationInterpolationPoint(float timeOffset, object value)
{
_timeOffset = timeOffset;
Value = value;
}
public float TimeOffset { get { return _timeOffset; } }
public object Value { get; set; }
}
}
<file_sep>/XViewLib/Animation/Controllers/AnimationController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using OpenJelly.XFileViewer.Core.World.Geometry;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Animation
{
/// <summary>
///
/// </summary>
public interface IAnimationController
{
void Reset();
void UpdateAnimation(SimTime simTime);
bool IsAnimationComplete { get; }
void SetComplete();
event EventHandler AnimationComplete;
}
/// <summary>
///
/// </summary>
public abstract class AnimationController : IAnimationController
{
private bool _isAnimationComplete = false;
public bool IsAnimationComplete
{
get { return _isAnimationComplete; }
}
public void SetComplete()
{
OnAnimationComplete();
}
public abstract void Reset();
public abstract void UpdateAnimation(SimTime simTime);
public event EventHandler AnimationComplete;
protected virtual void OnAnimationComplete()
{
_isAnimationComplete = true;
EventHandler handler = AnimationComplete;
if (handler != null)
AnimationComplete(this, EventArgs.Empty);
}
}
}<file_sep>/XFileViewer/ModelViewerVisualization.cs
using System;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Direct3D;
using SharpDX.DXGI;
using SharpDX.Mathematics.Interop;
using DXBuffer = SharpDX.Direct3D11.Buffer;
using OpenJelly.XFileViewer.Core.World.Geometry;
using OpenJelly.XFileViewer.Core.World;
using OpenJelly.XFileViewer.Core;
using OpenJelly.XFileViewer.Core.Effects;
using OpenJelly.XFileViewer.Core.Content;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace XFileViewer
{
public class ModelViewerVisualization : Visualization
{
private WorldSimulator _simulator = null;
private OpenJelly.XFileViewer.Core.World.Camera _mainCamera = null;
public Model Model { get; set; }
public WorldSimulator Simulator { get { return _simulator; } }
protected override void OnFinalInit()
{
_simulator = new WorldSimulator(this);
_mainCamera = new OpenJelly.XFileViewer.Core.World.Camera(this);
_mainCamera.ViewMatrix = Matrix.LookAtLH(new Vector3(0, 100, 200), new Vector3(0, 100, 0), Vector3.UnitY);
base.OnFinalInit();
}
protected override void OnDraw()
{
if ( Model != null)
{
Model.Effect.World = Matrix.Identity;
Model.Effect.View = _mainCamera.ViewMatrix;
Model.Effect.Projection = _mainCamera.ProjectionMatrix;
Model.Draw(SimTime);
}
base.OnDraw();
}
protected override void OnCleanup()
{
base.OnCleanup();
}
protected override void OnUpdate(SimTime simTime)
{
_simulator.Update(simTime);
base.OnUpdate(simTime);
}
protected override void OnSetupViewport()
{
ViewportF vp;
vp.Width = (float)Width;
vp.Height = (float)Height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.X = 0;
vp.Y = 0;
this.GraphicsDevice.ImmediateContext.Rasterizer.SetViewport(vp);
//Initialize the projection matrix
_mainCamera.ProjectionMatrix = Matrix.PerspectiveFovLH(0.785398163f, Width / (float)Height, 0.01f, 1000.0f);
base.OnSetupViewport();
}
}
public class VisualizationTest : ModelViewerVisualization
{
private DXBuffer _vertexBuffer = null;
private DXBuffer _indexBuffer = null;
private DXBuffer _constantBuffer = null;
private Matrix _world;
private Matrix _view;
private Matrix _projection;
private VertexShader _vertexShader = null;
private PixelShader _pixelShader = null;
private InputLayout _layout = null;
private Camera _camera = new Camera();
private TestMode Mode { get; set; }
public VisualizationTest(TestMode mode = TestMode.Cube)
{
Mode = mode;
}
protected override void OnFinalInit()
{
if (Mode == TestMode.Cube)
{
try
{
LoadShaders();
}
catch (Exception ex)
{
throw new InvalidOperationException("Could not load shaders", ex);
}
SimpleVertex[] vertices = new[]
{
new SimpleVertex { Position = new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), Color = new Vector4(0.0f, 0.0f, 1.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(1.0f, 1.0f, -1.0f, 1.0f), Color = new Vector4(0.0f, 1.0f, 0.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(1.0f, 1.0f, 1.0f, 1.0f), Color = new Vector4(0.0f, 1.0f, 1.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), Color = new Vector4(1.0f, 0.0f, 0.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), Color = new Vector4(1.0f, 0.0f, 1.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(1.0f, -1.0f, -1.0f, 1.0f), Color = new Vector4(1.0f, 1.0f, 0.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(1.0f, -1.0f, 1.0f, 1.0f), Color = new Vector4(1.0f, 1.0f, 1.0f, 0.5f) },
new SimpleVertex { Position = new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), Color = new Vector4(0.0f, 0.0f, 0.0f, 0.5f) },
};
BufferDescription bd = new BufferDescription
{
Usage = ResourceUsage.Default,
SizeInBytes = SimpleVertex.SizeInBytes * vertices.Length, //vertices.Length == 8
BindFlags = BindFlags.VertexBuffer,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None,
StructureByteStride = 0,
};
_vertexBuffer = DXBuffer.Create(this.GraphicsDevice, vertices, bd);
// Set vertex buffer
this.GraphicsDevice.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding
{
Buffer = _vertexBuffer,
Stride = SimpleVertex.SizeInBytes,
Offset = 0,
});
// Create index buffer
ushort[] indices = new ushort[]
{
3, 1, 0,
2, 1, 3,
0, 5, 4,
1, 5, 0,
3, 4, 7,
0, 4, 3,
1, 6, 5,
2, 6, 1,
2, 7, 6,
3, 7, 2,
6, 4, 5,
7, 4, 6,
};
bd.Usage = ResourceUsage.Default;
bd.SizeInBytes = sizeof(ushort) * indices.Length; //indices.Length == 36
bd.BindFlags = BindFlags.IndexBuffer;
bd.CpuAccessFlags = 0;
bd.OptionFlags = ResourceOptionFlags.None;
bd.StructureByteStride = 0;
_indexBuffer = DXBuffer.Create(this.GraphicsDevice, indices, bd);
// Set index buffer
this.GraphicsDevice.ImmediateContext.InputAssembler.SetIndexBuffer(_indexBuffer, Format.R16_UInt, 0);
// Set primitive topology
this.GraphicsDevice.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
// Create the constant buffer
bd.Usage = ResourceUsage.Default;
bd.SizeInBytes = Matrix.SizeInBytes * 3; //Size of World, View and Projection matrices.
bd.BindFlags = BindFlags.ConstantBuffer;
bd.CpuAccessFlags = CpuAccessFlags.None;
_constantBuffer = new DXBuffer(this.GraphicsDevice, bd);
_world = Matrix.Identity;
Vector3 eye = new Vector3(0.0f, 1.0f, -5.0f);
Vector3 at = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 up = new Vector3(0.0f, 1.0f, 0.0f);
_view = Matrix.LookAtLH(eye, at, up);
}
else
{
base.OnFinalInit();
LoadTestModel();
}
}
public void LoadTestModel()
{
//Load Isis Model...
//------------------
//Step 1: let's create the model's shader
//---------------------------------------
BlinnPhongEffect2 isisEffect = new BlinnPhongEffect2(new BlinnPhongShader(this, BlinnPhongShaderVertexType.Skin));
isisEffect.LampColorArray[0] = new Color(192.0f / 255, 191.0f / 255, 173.0f / 255, 1.0f);
isisEffect.AmbientColor = Color.Black;
isisEffect.LampDirPosArray[0] = Vector3.UnitY * 150.0f;
isisEffect.SpecularPower = 0.4f;
isisEffect.Eccentricity = 0.3f;
//Step 2: let's load the model's texture.
//---------------------------------------
string modelTexturePath = @"Resources\Textures\Final.png";
ShaderResourceView isisTexture = new ShaderResourceView(this.GraphicsDevice, ContentImporter.LoadTexture(this.GraphicsDeviceContext, modelTexturePath));
isisEffect.Texture = isisTexture;
//Step 3: load the model (mesh + animation data) from .X file.
//------------------------------------------------------------
string modelPath = @"Resources\Models\isis_x2.X";
RiggedModel isisModel = (RiggedModel)ContentImporter.ImportX(this, modelPath, isisEffect.SelectShaderByteCode(), XFileChannels.CommonAlinRiggedLitTexture1);
isisModel.Effect = isisEffect;
Model = isisModel;
//Setp 4: Add the model's animation to the simulator.
//---------------------------------------------------
Simulator.AnimationControllers.AddRange(isisModel.AnimationRig);
}
private float t = 0.0f;
private ulong dwTimeStart = 0;
protected override void OnDraw()
{
// If we've gotten a new Surface, need to initialize the renderTarget.
// One of the times that this happens is on a resize.
if (Mode == TestMode.Cube)
{
// Update our time
//if (_driverType == DriverType.Reference)
//{
// t += (float)Math.PI * 0.0125f;
//}
//else
{
ulong dwTimeCur = (ulong)Environment.TickCount;
if (dwTimeStart == 0)
dwTimeStart = dwTimeCur;
t = (dwTimeCur - dwTimeStart) / 1000.0f;
}
_world = Matrix.RotationX(t) * Matrix.RotationY(t);
_camera.Update();
//TODO: Update this line of code when camera implementation is complete.
Matrix viewProjection = _projection; //Matrix.Multiply(_camera.View, _projection);
ConstantBufferData cbd = new ConstantBufferData()
{
World = Matrix.Transpose(_world),
View = Matrix.Transpose(_view),
Projection = Matrix.Transpose(viewProjection)
};
this.GraphicsDevice.ImmediateContext.UpdateSubresource(ref cbd, _constantBuffer);
//Renders a triangle.
this.GraphicsDevice.ImmediateContext.VertexShader.Set(_vertexShader);
this.GraphicsDevice.ImmediateContext.VertexShader.SetConstantBuffer(0, _constantBuffer);
this.GraphicsDevice.ImmediateContext.PixelShader.Set(_pixelShader);
this.GraphicsDevice.ImmediateContext.DrawIndexed(36, 0, 0); //36 is the number of triangle indices of the cube (6 sides x 2 trianges per side x 3 vertices per triangle)
}
else
{
base.OnDraw();
}
}
private void LoadShaders()
{
//*****************************************************************************
// NOTE: For Vertex Shader and Pixel Shader creation, I chose to deviate,
// slightly, from the D3DVisualization.cpp logic.
// Instead of compiling the shaders inline, I chose to pre-compile the shaders.
// Vertex and Pixel shaders are created with the pre-compiled byte code
//*****************************************************************************
string vsFileName = "Resources\\Shaders\\position_color-vs.cso";
byte[] vertexShaderBlob = System.IO.File.ReadAllBytes(vsFileName);
_vertexShader = new VertexShader(this.GraphicsDevice, vertexShaderBlob);
string psFileName = "Resources\\Shaders\\position_color-ps.cso";
byte[] pixelShaderBlob = System.IO.File.ReadAllBytes(psFileName);
_pixelShader = new PixelShader(this.GraphicsDevice, pixelShaderBlob);
// Define the input layout
var inputElements = SimpleVertex.InputElements;
// Create the input layout
_layout = new InputLayout(this.GraphicsDevice, vertexShaderBlob, inputElements);
// Set the input layout
this.GraphicsDevice.ImmediateContext.InputAssembler.InputLayout = _layout;
}
protected override void OnCleanup()
{
_indexBuffer?.Dispose();
_indexBuffer = null;
_pixelShader?.Dispose();
_pixelShader = null;
_vertexBuffer.Dispose();
_vertexBuffer = null;
_layout?.Dispose();
_layout = null;
_vertexShader?.Dispose();
_vertexShader = null;
base.OnCleanup();
}
protected override void OnSetupViewport()
{
if (Mode == TestMode.Cube)
{
ViewportF vp;
vp.Width = (float)Width;
vp.Height = (float)Height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.X = 0;
vp.Y = 0;
this.GraphicsDevice.ImmediateContext.Rasterizer.SetViewport(vp);
//Initialize the projection matrix
_projection = Matrix.PerspectiveFovLH(MathEx.XM_PIDIV4, Width / (float)Height, 0.01f, 100.0f);
}
else
base.OnSetupViewport();
}
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct SimpleVertex
{
public Vector4 Position;
public Vector4 Color;
private static InputElement[] _inputElements = null;
private static int _sizeInBytes = 0;
public static InputElement[] InputElements { get { return _inputElements; } }
public static int SizeInBytes { get { return _sizeInBytes; } }
static SimpleVertex()
{
_inputElements = new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
};
_sizeInBytes = 32;
}
}
public static class MathEx
{
public const float XM_2PI = 6.283185307f;
public const float XM_1DIVPI = 0.318309886f;
public const float XM_1DIV2PI = 0.159154943f;
public const float XM_PIDIV2 = 1.570796327f;
public const float XM_PIDIV4 = 0.785398163f;
}
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct ConstantBufferData
{
public RawMatrix World;
public RawMatrix View;
public RawMatrix Projection;
}
public class Camera
{
public void Update()
{
}
}
public enum TestMode { Cube = 0, Model = 1 };
}
}
<file_sep>/XViewLib/Utils/Range.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
///////////////////////////////////////////////////////////////////////////////
// Developer: <NAME>
// Company: None
// Copyright © 2018
// Purpose: Open Source
// License: MIT
///////////////////////////////////////////////////////////////////////////////
namespace OpenJelly.XFileViewer.Core.Utils
{
public struct RangeF
{
public static RangeF Empty = new RangeF();
public float Min { get; set; }
public float Max { get; set; }
public RangeF(float min, float max) : this()
{
Min = min;
Max = max;
}
}
public struct Range
{
public static Range Empty = new Range();
public int Min { get; set; }
public int Max { get; set; }
public Range(int min, int max)
: this()
{
Min = min;
Max = max;
}
}
}
| fec81ddc51c70cff33b54302721e0de69bb2711d | [
"C#"
] | 27 | C# | jameson75/XFileViewer | 138f1a397879684fa4d4b33319848ddaba6d96eb | eeb4464c699894098155bc5227cc86126b344eed |
refs/heads/master | <repo_name>kiran18dev/App-gituser-search<file_sep>/src/components/HomeTab.js
import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Avatar from '@material-ui/core/Avatar';
import Chip from '@material-ui/core/Chip';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
large: {
width: theme.spacing(20),
height: theme.spacing(20),
},
name: {
padding: '5px 10px',
fontWeight: 'bold'
},
login: {
padding: '10px'
}
}));
const HomeTab = ({ userInfo }) => {
const classes = useStyles();
const [following, setFollowing] = useState(userInfo.following)
const handleFollowingClick = () => {
setFollowing(prev => prev += 10);
};
return (
<div className={classes.root}>
<Card >
<CardContent>
<Avatar alt="git user" src={userInfo.avatar_url} className={classes.large} />
<div className={classes.name}>
{userInfo.name}
</div>
<div className={classes.login}>
{userInfo.login}
</div>
<div>
<Chip
avatar={<Avatar>{userInfo.followers}</Avatar>}
label={`followers `}
variant="outlined"
/>
<Chip
avatar={<Avatar>{following}</Avatar>}
label={`following `}
onClick={handleFollowingClick}
variant="outlined"
/>
</div>
</CardContent>
</Card>
</div>
)
}
export default HomeTab
<file_sep>/src/components/RepoTab.js
import React from 'react';
import { useFetch } from '../hooks/useFetch';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import Divider from '@material-ui/core/Divider';
import FolderIcon from '@material-ui/icons/Folder';
import FolderOpenIcon from '@material-ui/icons/FolderOpen';
const Repo = ({ userInfo }) => {
const { status, data, error } = useFetch(userInfo.repos_url);
console.log(data);
let repos = [];
if (data) {
repos = data.map(item => {
if (item.private) { // Message for private repo
item.message = `User ${userInfo.login} with ${userInfo.followers} followers is following ${userInfo.following}. One repo for this user is ${userInfo.name}/${item.name} and it is private.`;
} else { // Message for public repo
item.message = `User ${userInfo.login} with ${userInfo.followers} followers is following ${userInfo.following}. One repo for this user is ${userInfo.name}/${item.name} and it is not private.`
}
return item;
})
}
return (
<Card style={{ width: '98%', margin: '20px' }}>
<CardContent>
<List component="nav" aria-label="main mailbox folders">
{
repos && repos.map((item, index) => (
<>
<ListItem key={index}>
<ListItemIcon>
{
item.private ? <FolderIcon /> : <FolderOpenIcon />
}
</ListItemIcon>
<ListItemText primary={item.message} />
</ListItem>
<Divider />
</>
))
}
</List>
</CardContent>
</Card>
);
};
export default Repo;<file_sep>/src/components/Home.js
import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import { useStyles } from '../hooks/useStyles';
import { a11yProps } from '../utility';
import { TabPanel } from './TabPanel';
import UserSearch from './UserSearch';
import HomeTab from './HomeTab';
import Repo from './RepoTab';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
export default function Home({ match }) {
console.log('match ==> ', match);
const classes = useStyles();
const [value, setValue] = React.useState(0);
const [userInfo, setUserInfo] = React.useState(null);
const getUserInfo = (userInfo) => {
setUserInfo(userInfo);
}
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<div className="git-app">
<Card style={{ margin: '20px' }}>
<CardContent>
<div>
<UserSearch getUserInfo={getUserInfo} params={match.params} />
</div>
{
userInfo && userInfo.login && (
<div>
<AppBar position="static">
<Tabs value={value} onChange={handleChange} aria-label="simple tabs example">
<Tab label="Home" {...a11yProps(0)} />
<Tab label="Repos" {...a11yProps(2)} />
</Tabs>
</AppBar>
<TabPanel value={value} index={0}>
<HomeTab userInfo={userInfo} />
</TabPanel>
<TabPanel value={value} index={1}>
<Repo userInfo={userInfo} />
</TabPanel>
</div>
)
}
</CardContent>
</Card>
</div>
);
}
| 0bd7f2457d288775a5ee5e5bdd0c0f409619cacb | [
"JavaScript"
] | 3 | JavaScript | kiran18dev/App-gituser-search | 5bbab6f9cfedd3db450298c753a3b8c784b52bb5 | c5e247a56c940da082fd28f33b5058eb69651365 |
refs/heads/main | <file_sep>/*
Programa de Variações de Variáveis
Este firmware exibe mensagens sobre o Serial para entender melhor o uso das variáveis.
Ligue a janela Serial Monitoring e reinicie a placa depois disso.
Observe e verifique o código :)
*/
// declarando variáveis antes de se divertir!
boolean myBoolean;
char myChar;
int myInt;
float myFloat;
String myString;
void setup(){
Serial.begin(9600);
myBoolean = false;
myChar = 'A';
myInt = 1;
myFloat = 5.6789 ;
myString = "Ola humano!!";
}
void loop(){
// verificando o booleano
if (myBoolean) {
Serial.println("myBoolean é verdade");
} else {
Serial.println("myBoolean é falso");
}
// jogando com char e int
Serial.print("myChar está atualmente");
Serial.write(myChar);
Serial.println();
Serial.print("myInt está atualmente ");
Serial.print(myInt);
Serial.println();
Serial.print("Então, aqui está myChar + myInt:");
Serial.write(myChar + myInt);
Serial.println();
// jogando com float e int
Serial.print("myFloat é : ");
Serial.print(myFloat);
Serial.println();
// colocar o conteúdo de myFloat em myInt
myInt = myFloat;
Serial.print("Coloquei meuFloat em meuInt, e aqui está meuInt agora:");
Serial.println(myInt);
// jogando com String
Serial.print("myString é atualmente:");
Serial.println(myString);
myString += myChar; //concatenando String com Char
Serial.print("myString tem um comprimento de");
Serial.print(myString.length());// imprimindo o comprimento de myString
Serial.print(" e é igual agora:");
Serial.println(myString);
// myString fica muito longa, mais de 15, removendo os últimos 3 elementos
if (myString.length() >= 15){
Serial.println("myString muito longa ... vamos, vamos limpar isso!");
myInt = myString.lastIndexOf('!'); // encontrando o lugar do '!'
myString = myString.substring(0,myInt+1); // removendo personagens
Serial.print("myString agora está mais limpo:");
Serial.println(myString);
// colocando true em myBoolean
} else {
myBoolean = false; // redefinindo myBoolean para false
}
delay(5000); // vamos fazer uma pausa
// vamos colocar 2 linhas em branco para ter uma leitura clara
Serial.println();
Serial.println();
}
| b3e5807f6978d5dae29a4c17f4484e99703f426b | [
"C++"
] | 1 | C++ | caneto/Programacao-C-para-Arduino | 446d3557885cab3786aadff37c6e38c83362f289 | 494d83233963a1c7fc3a3fcd1233ca62714bdf1c |
refs/heads/master | <file_sep># minesweeper
move a bot over a surface searching for IR strobes using image processing
This was made for an IP robotics competition in IIEST ,Shibpur,India.
The objective was to make an arduino based bot with ir sensors below,a motor driver,a bluetooth module hc 05
and a buzzer..
The best part...We won the competition....!!!!!!!
The image processing was done with a webcam hanging above the arena filled with 10 green blobs.
our task was to find in which of those green blobs there where ir lights.
the main code was written on matlab.
commands were sent over bluetooth.
See this video...
https://www.youtube.com/watch?v=6IhMgqlB2io
<file_sep>//Mohit's and vivek's and Suprotik's bot has 5,6 & 10,11 motor input l293d ic h-bridge
int leftmotfwd = 5;
int leftmotrvs = 6;
int rightmotfwd = 11;
int rightmotrvs = 10;
char state;
int low = 0;
int high = 255;
int del = 100;
int del_low = 50;
int flag=0;
//sound output declarations
/*to define the notes for speaker sound*/
#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978
/*to define the notes for speaker sound*/
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
//sound output declarations
int thresh = 150;
void setup() {
Serial.begin(9600);
pinMode(leftmotfwd,OUTPUT);
pinMode(leftmotrvs,OUTPUT);
pinMode(rightmotfwd,OUTPUT);
pinMode(rightmotrvs,OUTPUT);
pinMode(13,OUTPUT);
}
void loop() {
digitalWrite(13,LOW);
analogWrite(leftmotfwd,low);
analogWrite(rightmotfwd,low);
analogWrite(leftmotrvs,low);
analogWrite(rightmotrvs,low);
while(Serial.available() == 0);
state = Serial.read();
digitalWrite(13,HIGH);
flag=0;
if((state == 'f')||(state == 'F'))//forward
{analogWrite(leftmotfwd,high);
analogWrite(rightmotfwd,high);
delay(del);
analogWrite(leftmotfwd,low);
analogWrite(rightmotfwd,low);
}
else if((state == 'b')||(state == 'B'))//reverse
{analogWrite(leftmotrvs,high);
analogWrite(rightmotrvs,high);
delay(del);
analogWrite(leftmotrvs,low);
analogWrite(rightmotrvs,low);
}
else if((state == 'l')||(state == 'L'))//turn left
{analogWrite(leftmotrvs,high);
analogWrite(rightmotfwd,high);
delay(del_low);
analogWrite(leftmotrvs,low);
analogWrite(rightmotfwd,low);
}
else if((state == 'r')||(state == 'R'))//turn right
{analogWrite(leftmotfwd,high);
analogWrite(rightmotrvs,high);
delay(del_low);
analogWrite(leftmotfwd,low);
analogWrite(rightmotrvs,low);
}
else if((state == 'm')||(state == 'M'))//checking connection
{delay(0.5);
Serial.print('y');
}
else if((state == 's')||(state == 'S'))//checking connection
{
for (int thisNote = 0; thisNote < 8; thisNote++)
{
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}
for (int thisNote = 0; thisNote < 8; thisNote++)
{
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}
}
else if((state == 'c')||(state == 'C'))//check for ir transmitters
{int presentflag;
presentflag=1;
for(int i;i<=1000;i++)
{
if(flag==1)
break;
// read the input on analog pin 0:
int sensorValue1 = analogRead(A0);
// read the input on analog pin 1:
int sensorValue2 = analogRead(A1);
// read the input on analog pin 2:
int sensorValue3 = analogRead(A2);
//checking
if((sensorValue1>=thresh)||(sensorValue2>=thresh)||(sensorValue3>=thresh))
{
flag=1;
Serial.print('y');
for (int thisNote = 0; thisNote < 8; thisNote++)
{
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}
}
else
{
presentflag=0;
}
}
if(presentflag==0)
Serial.print('n');
}
}
| 70d55b8116ebd5da4c8c5919d0d4b95c477a2549 | [
"Markdown",
"C++"
] | 2 | Markdown | sprtkd/minesweeperRobotics | 66cbb355c7a8ce714c47cdcabd792eda0282f32a | 4903ee1c9af6a923af6dc110c6f18933fb011b88 |
refs/heads/master | <repo_name>rafaelcmorais02/Employee_Register_DOTNET<file_sep>/Classes/ColaboradorRepositorio.cs
using DIO.Registro.Interfaces;
using System;
using System.Collections.Generic;
namespace DIO.Registro
{
public class ColaboradorRepositorio : IRepositorio<Colaborador>
{
private List<Colaborador> listaColaboradores = new List<Colaborador>();
public void Atualiza(int id, Colaborador entidade)
{
listaColaboradores[id] = entidade;
}
public void Exclui(int id)
{
listaColaboradores[id].Excluir();
}
public void Insere(Colaborador entidade)
{
listaColaboradores.Add(entidade);
}
public List<Colaborador> Lista()
{
return listaColaboradores;
}
public int ProximoId()
{
return listaColaboradores.Count;
}
public Colaborador RetornaPorId(int id)
{
return listaColaboradores[id];
}
}
}<file_sep>/Program.cs
using System;
namespace DIO.Registro
{
class Program
{
static ColaboradorRepositorio repositorio = new ColaboradorRepositorio();
static void Main(string[] args)
{
Console.WriteLine("Projeto 01 - Dio Innovation");
string opcaoUsuario = ObterOpcaoUsuario();
while (opcaoUsuario.ToUpper() != "X")
{
switch (opcaoUsuario)
{
case "1":
listaColaboradores();
break;
case "2":
InsereColaboradores();
break;
case "3":
AtualizaColaboradores();
break;
case "4":
ExcluiColaboradores();
break;
case "5":
VisualizaColaboradores();
break;
case "C":
Console.Clear();
break;
default:
throw new ArgumentOutOfRangeException();
}
opcaoUsuario = ObterOpcaoUsuario();
}
}
private static void VisualizaColaboradores()
{
Console.WriteLine("Visualiza Colaboradores:");
Console.WriteLine("Digite o ID do colaborador a ser visualizado:");
int indicaSerie = int.Parse(Console.ReadLine());
var visualisa = repositorio.RetornaPorId(indicaSerie);
Console.WriteLine(visualisa.ToString());
}
private static void ExcluiColaboradores()
{
Console.WriteLine("Exclui Colaborador:");
Console.WriteLine("Digite o ID do colaborador a ser excluído:");
int indicaSerie = int.Parse(Console.ReadLine());
repositorio.Exclui(id: indicaSerie);
}
private static void AtualizaColaboradores()
{
Console.WriteLine("Atualiza Colaboradores:");
Console.WriteLine("Digite o ID do colaborador:");
int indicaColaborador = int.Parse(Console.ReadLine());
Console.WriteLine("Tipo de contratos:");
foreach(int i in Enum.GetValues(typeof(Tipo)))
{
Console.WriteLine("{0} - {1}", i, Enum.GetName(typeof(Tipo),i));
}
Console.WriteLine("Digite o contrato dentro das opções acima:");
int entradaTipo = int.Parse(Console.ReadLine());
Console.WriteLine("Digite o nome do colaborador:");
string entradaNome = Console.ReadLine();
Console.WriteLine("Digite a matrícula do colaborador:");
int entradaMatricula = int.Parse(Console.ReadLine());
Console.WriteLine("Digite o departamento do colaborador:");
string entradaSetor = Console.ReadLine();
Colaborador atualizaColaborador = new Colaborador(id: indicaColaborador,
contrato: (Tipo)entradaTipo,
nome: entradaNome,
setor: entradaSetor,
matricula: entradaMatricula
);
repositorio.Atualiza(id:indicaColaborador, entidade: atualizaColaborador);
}
private static void listaColaboradores()
{
Console.WriteLine("Listar de colaboradores:");
var lista = repositorio.Lista();
if(lista.Count==0)
{
Console.WriteLine("Sem colaboradores cadastrados");
return;
}
foreach (var colaborador in lista)
{
Console.WriteLine("#ID {0}: - {1} - Demitido?: {2}", colaborador.RetornaId(), colaborador.RetornaNome(), colaborador.RetornaStatus());
}
}
private static void InsereColaboradores()
{
Console.WriteLine("Inserir Colaborador:");
Console.WriteLine("Tipo de contratos:");
foreach(int i in Enum.GetValues(typeof(Tipo)))
{
Console.WriteLine("{0} - {1}", i, Enum.GetName(typeof(Tipo),i));
}
Console.WriteLine("Digite o contrato dentro das opções acima:");
int entradaTipo = int.Parse(Console.ReadLine());
Console.WriteLine("Digite o nome do colaborador:");
string entradaNome = Console.ReadLine();
Console.WriteLine("Digite a matrícula do colaborador:");
int entradaMatricula = int.Parse(Console.ReadLine());
Console.WriteLine("Digite o departamento do colaborador:");
string entradaSetor = Console.ReadLine();
Colaborador novoColaborador = new Colaborador(id: repositorio.ProximoId(),
contrato: (Tipo)entradaTipo,
nome: entradaNome,
setor: entradaSetor,
matricula: entradaMatricula
);
repositorio.Insere(novoColaborador);
}
private static string ObterOpcaoUsuario()
{
Console.WriteLine();
Console.WriteLine("Registro de Colaboradores!!");
Console.WriteLine("Informe a opção desejada");
Console.WriteLine("1 - Listar colaboradores");
Console.WriteLine("2 - Inserir colaborador");
Console.WriteLine("3 - Atualizar cadastro de colaborador");
Console.WriteLine("4 - Excluir colaborador");
Console.WriteLine("5 - Visualizar colaborador");
Console.WriteLine("C - Limpar Tela");
Console.WriteLine("X - Sair");
string opcaoUsuario = Console.ReadLine().ToUpper();
Console.WriteLine();
return opcaoUsuario;
}
}
}
<file_sep>/Enum/Tipo.cs
namespace DIO.Registro
{
public enum Tipo
{
CLT = 1,
CNPJ = 2,
Terceirizada = 3,
}
}<file_sep>/Classes/Colaborador.cs
using System;
namespace DIO.Registro
{
public class Colaborador:EntidadeBase
{
private Tipo Contrato {get; set;}
private string Nome {get; set;}
private string Setor {get;set;}
private int Matricula {get; set;}
private bool Status {get; set;}
public Colaborador(int id, Tipo contrato, string nome, string setor, int matricula)
{
this.Id = id;
this.Contrato = contrato;
this.Nome = nome;
this.Setor = setor;
this.Matricula = matricula;
this.Status = false;
}
public override string ToString()
{
string retorno = "";
retorno += "Nome: " + this.Nome + Environment.NewLine;
retorno += "Setor: " + this.Setor + Environment.NewLine;
retorno += "Contrato: " + this.Contrato + Environment.NewLine;
retorno += "Matrícula: " + this.Matricula + Environment.NewLine;
retorno += "Demitido?: " + this.Status;
return retorno;
}
public string RetornaNome()
{
return this.Nome;
}
public int RetornaId()
{
return this.Id;
}
public bool RetornaStatus()
{
return this.Status;
}
public void Excluir()
{
this.Status = true;
}
}
} | 01f7ecbee68bcb3f64c5c23ea3c6798fae544449 | [
"C#"
] | 4 | C# | rafaelcmorais02/Employee_Register_DOTNET | c3cfb1c5ba690bbabee2b29507f8c077617831b1 | a77ee2b70942a16529fa103da69001a773af86f9 |
refs/heads/master | <repo_name>mlankenau/hbci4java<file_sep>/chipcard/src/frontend/Makefile
DEFINES = -D__UNIX
INCLUDES = -I../include -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux
WARNINGS = -Wall
# removed "-Werror -pedantic" because of dlsym() typecast problem
CC = g++
CFLAGS = -fPIC $(DEFINES) $(INCLUDES) $(WARNINGS)
LIBS = -L../../bin -lzkachip-highlevel -lzkachip-lowlevel
SOURCES = frontend.cpp
OBJECTS = ../../bin/frontend.o
.SUFFIXES: .cpp .o
../../bin/%.o: %.cpp
$(CC) -c -o $@ $(CFLAGS) $<
all: depend ../../bin/libhbci4java-card-linux.so
depend: Makefile.depend
Makefile.depend: $(SOURCES)
for file in $(SOURCES); do echo -n "../../bin/"; gcc $(CFLAGS) -MM $$file; done >Makefile.depend
../../bin/libhbci4java-card-linux.so: $(OBJECTS) ../../bin/libzkachip-highlevel.a ../../bin/libzkachip-lowlevel.a
$(CC) -fPIC -shared -o $@ $(OBJECTS) $(LIBS)
include Makefile.depend
<file_sep>/src/org/kapott/hbci/xml/XMLData.java
/* $Id: XMLData.java,v 1.1 2011/05/04 22:38:04 willuhn Exp $
This file is part of HBCI4Java
Copyright (C) 2001-2008 <NAME>
HBCI4Java is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
HBCI4Java is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.kapott.hbci.xml;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/* contains data information for an xml tree */
public class XMLData
{
private Document rootdoc;
private Map nodes; // path -> node
private Properties values;
private Map restrictions;
private Map errors;
private boolean createOptionalElements;
public XMLData()
{
this.nodes=new Hashtable();
this.values=new Properties();
this.restrictions=new Hashtable();
this.errors=new Hashtable();
}
public Document getRootDoc()
{
return rootdoc;
}
public void setRootDoc(Document rootdoc)
{
this.rootdoc = rootdoc;
}
public void storeNode(String path, Node node)
{
this.nodes.put(path, node);
}
public Node getNodeByPath(String path)
{
return (Node)nodes.get(path);
}
public void setValue(String key, String value)
{
if (value!=null) {
this.values.setProperty(key, value);
}
}
public String getValue(String key)
{
return this.values.getProperty(key);
}
public Enumeration getValueNames()
{
return this.values.propertyNames();
}
public Map getErrors()
{
return this.errors;
}
public Iterator getRestrictionPaths()
{
return this.restrictions.keySet().iterator();
}
public Map getRestrictions(String path)
{
return (Map)this.restrictions.get(path);
}
public void setRestrictions(String path, Map restrictions)
{
this.restrictions.put(path, restrictions);
}
public void setCreateOptionalElements(boolean x)
{
this.createOptionalElements=x;
}
public boolean getCreateOptionalElements()
{
return this.createOptionalElements;
}
}
<file_sep>/src/org/kapott/hbci/GV/generators/AbstractSEPAGenerator.java
package org.kapott.hbci.GV.generators;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.kapott.hbci.manager.HBCIUtils;
import org.kapott.hbci.sepa.PainVersion;
/**
* Abstrakte Basis-Implementierung der SEPA-Generatoren.
*/
public abstract class AbstractSEPAGenerator implements ISEPAGenerator
{
/**
* Schreibt die Bean mittels JAXB in den Strean.
* @param e das zu schreibende JAXBElement mit der Bean.
* @param type der Typ der Bean.
* @param os
* @throws Exception
*/
protected void marshal(JAXBElement e, OutputStream os) throws Exception
{
JAXBContext jaxbContext = JAXBContext.newInstance(e.getDeclaredType());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
PainVersion version = this.getPainVersion();
if (version != null)
{
String schemaLocation = version.getSchemaLocation();
if (schemaLocation != null)
{
HBCIUtils.log("appending schemaLocation " + schemaLocation,HBCIUtils.LOG_DEBUG);
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,schemaLocation);
}
String file = version.getFile();
if (file != null)
{
boolean validate = HBCIUtils.getParam("sepa.schema.validation","0").equals("1");
if (validate)
{
InputStream is = this.getClass().getResourceAsStream(file);
if (is != null)
{
HBCIUtils.log("activating schema validation " + schemaLocation,HBCIUtils.LOG_DEBUG);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new StreamSource(is));
marshaller.setSchema(schema);
}
}
}
}
marshaller.marshal(e, os);
}
/**
* @see org.kapott.hbci.GV.generators.ISEPAGenerator#getPainVersion()
*/
@Override
public PainVersion getPainVersion()
{
return null;
}
}
<file_sep>/chipcard/Makefile
all: lib/libhbci4java-card-linux.so
lib/libhbci4java-card-linux.so: bin/libhbci4java-card-linux.so
cp bin/libhbci4java-card-linux.so lib/
bin/libhbci4java-card-linux.so: .make
.make:
make -C src all
clean:
-rm -f lib/libhbci4java-card-linux.so
-rm -f bin/*
-rm -f `find -name Makefile.depend`
<file_sep>/readme.txt
Hinweis zu "Hibiscus-Branch" von HBCI4Java.
Das SVN von hbci4java.kapott.org ist schon seit einiger Zeit nicht mehr
oeffentlich, weil da drin wegen HBCI4Java 3 grundlegende Aenderungen
stattfinden. Fuer 2.5.12 haben sich im Laufe der Zeit aber einige Patches
angesammelt, die auf http://hbci4java.kapott.org nicht veroeffentlicht wurden.
Daher habe ich im Hibiscus CVS diese HBCI4Java-Version eingecheckt.
Ausgangsbasis ist Version 2.5.12 mit einigen Patches von Stefan
(konkret seine SVN-Revision r227 vom 28.05.2010). Hinzugekommen sind
anschliessend noch ein paar weitere Patches. Verlauf also bisher:
2.5.12 (http://hbci4java.kapott.org/hbci4java-2.5.12-src.zip)
-> r227 (log/hbci4java-r227.tgz)
-> "Hibiscus-Branch" (r227+log/patches/*)
Ich werde versuchen, fuer alle weiteren Aenderungen, die ich hier vornehme,
nummerierte Diff-Dateien in log/patches abzulegen.
Wichtig: Damit das Projekt compiliert, muss einmal das Ant-Script
"thirdparty/cryptalgs4java/build.xml" mit dem Target "compile" ausghefuehrt
werden. Es erzeugt Klassen in "thirdparty/cryptalgs4java/bin/classes", die
von HBCI4Java benoetigt werden.
<file_sep>/src/org/kapott/hbci/GV/GVLastSEPAOrg.java
/* $Id: GVUebSEPA.java,v 1.1 2011/05/04 22:37:54 willuhn Exp $
This file is part of HBCI4Java
Copyright (C) 2001-2008 <NAME>
HBCI4Java is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
HBCI4Java is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.kapott.hbci.GV;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import org.kapott.hbci.GV_Result.HBCIJobResultImpl;
import org.kapott.hbci.manager.HBCIHandler;
import org.kapott.hbci.manager.HBCIUtils;
import org.kapott.hbci.manager.LogFilter;
import org.kapott.hbci.xml.XMLCreator2;
import org.kapott.hbci.xml.XMLData;
public class GVLastSEPAOrg
extends HBCIJobImpl
{
private Properties sepaParams;
public static String getLowlevelName()
{
return "LastSEPA";
}
public GVLastSEPAOrg(HBCIHandler handler,String name)
{
super(handler,name,new HBCIJobResultImpl());
this.sepaParams = new Properties();
}
public GVLastSEPAOrg(HBCIHandler handler)
{
this(handler,getLowlevelName());
addConstraint("dst.bic", "My.bic", null, LogFilter.FILTER_MOST);
addConstraint("dst.iban", "My.iban", null, LogFilter.FILTER_IDS);
/* TODO: take SEPA descriptor from list of supported descriptors (BPD) */
addConstraint("_sepadescriptor", "sepadescr", "sepade.pain.008.002.02.xsd", LogFilter.FILTER_NONE);
addConstraint("_sepapain", "sepapain", null, LogFilter.FILTER_IDS);
/* dummy constraints to allow an application to set these values. the
* overriden setLowlevelParam() stores these values in a special structure
* which is later used to create the SEPA pain document. */
addConstraint("src.bic", "sepa.src.bic", null, LogFilter.FILTER_MOST);
addConstraint("src.iban", "sepa.src.iban", null, LogFilter.FILTER_IDS);
addConstraint("src.name", "sepa.src.name", null, LogFilter.FILTER_IDS);
addConstraint("src.MandateId", "sepa.src.MandateId", null, LogFilter.FILTER_IDS);
addConstraint("src.DtOfSgntr", "sepa.src.DtOfSgntr", null, LogFilter.FILTER_IDS);
addConstraint("dst.bic", "sepa.dst.bic", null, LogFilter.FILTER_MOST);
addConstraint("dst.iban", "sepa.dst.iban", null, LogFilter.FILTER_IDS);
addConstraint("dst.name", "sepa.dst.name", null, LogFilter.FILTER_IDS);
addConstraint("dst.CdtrIdentifier", "sepa.dst.CdtrIdentifier", null, LogFilter.FILTER_IDS);
addConstraint("btg.value", "sepa.btg.value", null, LogFilter.FILTER_NONE);
addConstraint("btg.curr", "sepa.btg.curr", "EUR", LogFilter.FILTER_NONE);
addConstraint("usage", "sepa.usage", null, LogFilter.FILTER_NONE);
}
/* This is needed to "redirect" the sepa values. They dont have to stored
* directly in the message, but have to go into the SEPA document which will
* by created later (in verifyConstraints()) */
protected void setLowlevelParam(String key, String value)
{
String intern=getName()+".sepa.";
if (key.startsWith(intern)) {
String realKey=key.substring(intern.length());
this.sepaParams.setProperty(realKey, value);
HBCIUtils.log("setting SEPA param "+realKey+" = "+value, HBCIUtils.LOG_DEBUG);
} else {
super.setLowlevelParam(key, value);
}
}
/* This is needed for verifyConstraints(). Because verifyConstraints() tries
* to read the lowlevel-values for each constraint, the lowlevel-values for
* sepa.xxx would always be empty (because they do not exist in hbci messages).
* So we read the sepa lowlevel-values from the special sepa structure instead
* from the lowlevel params for the message */
public String getLowlevelParam(String key)
{
String result;
String intern=getName()+".sepa.";
if (key.startsWith(intern)) {
String realKey=key.substring(intern.length());
result=getSEPAParam(realKey);
} else {
result=super.getLowlevelParam(key);
}
return result;
}
protected String getSEPAMessageId()
{
String result=getSEPAParam("messageId");
if (result==null) {
Date now=new Date();
result=now.getTime() + "-" + getMainPassport().getUserId();
result=result.substring(0, Math.min(result.length(),35));
setSEPAParam("messageId", result);
}
return result;
}
protected String createSEPATimestamp()
{
Date now=new Date();
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return format.format(now);
}
protected void createSEPAFromParams()
{
// open SEPA descriptor and create an XML-Creator using it
/* TODO: load correct schema files depending on the SEPA descriptor set
* above, depending on the supported SEPA descriptors (BPD) */
InputStream f=this.getClass().getClassLoader().getResourceAsStream("pain.008.002.02.xsd");
XMLCreator2 creator=new XMLCreator2(f);
int size = 1;
/* TODO: Mehr als Eintrag
float sumvalue = 0;
for (int i=0; i<size ; ++i)
sumvalue += btg.value;
*/
// define data to be filled into SEPA document
XMLData xmldata=new XMLData();
xmldata.setValue("Document/pain.008.002.02/GrpHdr/MsgId", getSEPAMessageId());
xmldata.setValue("Document/pain.008.002.02/GrpHdr/CreDtTm", createSEPATimestamp());
xmldata.setValue("Document/pain.008.002.02/GrpHdr/NbOfTxs", "1");
// TODO: Gesamtbetrag wenn size > 1 bei mehr als einem Eintrag
xmldata.setValue("Document/pain.008.002.02/GrpHdr/CtrlSum", getSEPAParam("btg.value"));
xmldata.setValue("Document/pain.008.002.02/GrpHdr/InitgPty/Nm", getSEPAParam("dst.name"));
xmldata.setValue("Document/pain.008.002.02/PmtInf/PmntInfId", getSEPAParam("dst.CdtrIdentifier"));
xmldata.setValue("Document/pain.008.002.02/PmtInf/PmntInfMtd", "DD");
// TODO: Wert auf Anzahl bei mehr als einem Eintrag
xmldata.setValue("Document/pain.008.002.02/PmtInf/NbOfTxs", "1");
// TODO: Gesamtbetrag wenn size > 1
xmldata.setValue("Document/pain.008.002.02/PmtInf/CtrlSum", getSEPAParam("btg.value"));
// Payment Type Id: Basislastschrift
xmldata.setValue("Document/pain.008.002.02/PmtInf/PmtTpInf/SvcLvl/Cd", "SEPA");
// TODO: wenn Kunde kein Verbraucher, muss hier B2B stehen, für die Business-Kunden
xmldata.setValue("Document/pain.008.002.02/PmtInf/PmtTpInf/LclInstrm/Cd", "CORE");
// TODO: Nur bei einmaliger Einreichung: sonst FRST bei erster, RCUR bei allen weiteren.
xmldata.setValue("Document/pain.008.002.02/PmtInf/PmtTpInf/SeqTp", "OOFF");
xmldata.setValue("Document/pain.008.002.02/PmtInf/ReqdColltnDt", "1999-01-01"); // hart kodiert
// Angaben zum Empfänger der Lastschrift
xmldata.setValue("Document/pain.008.002.02/PmtInf/Cdtr/Nm", getSEPAParam("dst.name"));
xmldata.setValue("Document/pain.008.002.02/PmtInf/CdtrAgt/FinInstnId/BIC", getSEPAParam("dst.bic"));
xmldata.setValue("Document/pain.008.002.02/PmtInf/CdtrAcct/Id/IBAN", getSEPAParam("dst.iban"));
xmldata.setValue("Document/pain.008.002.02/PmtInf/ChrgBr", "SLEV");
// NEU Gläubiger-Identifikationsnummer: muss der Einreicher der Lastschrift angeben
xmldata.setValue("Document/pain.008.002.02/PmtInf/CdtrSchmeId/Id/PrvtId/Othr/Id", getSEPAParam("dst.CdtrIdentifier"));
xmldata.setValue("Document/pain.008.002.02/PmtInf/CdtrSchmeId/Id/PrvtId/Othr/SchmeNm/Prtry", "SEPA");
// for (int i=0; i<size ; ++i) TODO: Mehr als Eintrag
{
// Angaben zum Schuldner
xmldata.setValue("Document/pain.008.002.02/PmtInf/DrctDbtTxInf/InstdAmt", getSEPAParam("btg.value"));
xmldata.setValue("Document/pain.008.002.02/PmtInf/DrctDbtTxInf/InstdAmt:Ccy", getSEPAParam("btg.curr"));
// NEU Mandatsreferenznummer, wird vom Einreicher jedem Kunden zugewiesen
xmldata.setValue("Document/pain.008.002.02/PmtInf/DrctDbtTxInf/DrctDbtTx/MndtRltdInf/MndtId",
getSEPAParam("src.MandateId"));
// NEU Datum der Einzugsermächtigung
xmldata.setValue("Document/pain.008.002.02/PmtInf/DrctDbtTxInf/DrctDbtTx/MndtRltdInf/DtOfSgntr",
getSEPAParam("src.DtOfSgntr"));
// NEU laut [ksk] optional
xmldata.setValue("Document/pain.008.002.02/PmtInf/DrctDbtTxInf/DrctDbtTx/MndtRltdInf/AmdmntInd", "false");
xmldata.setValue("Document/pain.008.002.02/PmtInf/DrctDbtTxInf/Dbtr/Nm",
getSEPAParam("src.name"));
xmldata.setValue("Document/pain.008.002.02/PmtInf/DrctDbtTxInf/DbtrAgt/FinInstnId/BIC",
getSEPAParam("src.bic"));
xmldata.setValue("Document/pain.008.002.02/PmtInf/DrctDbtTxInf/DbtrAcct/Id/IBAN",
getSEPAParam("src.iban"));
// TODO: bei mehreren Einträgen Unterschiedlich für alle
xmldata.setValue("Document/pain.008.002.02/PmtInf/DrctDbtTxInf/PmtId/EndToEndId", getSEPAMessageId());
// TODO: muss Richtlinien entsprechen
xmldata.setValue("Document/pain.008.002.02/PmtInf/DrctDbtTxInf/RmtInf/Ustrd", getSEPAParam("usage"));
}
/*
*
* Quellen:
* Beispiel-Datei: http://www.ebics.de/fileadmin/unsecured/anlage3/anlage3_archiv/Anlage3_V2_6_gueltigBis2013-11-03.zip
* [ksk] https://www.ksk-koeln.de/erstellung-einer-sepa-lastschriftdatei-aus-dta-dateien.xlsx?forced=true
* [bayernlb] http://www.bayernlb.de/internet/media/internet_4/de_1/downloads_5/0800_financial_office_it_operations_5/4200_1/sepa_5/sepaaktuell/Newsletter_SEPA_006.pdf
<PmtInf>
!<PmtInfId>Payment-ID</PmtInfId>
!<PmtMtd>DD</PmtMtd>
!<NbOfTxs>2</NbOfTxs>
!<CtrlSum>6655.86</CtrlSum>
!<PmtTpInf>
! <SvcLvl>
! <Cd>SEPA</Cd>
! </SvcLvl>
! <LclInstrm>
! <Cd>CORE</Cd>
! </LclInstrm>
! <SeqTp>FRST</SeqTp>
!</PmtTpInf>
!<ReqdColltnDt>2010-12-03</ReqdColltnDt>
!<Cdtr>
! <Nm>Creditor Name</Nm>
!</Cdtr>
!<CdtrAcct>
! <Id>
! <IBAN>DE87200500001234567890</IBAN>
! </Id>
!</CdtrAcct>
!<CdtrAgt>
! <FinInstnId>
! <BIC>BANKDEFFXXX</BIC>
! </FinInstnId>
!</CdtrAgt>
<ChrgBr>SLEV</ChrgBr>
!<CdtrSchmeId> <Id>
! <PrvtId>
! <Othr>
! <Id>DE00ZZZ00099999999</Id>
! <SchmeNm>
! <Prtry>SEPA</Prtry>
! </SchmeNm>
! </Othr>
! </PrvtId>
! </Id>
!</CdtrSchmeId>
<DrctDbtTxInf>
<PmtId>
<EndToEndId>OriginatorID1234</EndToEndId>
// ist optional, erstmal weggelassen [bayernlb]
</PmtId>
! <InstdAmt Ccy="EUR">6543.14</InstdAmt>
! <DrctDbtTx>
! <MndtRltdInf>
! <MndtId>Mandate-Id</MndtId>
! <DtOfSgntr>2010-11-20</DtOfSgntr>
! ! Dtls optional wenn auf false [ksk], weggelassen
! <AmdmntInd>true</AmdmntInd>
! <AmdmntInfDtls>
! <OrgnlCdtrSchmeId>
! <Nm>Original Creditor Name</Nm>
! <Id>
! <PrvtId>
! <Othr>
! <Id>AA00ZZZOriginalCreditorID</Id>
! <SchmeNm>
! <Prtry>SEPA</Prtry>
! </SchmeNm>
! </Othr>
! </PrvtId>
! </Id>
! </OrgnlCdtrSchmeId>
! </AmdmntInfDtls>
! </MndtRltdInf>
! </DrctDbtTx>
! <DbtrAgt>
! <FinInstnId>
! <BIC>SPUEDE2UXXX</BIC>
! </FinInstnId>
! </DbtrAgt>
! <Dbtr>
! <Nm>Debtor Name</Nm>
! </Dbtr>
! <DbtrAcct>
! <Id>
! <IBAN>DE21500500009876543210</IBAN>
! </Id>
! </DbtrAcct>
<UltmtDbtr>
<Nm>Ultimate Debtor Name</Nm>
</UltmtDbtr>
<RmtInf>
<Ustrd>Unstructured Remittance Information</Ustrd>
</RmtInf>
</DrctDbtTxInf>
<DrctDbtTxInf>
<PmtId>
<EndToEndId>OriginatorID1235</EndToEndId>
</PmtId>
<InstdAmt Ccy="EUR">112.72</InstdAmt>
<DrctDbtTx>
<MndtRltdInf>
<MndtId>Other-Mandate-Id</MndtId>
<DtOfSgntr>2010-11-20</DtOfSgntr>
<AmdmntInd>false</AmdmntInd>
</MndtRltdInf>
</DrctDbtTx>
<DbtrAgt>
<FinInstnId>
<BIC>SPUEDE2UXXX</BIC>
</FinInstnId>
</DbtrAgt>
<Dbtr>
<Nm>Other Debtor Name</Nm>
</Dbtr>
<DbtrAcct>
<Id>
<IBAN>DE21500500001234567897</IBAN>
</Id>
</DbtrAcct>
<UltmtDbtr>
<Nm>Ultimate Debtor Name</Nm>
</UltmtDbtr>
<RmtInf>
<Ustrd>Unstructured Remittance Information</Ustrd>
</RmtInf>
</DrctDbtTxInf>
</PmtInf>
*/
// create SEPA document
ByteArrayOutputStream o=new ByteArrayOutputStream();
creator.createXMLFromSchemaAndData(xmldata, o);
// store SEPA document as parameter
try {
setParam("_sepapain", "B"+o.toString("ISO-8859-1"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public void verifyConstraints()
{
// creating SEPA document and storing it in _sepapain
createSEPAFromParams();
// verify all constraints
super.verifyConstraints();
// TODO: checkIBANCRC
}
protected void setSEPAParam(String name, String value)
{
this.sepaParams.setProperty(name, value);
}
protected String getSEPAParam(String name)
{
return this.sepaParams.getProperty(name);
}
}
<file_sep>/src/org/kapott/hbci/GV/generators/GenUebSEPA00100303.java
package org.kapott.hbci.GV.generators;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.datatype.DatatypeFactory;
import org.kapott.hbci.GV.AbstractSEPAGV;
import org.kapott.hbci.sepa.PainVersion;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.AccountIdentificationSEPA;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.ActiveOrHistoricCurrencyAndAmountSEPA;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.ActiveOrHistoricCurrencyCodeEUR;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.AmountTypeSEPA;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.BranchAndFinancialInstitutionIdentificationSEPA1;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.BranchAndFinancialInstitutionIdentificationSEPA3;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.CashAccountSEPA1;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.CashAccountSEPA2;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.ChargeBearerTypeSEPACode;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.CreditTransferTransactionInformationSCT;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.CustomerCreditTransferInitiationV03;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.Document;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.FinancialInstitutionIdentificationSEPA1;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.FinancialInstitutionIdentificationSEPA3;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.GroupHeaderSCT;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.ObjectFactory;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.PartyIdentificationSEPA1;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.PartyIdentificationSEPA2;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.PaymentIdentificationSEPA;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.PaymentInstructionInformationSCT;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.PaymentMethodSCTCode;
import org.kapott.hbci.sepa.jaxb.pain_001_003_03.RemittanceInformationSEPA1Choice;
/**
* SEPA-Generator fuer pain.001.003.03.
*/
public class GenUebSEPA00100303 extends AbstractSEPAGenerator
{
/**
* @see org.kapott.hbci.GV.generators.AbstractSEPAGenerator#getPainVersion()
*/
@Override
public PainVersion getPainVersion()
{
return PainVersion.PAIN_001_003_03;
}
/**
* @see org.kapott.hbci.GV.generators.ISEPAGenerator#generate(org.kapott.hbci.GV.AbstractSEPAGV, java.io.OutputStream)
*/
public void generate(AbstractSEPAGV job, OutputStream os) throws Exception
{
//Formatter um Dates ins gewünschte ISODateTime Format zu bringen.
Date now=new Date();
SimpleDateFormat sdtf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DatatypeFactory df = DatatypeFactory.newInstance();
//Document
Document doc = new Document();
//Customer Credit Transfer Initiation
doc.setCstmrCdtTrfInitn(new CustomerCreditTransferInitiationV03());
doc.getCstmrCdtTrfInitn().setGrpHdr(new GroupHeaderSCT());
//Group Header
doc.getCstmrCdtTrfInitn().getGrpHdr().setMsgId(job.getSEPAParam("sepaid"));
doc.getCstmrCdtTrfInitn().getGrpHdr().setCreDtTm(df.newXMLGregorianCalendar(sdtf.format(now)));
doc.getCstmrCdtTrfInitn().getGrpHdr().setNbOfTxs("1");
doc.getCstmrCdtTrfInitn().getGrpHdr().setInitgPty(new PartyIdentificationSEPA1());
doc.getCstmrCdtTrfInitn().getGrpHdr().getInitgPty().setNm(job.getSEPAParam("src.name"));
//Payment Information
ArrayList<PaymentInstructionInformationSCT> pmtInfs = (ArrayList<PaymentInstructionInformationSCT>) doc.getCstmrCdtTrfInitn().getPmtInf();
PaymentInstructionInformationSCT pmtInf = new PaymentInstructionInformationSCT();
pmtInfs.add(pmtInf);
//FIXME: Wo kommt die ID her und wie muss sie aussehen?
pmtInf.setPmtInfId(job.getSEPAParam("sepaid"));
pmtInf.setPmtMtd(PaymentMethodSCTCode.TRF);
pmtInf.setReqdExctnDt(df.newXMLGregorianCalendar("1999-01-01"));
pmtInf.setDbtr(new PartyIdentificationSEPA2());
pmtInf.setDbtrAcct(new CashAccountSEPA1());
pmtInf.setDbtrAgt(new BranchAndFinancialInstitutionIdentificationSEPA3());
//Payment Information - Debtor
pmtInf.getDbtr().setNm(job.getSEPAParam("src.name"));
//Payment Information - DebtorAccount
pmtInf.getDbtrAcct().setId(new AccountIdentificationSEPA());
pmtInf.getDbtrAcct().getId().setIBAN(job.getSEPAParam("src.iban"));
//Payment Information - DebtorAgent
pmtInf.getDbtrAgt().setFinInstnId(new FinancialInstitutionIdentificationSEPA3());
pmtInf.getDbtrAgt().getFinInstnId().setBIC(job.getSEPAParam("src.bic"));
//Payment Information - ChargeBearer
pmtInf.setChrgBr(ChargeBearerTypeSEPACode.SLEV);
//Payment Information - Credit Transfer Transaction Information
ArrayList<CreditTransferTransactionInformationSCT> cdtTrxTxInfs = (ArrayList<CreditTransferTransactionInformationSCT>) pmtInf.getCdtTrfTxInf();
CreditTransferTransactionInformationSCT cdtTrxTxInf = new CreditTransferTransactionInformationSCT();
cdtTrxTxInfs.add(cdtTrxTxInf);
//Payment Information - Credit Transfer Transaction Information - Payment Identification
cdtTrxTxInf.setPmtId(new PaymentIdentificationSEPA());
cdtTrxTxInf.getPmtId().setEndToEndId(job.getSEPAParam("endtoendid"));
//Payment Information - Credit Transfer Transaction Information - Creditor
cdtTrxTxInf.setCdtr(new PartyIdentificationSEPA2());
cdtTrxTxInf.getCdtr().setNm(job.getSEPAParam("dst.name"));
//Payment Information - Credit Transfer Transaction Information - Creditor Account
cdtTrxTxInf.setCdtrAcct(new CashAccountSEPA2());
cdtTrxTxInf.getCdtrAcct().setId(new AccountIdentificationSEPA());
cdtTrxTxInf.getCdtrAcct().getId().setIBAN(job.getSEPAParam("dst.iban"));
//Payment Information - Credit Transfer Transaction Information - Creditor Agent
cdtTrxTxInf.setCdtrAgt(new BranchAndFinancialInstitutionIdentificationSEPA1());
cdtTrxTxInf.getCdtrAgt().setFinInstnId(new FinancialInstitutionIdentificationSEPA1());
cdtTrxTxInf.getCdtrAgt().getFinInstnId().setBIC(job.getSEPAParam("dst.bic"));
//Payment Information - Credit Transfer Transaction Information - Amount
cdtTrxTxInf.setAmt(new AmountTypeSEPA());
cdtTrxTxInf.getAmt().setInstdAmt(new ActiveOrHistoricCurrencyAndAmountSEPA());
cdtTrxTxInf.getAmt().getInstdAmt().setValue(new BigDecimal(job.getSEPAParam("btg.value")));
//FIXME: Schema sagt es gibt nur "eur" aber besser wäre bestimmt trotzdem getSEPAParam("btg.curr") oder?
cdtTrxTxInf.getAmt().getInstdAmt().setCcy(ActiveOrHistoricCurrencyCodeEUR.EUR);
//Payment Information - Credit Transfer Transaction Information - Usage
//FIXME: momentan nur unstrukturierter Verwendungszweck! Vielleicht gibt es einen Parameter dafür? Dann kann man per If entscheiden
cdtTrxTxInf.setRmtInf(new RemittanceInformationSEPA1Choice());
cdtTrxTxInf.getRmtInf().setUstrd(job.getSEPAParam("usage"));
ObjectFactory of = new ObjectFactory();
this.marshal(of.createDocument(doc),os);
}
}
<file_sep>/src/org/kapott/hbci/xml/XMLEntity.java
/* $Id: XMLEntity.java,v 1.1 2011/05/04 22:38:04 willuhn Exp $
This file is part of HBCI4Java
Copyright (C) 2001-2008 <NAME>
HBCI4Java is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
HBCI4Java is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.kapott.hbci.xml;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/* An XMLEntity is either an element or an attribute with a "path" */
public class XMLEntity
{
private Node node;
private String path;
public XMLEntity(Node node, String path)
{
this.node=node;
this.path=path;
}
public Node getNode()
{
return node;
}
public void setNode(Node node)
{
this.node = node;
}
public String getPath()
{
return path;
}
public void setPath(String path)
{
this.path = path;
}
public Element getElement()
{
return (Element)this.getNode();
}
public String toString()
{
return "<XMLEntity "+this.path+">";
}
}
<file_sep>/test/hbci4java/sepa/TestPainGen.java
/**********************************************************************
* $Source: /cvsroot/hibiscus/hbci4java/test/hbci4java/ddv/PCSCTest.java,v $
* $Revision: 1.1 $
* $Date: 2011/11/24 21:59:37 $
* $Author: willuhn $
*
* Copyright (c) by willuhn - software & services
* All rights reserved
*
**********************************************************************/
package hbci4java.sepa;
import hbci4java.AbstractTest;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.validation.SchemaFactory;
import org.junit.Test;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.AccountIdentification2;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.AmountType3;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.CashAccount8;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.ChargeBearerType2Code;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.CreditTransferTransactionInformation2;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.Document;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.EuroMax9Amount;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.FinancialInstitution2;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.FinancialInstitutionIdentification4;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.GroupHeader20;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.Grouping2Code;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.ObjectFactory;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.Pain00100102;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.PartyIdentification20;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.PartyIdentification21;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.PartyIdentification23;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.PaymentIdentification1;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.PaymentInstructionInformation4;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.PaymentMethod5Code;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.PaymentTypeInformation7;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.RemittanceInformation3;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.ServiceLevel3Code;
import org.kapott.hbci.sepa.jaxb.pain_001_001_02.ServiceLevel4;
import org.kapott.hbci.xml.XMLCreator2;
import org.kapott.hbci.xml.XMLData;
/**
* Testet das Generieren von Pain XML-Dateien.
*/
public class TestPainGen extends AbstractTest
{
/**
* Erstellt eine Pain-Nachricht mit dem alten XMLCreator und mit JAXB und vergleicht das Ergebnis.
* @throws Exception
*/
@Test
public void test001() throws Exception
{
String sOld = this.viaXMLCreator2();
System.out.println(sOld);
String sNew = this.viaJAXB();
System.out.println(sNew);
}
private String viaJAXB() throws Exception
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DatatypeFactory df = DatatypeFactory.newInstance();
// Document doc = new Document();
ObjectFactory factory = new ObjectFactory();
Document doc = factory.createDocument();
Pain00100102 pain = new Pain00100102();
GroupHeader20 grpHdr = new GroupHeader20();
PartyIdentification20 initgPty = new PartyIdentification20();
PaymentInstructionInformation4 pmtInf = new PaymentInstructionInformation4();
PartyIdentification23 dbtr = new PartyIdentification23();
FinancialInstitution2 dbtrAgt = new FinancialInstitution2();
FinancialInstitutionIdentification4 finInstnId = new FinancialInstitutionIdentification4();
CashAccount8 dbtrAcct = new CashAccount8();
AccountIdentification2 id = new AccountIdentification2();
CreditTransferTransactionInformation2 cdtTrfTxInf = new CreditTransferTransactionInformation2();
PartyIdentification21 cdtr = new PartyIdentification21();
FinancialInstitution2 cdtrAgt = new FinancialInstitution2();
FinancialInstitutionIdentification4 finInstnId2 = new FinancialInstitutionIdentification4();
CashAccount8 cdtrAcct = new CashAccount8();
AccountIdentification2 id2 = new AccountIdentification2();
AmountType3 amt = new AmountType3();
EuroMax9Amount instdAmt = new EuroMax9Amount();
RemittanceInformation3 rmtInf = new RemittanceInformation3();
PaymentIdentification1 pmtId = new PaymentIdentification1();
PaymentTypeInformation7 pmtTpInf = new PaymentTypeInformation7();
ServiceLevel4 svcLvl = new ServiceLevel4();
svcLvl.setCd(ServiceLevel3Code.SEPA);
pmtTpInf.setSvcLvl(svcLvl);
doc.setPain00100102(pain);
pain.setGrpHdr(grpHdr);
pain.setPmtInf(pmtInf);
grpHdr.setInitgPty(initgPty);
pmtInf.setDbtr(dbtr);
pmtInf.setDbtrAgt(dbtrAgt);
pmtInf.setDbtrAcct(dbtrAcct);
pmtInf.getCdtTrfTxInf().add(cdtTrfTxInf);
pmtInf.setChrgBr(ChargeBearerType2Code.SLEV);
dbtrAgt.setFinInstnId(finInstnId);
dbtrAcct.setId(id);
cdtTrfTxInf.setCdtr(cdtr);
cdtTrfTxInf.setCdtrAgt(cdtrAgt);
cdtrAgt.setFinInstnId(finInstnId2);
cdtTrfTxInf.setCdtrAcct(cdtrAcct);
cdtrAcct.setId(id2);
cdtTrfTxInf.setAmt(amt);
amt.setInstdAmt(instdAmt);
cdtTrfTxInf.setRmtInf(rmtInf);
cdtTrfTxInf.setPmtId(pmtId);
grpHdr.setMsgId("Message-ID-4711");
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(format.parse("2008-05-11T09:30:47.000Z"));
grpHdr.setCreDtTm(df.newXMLGregorianCalendar(cal));
grpHdr.setGrpg(Grouping2Code.GRPD);
grpHdr.setNbOfTxs("1");
initgPty.setNm("Name 1");
dbtr.setNm("Name 2");
finInstnId.setBIC("MY-BIC");
id.setIBAN("MY-IBAN");
cdtr.setNm("<NAME>");
finInstnId2.setBIC("OTHER-BIC");
id2.setIBAN("OTHER-IBAN");
instdAmt.setValue(new BigDecimal("1.23"));
instdAmt.setCcy("EUR");
rmtInf.setUstrd("Verwendungszweck");
pmtId.setEndToEndId("NOTPROVIDED");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
cal.setTime(format2.parse("1999-01-01"));
pmtInf.setPmtMtd(PaymentMethod5Code.TRF);
pmtInf.setPmtTpInf(pmtTpInf);
XMLGregorianCalendar cal2 = df.newXMLGregorianCalendar(cal);
pmtInf.setReqdExctnDt(cal2);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Schema schema = schemaFactory.newSchema(new File("src/pain.001.001.02.xsd"));
JAXBContext jaxbContext = JAXBContext.newInstance(Document.class);
Marshaller marshaller = jaxbContext.createMarshaller();
// marshaller.setSchema(schema);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(factory.createDocument(doc) ,bos);
ObjectFactory of = new ObjectFactory();
marshaller.marshal(of.createDocument(doc),bos);
return bos.toString("UTF-8");
}
private String viaXMLCreator2() throws Exception
{
FileInputStream f = new FileInputStream("src/pain.001.001.02.xsd");
XMLCreator2 creator = new XMLCreator2(f);
XMLData xmldata=new XMLData();
xmldata.setValue("Document/pain.001.001.02/GrpHdr/MsgId", "Message-ID-4711");
xmldata.setValue("Document/pain.001.001.02/GrpHdr/CreDtTm", "2008-05-11T09:30:47.000Z");
xmldata.setValue("Document/pain.001.001.02/GrpHdr/NbOfTxs", "1");
xmldata.setValue("Document/pain.001.001.02/GrpHdr/InitgPty/Nm", "Name 1");
xmldata.setValue("Document/pain.001.001.02/PmtInf/Dbtr/Nm", "Name 2");
xmldata.setValue("Document/pain.001.001.02/PmtInf/DbtrAgt/FinInstnId/BIC", "MY-BIC");
xmldata.setValue("Document/pain.001.001.02/PmtInf/DbtrAcct/Id/IBAN", "MY-IBAN");
xmldata.setValue("Document/pain.001.001.02/PmtInf/CdtTrfTxInf/Cdtr/Nm", "Der Empfaenger");
xmldata.setValue("Document/pain.001.001.02/PmtInf/CdtTrfTxInf/CdtrAgt/FinInstnId/BIC", "OTHER-BIC");
xmldata.setValue("Document/pain.001.001.02/PmtInf/CdtTrfTxInf/CdtrAcct/Id/IBAN", "OTHER-IBAN");
xmldata.setValue("Document/pain.001.001.02/PmtInf/CdtTrfTxInf/Amt/InstdAmt", "1.23");
xmldata.setValue("Document/pain.001.001.02/PmtInf/CdtTrfTxInf/Amt/InstdAmt:Ccy", "EUR");
xmldata.setValue("Document/pain.001.001.02/PmtInf/CdtTrfTxInf/RmtInf/Ustrd", "Verwendungszweck");
xmldata.setValue("Document/pain.001.001.02/PmtInf/CdtTrfTxInf/PmtId/EndToEndId", "NOTPROVIDED");
xmldata.setValue("Document/pain.001.001.02/PmtInf/ReqdExctnDt", "1999-01-01"); // hart kodiert
ByteArrayOutputStream bos = new ByteArrayOutputStream();
creator.createXMLFromSchemaAndData(xmldata, bos);
return bos.toString("UTF-8");
}
}
| 5992e869351b1cfb554b76f764a020c493cfeeca | [
"Text",
"Java",
"Makefile"
] | 9 | Makefile | mlankenau/hbci4java | 6b4ccb75df3f99b38370765b818c9065e95226fc | b06ea34737a4e29e52333e81018d8c30f2561c47 |
refs/heads/master | <repo_name>lace1010/Sudoku-Solver<file_sep>/tests/1_unit-tests.js
const chai = require("chai");
const assert = chai.assert;
const Solver = require("../controllers/sudoku-solver.js");
let solver = new Solver();
suite("UnitTests", () => {
test("Logic handles a valid puzzle string of 81 characters", (done) => {
let input =
"..9..172.16.17.32....2432......1...69.83.9.....6.62.71...9......1945....192.168.127.12..6..";
assert.equal(solver.validate(input), "correct puzzle");
done();
});
test("Logic handles a puzzle string with invalid characters", (done) => {
let input =
"j?9..172.16.17.32....2432......1...69.83.9.....6.62.71...9......1945....192.168.127.12..6..";
assert.deepEqual(solver.validate(input), {
error: "Invalid characters in puzzle",
});
done();
});
test("Logic handles a puzzle string that is not 81 characters in length", (done) => {
let input = "..9..5.1.85.";
assert.deepEqual(solver.validate(input), {
error: "Expected puzzle to be 81 characters long",
});
done();
});
test("Logic handles a valid row placement", (done) => {
let input =
"..9..172.16.17.32....2432......1...69.83.9.....6.62.71...9......1945....192.168.127.12..6..";
assert.isArray(solver.filterRow(input));
done();
});
test("Logic handles an invalid row placement", (done) => {
let input =
"999..172.16.17.32....2432......1...69.83.9.....6.62.71...9......1945....192.168.127.12..6..";
assert.equal(solver.filterRow(input), "invalid rows");
done();
});
test("Logic handles a valid column placement", (done) => {
let input =
"..9..172.16.17.32....2432......1...69.83.9.....6.62.71...9......1945....192.168.127.12..6..";
assert.isArray(solver.filterColumn(input));
done();
});
test("Logic handles an invalid column placement", (done) => {
let input =
"..9..5.1.8594....2432......1...69.83.9.....6.62.71...9......1945....192.168.127.12..6..";
assert.equal(solver.filterColumn(input), "invalid columns");
done();
});
test("Logic handles a valid region (3x3 grid) placement", (done) => {
let input =
"..9..172.16.17.32....2432......1...69.83.9.....6.62.71...9......1945....192.168.127.12..6..";
assert.isArray(solver.filterRegion(input));
done();
});
test("Logic handles an invalid region (3x3 grid) placement", (done) => {
let input =
".99..172.16.17.32....2432......1...69.83.9.....6.62.71...9......1945....192.168.127.12..6..";
assert.equal(solver.filterRegion(input), "invalid regions");
done();
});
test("Valid puzzle strings pass the solver", (done) => {
let input =
"..9..172.16.17.32....2432......1...69.83.9.....6.62.71...9......1945....192.168.127.12..6..";
let board = solver.stringToBoard(input);
assert.equal(solver.sudokuSolver(board), true);
done();
});
test("Valid puzzle strings pass the solver", (done) => {
// Make input pass all requirements but still unsolveable but placing a random number in . that could be one of many solutions.
let input =
"..9..172.16.17.32....2432......1...69.83.9.....6.62471...9......1945....192.168.127.12..6..";
let board = solver.stringToBoard(input);
assert.equal(solver.sudokuSolver(board), false);
done();
});
test("Solver returns the the expected solution for an incomplete puzzzle", (done) => {
// Make input pass all requirements but still unsolveable but placing a random number in . that could be one of many solutions.
let input =
"..9..172.16.17.32....2432......1...69.83.9.....6.62.71...9......1945....192.168.127.12..6..";
let board = solver.stringToBoard(input);
solver.sudokuSolver(board); // changes board to solve board.
let solvedString = solver.boardToString(board);
assert.notInclude(solvedString, ".");
done();
});
});
<file_sep>/controllers/sudoku-solver.js
class SudokuSolver {
validate(puzzleString) {
let notNumberOrPeriodRegex = /[^\.0-9]/;
// Add invalid characters condition
if (notNumberOrPeriodRegex.test(puzzleString)) {
return { error: "Invalid characters in puzzle" };
} else if (puzzleString.length !== 81) {
return {
error: "Expected puzzle to be 81 characters long",
};
} else return "correct puzzle";
}
filterRow(puzzleString) {
let doubleNumberRegex = /([1-9]).*\1/;
// split string up into 9 rows using regex and match
let puzzleArrayInRows = puzzleString.match(/.{9}/g);
let filteredRowArray = puzzleArrayInRows.filter((i) => {
return !doubleNumberRegex.test(i);
});
if (filteredRowArray.length == 9) return filteredRowArray;
else return "invalid rows";
}
filterColumn(puzzleString) {
let doubleNumberRegex = /([1-9]).*\1/;
let puzzleArrayInColumns = [];
let columnArray = [];
for (let i = 0; i < 9; i++) {
columnArray.push(puzzleString[i]); // need to push in initial value
// for each index we cycle through valid 81 character string to get column
for (let j = 0; j < 81; j += 9) {
columnArray.push(puzzleString.slice(i + j + 9, i + 1 + j + 9));
}
}
// We join all of the columns characters together to make one big string then match for every 9 characters to form array of columns
puzzleArrayInColumns = columnArray.join("").match(/.{9}/g);
let filteredColumnArray = puzzleArrayInColumns.filter((i) => {
return !doubleNumberRegex.test(i);
});
if (filteredColumnArray.length == 9) return filteredColumnArray;
else return "invalid columns";
}
filterRegion(puzzleString) {
let doubleNumberRegex = /([1-9]).*\1/;
let splitArrayInThree = puzzleString.match(/.{3}/g);
let puzzleArray = [];
// regions for top
for (let i = 0; i < 3; i++) {
puzzleArray.push(
splitArrayInThree[i],
splitArrayInThree[i + 3],
splitArrayInThree[i + 6]
);
}
// regions for middle
for (let i = 9; i < 12; i++) {
puzzleArray.push(
splitArrayInThree[i],
splitArrayInThree[i + 3],
splitArrayInThree[i + 6]
);
}
// regions for bottom
for (let i = 18; i < 21; i++) {
puzzleArray.push(
splitArrayInThree[i],
splitArrayInThree[i + 3],
splitArrayInThree[i + 6]
);
}
// Split the regions in groups of 3 so the first 3 sets is the first region. So on and so on.
let puzzleArrayInRegionsSplit = [];
for (var i = 0, end = puzzleArray.length / 3; i < end; ++i) {
puzzleArrayInRegionsSplit.push(puzzleArray.slice(i * 3, (i + 1) * 3));
}
// Map through each region and join the three split mini regions to form the 9 whole regions.
let puzzleArrayInRegions = puzzleArrayInRegionsSplit.map((item) => {
return item.join("");
});
// Now that we have an array of 9 regions as strings filter to see if one has a number twice.
let filteredRegionArray = puzzleArrayInRegions.filter((item) => {
return !doubleNumberRegex.test(item);
});
// Return the filtered array and handle it with condition statement in api.js in route("/api/solve")
if (filteredRegionArray.length == 9) return filteredRegionArray;
else return "invalid regions";
}
checkPlacement(puzzleString, row, col, value) {
const replaceAt = (string, index, replacement) => {
return (
string.substring(0, index) + replacement + string.substring(index + 1)
);
};
let board = this.stringToBoard(puzzleString);
// set col and row to the array value thus col has to go back one for index starts at 1 and row we must convert letter to array index for column
col = col - 1;
if (row == "a" || row == "A") {
row = 0;
} else if (row == "b" || row == "B") {
row = 1;
} else if (row == "c" || row == "C") {
row = 2;
} else if (row == "d" || row == "D") {
row = 3;
} else if (row == "e" || row == "E") {
row = 4;
} else if (row == "f" || row == "F") {
row = 5;
} else if (row == "g" || row == "G") {
row = 6;
} else if (row == "h" || row == "H") {
row = 7;
} else if (row == "i" || row == "I") {
row = 8;
}
// logic that will handle everything
if (board[row][col] == value) {
return "input is same as value in coordinate";
} else if (board[row][col] !== "." && board[row][col] !== value) {
return "can't replace number";
} else if (board[row][col] == ".") {
// change the . to value inputted by user
board[row][col] = value;
// have new board be transferred to string so it can go through filter logic
let updatedString = this.boardToString(board);
let conflictArray = [];
let froArray = [];
let fcArray = [];
let freArray = [];
let index = 0;
// set index based off row and column to replace value in string so we can check the new value through the filter
if (row == 0) {
index = col;
} else {
index = row * 9 + col;
}
froArray = this.filterRow(replaceAt(updatedString, index, value));
fcArray = this.filterColumn(replaceAt(updatedString, index, value));
freArray = this.filterRegion(replaceAt(updatedString, index, value));
if (froArray == "invalid rows") {
conflictArray.push("row");
}
if (fcArray == "invalid columns") {
conflictArray.push("column");
}
if (freArray == "invalid regions") {
conflictArray.push("region");
}
if (conflictArray.length > 0) {
return { valid: false, conflict: conflictArray };
} else return { valid: true };
}
}
stringToBoard(puzzleString) {
// split string up into 9 rows using regex and match
let puzzleArrayInRows = puzzleString.match(/.{9}/g);
return puzzleArrayInRows.map((i) => i.split(""));
}
boardToString(board) {
return board.map((i) => i.join("")).reduce((a, b) => a + b);
}
isValid(board, row, col, k) {
for (let i = 0; i < 9; i++) {
const m = 3 * Math.floor(row / 3) + Math.floor(i / 3);
const n = 3 * Math.floor(col / 3) + (i % 3);
if (board[row][i] == k || board[i][col] == k || board[m][n] == k) {
return false;
}
}
return true;
}
sudokuSolver(data) {
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
if (data[i][j] == ".") {
for (let k = 1; k <= 9; k++) {
if (this.isValid(data, i, j, k)) {
data[i][j] = k;
if (this.sudokuSolver(data)) {
return true;
} else {
data[i][j] = ".";
}
}
}
return false;
}
}
}
return true;
}
}
module.exports = SudokuSolver;
<file_sep>/routes/api.js
"use strict";
const SudokuSolver = require("../controllers/sudoku-solver.js");
module.exports = (app) => {
let solver = new SudokuSolver();
let numberRegex = /\d/;
let coordinateRegex = /^[a-i][1-9]/i; // can't use \d because 0 is not a coordinate option
app.route("/api/check").post((req, res) => {
let puzzle = req.body.puzzle;
let coordinate = req.body.coordinate;
let value = req.body.value;
let validateResponse = solver.validate(req.body.puzzle);
let object = { puzzle: puzzle, coordinate: coordinate, value: value }; // need this to pass a test
// // If validateResponse has an error value then respond with res.json()
if (validateResponse !== "correct puzzle")
return res.json(validateResponse);
// If puzzle coordinate or value is not filled out
if (!puzzle || !coordinate || !value) {
return res.json({ error: "Required field(s) missing" });
}
// If the coordinate given is not valid
else if (!coordinateRegex.test(coordinate) || coordinate.length > 2) {
return res.json({ error: "Invalid coordinate" });
}
// If the value given is invalid
else if (!numberRegex.test(value)) {
return res.json({ error: "Invalid value" });
}
// If all things given are valid and
// CHECK ROW COLUMN AND REGION PLACEMENT TO SEE IF A VALUE CAN GO HERE
else {
let checkPlacement = solver.checkPlacement(
puzzle,
coordinate[0],
coordinate[1],
value
);
if (checkPlacement == "input is same as value in coordinate") {
return res.json({ valid: true });
} else if (checkPlacement == "can't replace number") {
return res.json(checkPlacement);
} else res.json(checkPlacement);
}
});
app.route("/api/solve").post((req, res) => {
let puzzle = req.body.puzzle;
if (!puzzle) return res.json({ error: "Required field missing" });
let validateResponse = solver.validate(puzzle);
// If validateResponse has an error value then respond with res.json()
if (validateResponse !== "correct puzzle") {
return res.json(validateResponse);
}
// Create arrays with all forms of sudoku needed.
let filteredRowArray = solver.filterRow(puzzle);
if (filteredRowArray == "invalid rows") {
return res.json({ error: "Puzzle cannot be solved" });
}
let filteredColumnArray = solver.filterColumn(puzzle);
if (filteredColumnArray == "invalid columns") {
return res.json({ error: "Puzzle cannot be solved" });
}
// Check region placement
let filteredRegionArray = solver.filterRegion(puzzle);
if (filteredRegionArray == "invalid regions") {
return res.json({ error: "Puzzle cannot be solved" });
}
// set up array board from puzzle string given
let board = solver.stringToBoard(puzzle);
// solve board. this changes board so solvedString uses a solved board
solver.sudokuSolver(board);
let solvedString = solver.boardToString(board);
if (solvedString.indexOf(".") == -1) {
return res.json({ solution: solvedString });
} else return res.json({ error: "Puzzle cannot be solved" });
});
};
| 4f1ca9c0bf02bc054fbe637e51bacd3a3647a03d | [
"JavaScript"
] | 3 | JavaScript | lace1010/Sudoku-Solver | 2927eb1619b7c05b30afcc6dd86a563544a35da3 | bd75716aa2ef155db42982a34b8d734d2a7e2edd |
refs/heads/master | <repo_name>sjtusonic/exe<file_sep>/tcl/tcl_call_cpp/4_swig_manual/example.cpp
/* PowObjCmd
*
* Tcl 8.x wrapper for the pow(x,y) function.
*/
#include <tcl.h>
#include <math.h>
int
PowObjCmd(ClientData clientData, Tcl_Interp *interp,
int objc, Tcl_Obj *CONST objv[])
{
Tcl_Obj *resultptr;
double x,y,result;
int error;
if (objc != 3) {
Tcl_WrongNumArgs(interp,2,objv,
"Usage : pow x y");
return TCL_ERROR;
}
error = Tcl_GetDoubleFromObj(interp, objv[1], &x);
if (error != TCL_OK) return error;
error = Tcl_GetDoubleFromObj(interp, objv[2], &y);
if (error != TCL_OK) return error;
result = pow(x,y);
resultptr = Tcl_GetObjResult(interp);
Tcl_SetDoubleObj(resultptr,result);
return TCL_OK;
}
//To make this new command available to Tcl, you also need to write an initialization function such as follows:
int
Example_Init(Tcl_Interp *interp) {
Tcl_CreateObjCommand(interp, "pow", PowObjCmd,
(ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
return TCL_OK;
}
<file_sep>/cpp/5_BOOK_CPP_PRIMER/src/main.cpp
#include "include.top.h"
using namespace std;
int main() {
cout<<"Hello world!"<<endl;
//exe_3_2();
//exe_3_16();
f_3_22();
PRINT_DEBUG_INFO();
return 0;
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph/GraphMat.h
#include "GraphBase.h"
class GraphMat:public GraphBase {
int V();
int E();
void addEdge(int v,int w);
vector<int> adj(int v);
}
<file_sep>/cpp/5_BOOK_CPP_PRIMER/Makefile
DIR_INC = ./include
DIR_SRC = ./src
DIR_OBJ = ./obj
DIR_BIN = ./bin
SRC = $(wildcard ${DIR_SRC}/*.cpp)
OBJ = $(patsubst %.cpp,${DIR_OBJ}/%.o,$(notdir ${SRC}))
TARGET = main
BIN_TARGET = ${DIR_BIN}/${TARGET}
CC = g++
#CC = g++ -E
CFLAGS = -v -g -Wall -I${DIR_INC}
#CFLAGS = -v -g -I${DIR_INC}
${BIN_TARGET}:${OBJ}
make ctags
$(CC) $(OBJ) -o $@
#-$(CC) $(OBJ) -o $@ 2> link.log
#-cat link.log
@echo "=========================================================================================="
${DIR_OBJ}/%.o:${DIR_SRC}/%.cpp
$(CC) $(CFLAGS) -c $< -o $@
#$(CC) $(CFLAGS) -c $< -o $@ 2> compile.log
#cat compile.log
@echo "=========================================================================================="
.PHONY:clean run
clean:
#find ${DIR_OBJ} -name *.o -exec rm -rf {}
rm ${DIR_OBJ}/*.o
rm ${DIR_BIN}/*.exe
run:
${BIN_TARGET}
debug:
gdb -f ${BIN_TARGET}
ctags:
ctags -R --sort=yes --c++-kinds=+px --fields=+iaS --extra=+q
ctags_system:
ctags -R --sort=yes -I __THROW –file-scope=yes –langmap=c:+.h –languages=c,c++ –links=yes –c-kinds=+p --fields=+S -R -f ~/.vim/systags /usr/include /usr/local/include
check:
#valgrind --tool=memcheck --show-reachable=yes --leak-check=yes bin/main 2> valgrind.log 1> valgrind.log
valgrind --tool=memcheck --show-reachable=yes --leak-check=yes bin/main
#cat valgrind.log
@echo "=========================================================================================="
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/4.1.h
int main4_1 () ;
<file_sep>/python/workspace_python/dive_into_python/src/1/scan_chain_research/scan_chain.py~
#!/usr/bin/env python
# http://www.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/tsp/
'''
this is a simulator of scan chain reorder
'''
# MODULE IMPORTS:
import matplotlib.pyplot as plt
import random
import re
import os
import time
import copy
# GLOBAL VAR:
W=1000
H=1000
LENGTH=52
GEN_PLOT=1
'''
set DUMP_FILE to 1 to re-gen cfg file by random, when you change 'LENGTH', cfg file should re-gen
'''
DUMP_FILE=0
# PROC:
def calc_dist_hamiton(x1,y1,x2,y2,domain1=999,domain2=999):
derate_value=0.2
v=abs(x1-x2)+abs(y1-y2)
PUNISH=v*derate_value*1.5*100 # length of clock net w/o crpr may be 1.5 of data path distance
if domain1==domain2:
return v
else:
return v+PUNISH
def calc_dist_hamiton_exp(x1,y1,x2,y2,domain1=999,domain2=999):
derate_value=0.2
v_linear=abs(x1-x2)+abs(y1-y2)
if v_linear<10:
v=v_linear
elif v_linear <100:
v=v_linear*10
elif v_linear <1000:
v=v_linear*100
else :
v=v_linear*1000
PUNISH=v*derate_value*1.5*100 # length of clock net w/o crpr may be 1.5 of data path distance
if domain1==domain2:
return v
else:
return v+PUNISH
def calc_dist(x1,y1,x2,y2):
return ((x1-x2)**2 + (y1-y2)**2)**0.5
#print calc_dist(3,4,5,6)
def find_nearest(node_name,left,mode=0):
# MODE=0:linear; MODE=1:exp
debug=0
if debug: print '---------------------------------------------'
if debug: print 'calling find_nearest: %d'%(node_name)
if debug: print left
smallest_dist=9999999
ans_name=-1
for i in left:
if i==-1:
continue
if mode==0:
dist=calc_dist_hamiton(rx[node_name],ry[node_name],rx[i],ry[i],r_cg_domain[node_name],r_cg_domain[i])
dist_pure=calc_dist_hamiton(rx[node_name],ry[node_name],rx[i],ry[i])
else:
dist=calc_dist_hamiton_exp(rx[node_name],ry[node_name],rx[i],ry[i],r_cg_domain[node_name],r_cg_domain[i])
dist_pure=calc_dist_hamiton_exp(rx[node_name],ry[node_name],rx[i],ry[i])
if debug: print '%d is %d (%d)'%(i, dist,dist_pure)
if dist<smallest_dist:
if i!=node_name:
smallest_dist=dist
ans_name=i
if debug: print '=smallest is node %d: %d'%(ans_name, smallest_dist)
if debug: print '---------------------------------------------'
return ans_name,smallest_dist
def calc_total_dist (ans_list,rname,rx,ry,r_cg_domain,mode=0):
'''
calc total cost of NET LENGTH of a config 'ans_list'
'''
debug=0
if debug: print 'Info: proc calc_total_dist'
total_dist=0
for i in range(len(ans_list)):
if i==len(ans_list)-1:
break
last=ans_list[i]
curr=ans_list[i+1]
if mode==0:
dist=calc_dist_hamiton(rx[curr],ry[curr],rx[last],ry[last],r_cg_domain[curr],r_cg_domain[last])
dist_pure=calc_dist_hamiton(rx[curr],ry[curr],rx[last],ry[last])
else:
dist=calc_dist_hamiton_exp(rx[curr],ry[curr],rx[last],ry[last],r_cg_domain[curr],r_cg_domain[last])
dist_pure=calc_dist_hamiton_exp(rx[curr],ry[curr],rx[last],ry[last])
if debug: print 'reg: %d (%d, %d) \tlast is (%d,%d), \tdist: %d (%d)' %(curr,rx[curr],ry[curr],rx[last],ry[last],dist,dist_pure)
#print 'from %d to %d, incr %d, dist %d'%(last,curr,dist,0)
total_dist=total_dist+dist
if debug: print 'TOTAL DIST of'
if debug: print ans_list
if debug: print 'IS: %d'%(total_dist)
return total_dist
def swap (ll,i,j):
llout=range(LENGTH)
for iter in range(LENGTH):
llout[iter]=0
for iter in range(LENGTH):
llout[iter]=ll[iter]
temp=llout[i]
llout[i]=llout[j]
llout[j]=temp
return llout
def dump_file(scan_def='scan.def',cfg_file='scan.cfg.txt'):
print 'Info: dump file: %s %s'%(scan_def, cfg_file)
out_file=open(scan_def,'w')
cfg_file=open(cfg_file,'w')
out_file.write('name\t\tX\tY\trcg\n')
for i in range(LENGTH):
out_file.write('reg'+str(rname[i]))
out_file.write(': \t(')
out_file.write(str(rx[rname[i]]))
out_file.write(', \t')
out_file.write(str(ry[rname[i]]))
out_file.write(') \t')
out_file.write(str(r_cg_domain[rname[i]]))
out_file.write('\n')
#print 'reg: %s is located in %s, %s' %(rname[i], rx[i], ry[i])
cfg_file.write(str(rname[i]))
cfg_file.write('\t')
cfg_file.write(str(rx[rname[i]]))
cfg_file.write('\t')
cfg_file.write(str(ry[rname[i]]))
cfg_file.write('\t')
cfg_file.write(str(r_cg_domain[rname[i]]))
cfg_file.write('\n')
out_file.close()
cfg_file.close()
def read_cfg_file(cfg_file='scan.cfg.txt'):
cfg_file=open(cfg_file,'r')
print 'Info: read in %s'%(cfg_file)
i=0
for line in cfg_file:
words=line.split()
rname[i]=int(words[0])
rx[rname[i]]=int(words[1])
ry[rname[i]]=int(words[2])
r_cg_domain[rname[i]]=int(words[3])
print 'GET rname: %d rx %d ry %d rcg %d'%(rname[i],rx[rname[i]],ry[rname[i]],r_cg_domain[rname[i]])
i+=1
cfg_file.close()
def gen_c (ll,ptr=0,force_start=-1):
print 'Info: calling gen_c with ptr: '+str(ptr)
global best_dist
global best_ll_yet
if len(ll)>7:
print "Warning: length of ll is too large, full_mode is turned off."
full_iter_mode=0
else:
full_iter_mode=1
if force_start!=-1:
ll[0],ll[force_start]=ll[force_start],ll[0]
#print ll
if ptr==len(ll):
print '---------------'+str(ll)
########################
#
#calc_distance
total_dist=calc_total_dist (ll,rname,rx,ry,r_cg_domain)
if total_dist<best_dist:
best_dist=total_dist
best_ll_yet=copy.deepcopy(ll)
print 'total dist: %d'%(total_dist)
########################
return ll
for i in range(ptr,len(ll)):
ll[ptr],ll[i]=ll[i],ll[ptr]
#ll[1:]=copy.deepcopy(gen_c(ll[1:]))
if full_iter_mode==1:
step=1
else:
#step=len(ll)/3
return ll
gen_c(ll,ptr+step)
ll[ptr],ll[i]=ll[i],ll[ptr]
return ll
def plot_a_cfg(ans,plot_code='141',clr_str='bs-',label_v='ans',title_v='solve by algor: NA'):
global rx
global ry
print 'ans: '+str(ans)
ans_x=[]
ans_y=[]
for i in ans:
ans_x.append(rx[i])
ans_y.append(ry[i])
plt.subplot(plot_code)
plt.axis([0,W,0,H],aspect='equal')
#plt.legend()
'''
print 'x: '+str(ans_x)
print 'y: '+str(ans_y)
'''
plt.plot(ans_x,ans_y,clr_str,label=label_v)
xp=range(0,LENGTH)
yp=range(0,LENGTH)
SHOW_NUM_ANNOTATE=1
if SHOW_NUM_ANNOTATE==1:
for i in range(len(ans_x)):
if i%5==0:
ss='%s(%s)'%(str(i),str(ans[i]))
plt.annotate(ss,xy=(ans_x[i],ans_y[i]))
for i in range(len(ans_x)-1):
xp[i]=ans_x[i+1]-ans_x[i]
yp[i]=ans_y[i+1]-ans_y[i]
#print "xp:"+str(xp)
SHOW_ARROW=1
if SHOW_ARROW: plt.quiver(ans_x[:-1], ans_y[:-1],xp[:-1], yp[:-1],pivot='tail',minlength=1,minshaft=10,width=0.001)
plt.title(title_v)
def ratio(num,ll):
rat_str='%.2f%%'%(100*float(num)/total_dist0)
return " rat:"+str(rat_str)+"\nstr: "+str(ll)
def get_smallest(list):
small=999999
for i in list:
if i<small:
small=i
return small
def get_largest(list):
large=-999999
for i in list:
if i>large:
large=i
return large
'''
STRUCTURE DEFINITION:
#
line=[p1,p2]
p1=[x1,y1]
p2=[x2,y2]
#
box=[llx,lly,urx,ury]
#
rect=[p1,p2,p3,p4]
p1=[x1,y1]
......
'''
def gen_box(line1):
p1,p2=line1
x1,y1=p1
x2,y2=p2
llx=get_smallest([x1,x2])
lly=get_smallest([y1,y2])
urx=get_largest([x1,x2])
ury=get_largest([y1,y2])
return [llx,lly,urx,ury]
def point_is_in_box(p,b):
x,y=p
llx,lly,urx,ury=b
if x>=llx and x<=urx:
if y>=lly and y<=ury:
return True
return False
def points_exclude_wrong(line1,line2):
l1p1,l1p2=line1
l2p1,l2p2=line2
b1=gen_box(line1)
b2=gen_box(line2)
if not point_is_in_box(l1p1,b2):
if not point_is_in_box(l1p2,b2):
if not point_is_in_box(l2p1,b1):
if not point_is_in_box(l2p2,b1):
return True
return False
def points_exclude(line1,line2):
l1p1,l1p2=line1
l2p1,l2p2=line2
l1p1x,l1p1y=l1p1
l1p2x,l1p2y=l1p2
l2p1x,l2p1y=l2p1
l2p2x,l2p2y=l2p2
if max(l1p1x,l1p2x)<min(l2p1x,l2p2x):return True
if max(l1p1y,l1p2y)<min(l2p1y,l2p2y):return True
if max(l2p1x,l2p2x)<min(l1p1x,l1p2x):return True
if max(l2p1y,l2p2y)<min(l1p1y,l1p2y):return True
return False
def v_add(v1,v2):
x1,y1=v1
x2,y2=v2
return [x1+x2,y1+y2]
def v_sub (v1,v2):
return v_add(v1,v_minus(v2))
def v_minus(v1):
x1,y1=v1
return [-x1,-y1]
def inner_product(v1,v2):
x1,y1=v1
x2,y2=v2
return x1*x2+y1*y2
def outer_product_algebra(v1,v2):
x1,y1=v1
x2,y2=v2
return x1*y2-x2*y1
def vector_cross(line1,line2): # 'KuaLi' in Chinese
'''
l2p1------------------->l1p2
| |
| |
| |
l1p1------------------->l2p2
'''
l1p1,l1p2=line1
l2p1,l2p2=line2
vL=v_sub(l2p1,l1p1) # Left
vB=v_sub(l2p2,l1p1) # Bottom
vT=v_sub(l1p2,l2p1) # Top
vLine1=v_sub(l1p2,l1p1)
vLine2=v_sub(l2p2,l2p1)
if outer_product_algebra(vL,vLine1) * outer_product_algebra(vB,vLine1) <0:
if outer_product_algebra(v_minus(vL),vLine2) * outer_product_algebra(vT,vLine2) <0:
return True
return False
def cross(line1,line2):
if not points_exclude(line1,line2):
if vector_cross(line1,line2):
return True
return False
def reg_pair2line(r1,r2):
x1=rx[r1]
y1=ry[r1]
x2=rx[r2]
y2=ry[r2]
return [[x1,y1],[x2,y2]]
def reverse(series,from_ind,to_ind):
print 'Info: calling reverse to swap ind: %d and %d'%(from_ind,to_ind)
#print '%d(%d)->%d(%d),%d(%d)->%d(%d)'%(from_ind-1,series[from_ind-1],from_ind,series[from_ind],\
# to_ind,series[to_ind],to_ind+1,series[to_ind+1])
t=from_ind-1
print '%d(%d)[%d,%d]'%(t,series[t],rx[series[t]],ry[series[t]]),
print '->',
t=from_ind
print '%d(%d)[%d,%d]'%(t,series[t],rx[series[t]],ry[series[t]]),
print '|',
t=to_ind
print '%d(%d)[%d,%d]'%(t,series[t],rx[series[t]],ry[series[t]]),
print '->',
t=to_ind+1
print '%d(%d)[%d,%d]'%(t,series[t],rx[series[t]],ry[series[t]])
u=series[from_ind:to_ind+1]
u.reverse()
series[from_ind:to_ind+1]=u
t=from_ind-1
print '%d(%d)[%d,%d]'%(t,series[t],rx[series[t]],ry[series[t]]),
print '->',
t=from_ind
print '%d(%d)[%d,%d]'%(t,series[t],rx[series[t]],ry[series[t]]),
print '|',
t=to_ind
print '%d(%d)[%d,%d]'%(t,series[t],rx[series[t]],ry[series[t]]),
print '->',
t=to_ind+1
print '%d(%d)[%d,%d]'%(t,series[t],rx[series[t]],ry[series[t]])
return series
#===============================================================================
# # INPUT:
#===============================================================================
#series=[9,8,7,6,5,4,3,2,1,0]
series=range(LENGTH)
start_point=series[0]
# choose Lower-left reg as start point:
rname=range(LENGTH)
rx=range(LENGTH)
ry=range(LENGTH)
#===============================================================================
# # INIT:
#===============================================================================
away_from_zero=W+H
last_away_from_zero=W+H
for i in range(LENGTH):
x=random.randint(0,W)
y=random.randint(0,H)
rname[i]=i
rx[rname[i]]=x
ry[rname[i]]=y
#print 'reg: %s is located in %s, %s' %(rname[i], rx[i], ry[i])
#===============================================================================
# # RCG CONFIG:
#===============================================================================
r_cg_domain=range(LENGTH)
USE_SAME_CG=1
if USE_SAME_CG==1:
for i in range(LENGTH): r_cg_domain[i]=1
r_cg_domain[1]=1
else:
for i in range(LENGTH):
if rx[rname[i]]<400 and ry[rname[i]]<400:
r_cg_domain[rname[i]]=2
else:
r_cg_domain[i]=1
#===============================================================================
# # DUMP TO FILE:
#===============================================================================
if DUMP_FILE:
dump_file()
#===============================================================================
# # READ IN CFG FILE:
#===============================================================================
read_cfg_file()
#===============================================================================
# # START POINT:
#===============================================================================
for i in range(LENGTH):
away_from_zero=rx[rname[i]]+ry[rname[i]]
if away_from_zero<last_away_from_zero:
start_point=i
last_away_from_zero=away_from_zero
print 'Start point is %d, at %d, %d'%(start_point,rx[start_point],ry[start_point])
#===============================================================================
# # MAIN:
#===============================================================================
total_dist=calc_total_dist (series,rname,rx,ry,r_cg_domain,mode=0)
print 'total dist is %d'%(total_dist)
print 'average dist: %d'%(total_dist/LENGTH)
total_dist0=total_dist
#(ans,dist)=find_nearest(0,left)
#===============================================================================
# # exhaustion
#===============================================================================
print "Info: Start step0"
best_ll_yet=range(LENGTH)
best_dist=(H+W)*LENGTH*10
gen_c(range(LENGTH),1,start_point)
print 'the best solution(dist=%d) is:'%(best_dist)
print best_ll_yet
#===============================================================================
# # nearest
#===============================================================================
print "Info: Start step1"
ans_list=[]
left=copy.deepcopy(rname)
curr_node=start_point
ans_total_dist=0
while left.count(-1)<len(left):
ans_list.append(curr_node)
#print len(ans_list)
ans,dist=find_nearest(curr_node,left)
if ans==-1:
break
left[left.index(curr_node)]=-1
ans_total_dist=ans_total_dist+dist
if 1: print 'from %d to %d, incr %d,total dist %d'%(curr_node,ans,dist,ans_total_dist)
curr_node=ans
print 'answer list:'
print ans_list
print 'total dist: %d'%(ans_total_dist)
print 'average dist: %d'%(ans_total_dist/LENGTH)
print calc_total_dist (ans_list,rname,rx,ry,r_cg_domain)
total_dist_nearest=ans_total_dist
#===============================================================================
# # INCR OPT:
#===============================================================================
print "Info: Start random opt"
out_file=open('random_reorder.record.txt','w')
out_file.write('random_reorder.record\n')
ans_list2=range(LENGTH)
for iter in range(LENGTH):
ans_list2[iter]=ans_list[iter]
#for i in range(LENGTH*100):
STEP_U=10
STEP_V=10
if LENGTH>100:
STEP_U=LENGTH/100
STEP_V=LENGTH/100
START_REG_IN_RANDOM_REORDER=1 #because reg0 is the start reg, dont reorder
for u in range(START_REG_IN_RANDOM_REORDER,LENGTH,STEP_U):
break # DISABLE THE INCR OPT STEP
#print '%d, %d,'%(u,0)
print u,
for v in range(START_REG_IN_RANDOM_REORDER,u,STEP_V):
#u=random.randint(0,LENGTH-1)
#v=random.randint(0,LENGTH-1)
ll=swap(ans_list2,u,v)
out_str='try to swap:%d(%d,%d), %d(%d,%d) \n'%(u,rx[u],ry[u],v,rx[v],ry[v])
out_file.write(out_str)
dist_low_bound=calc_total_dist (ans_list2,rname,rx,ry,r_cg_domain)
new_dist=calc_total_dist (ll ,rname,rx,ry,r_cg_domain)
if dist_low_bound>new_dist:
#swap
#print '\nSWAP in iter:%d, %d'%(u,v)
out_str='SWAP in iter:%d, %d\n'%(u,v)
out_file.write(out_str)
for iter in range(LENGTH):
ans_list2[iter]=ll[iter]
pass
print 'answer list2:'
print ans_list2
dist=calc_total_dist(ans_list2,rname,rx,ry,r_cg_domain)
print 'total dist2: %d'%(dist)
print 'average dist: %d'%(dist/LENGTH)
total_dist_random=dist
out_file.close()
'''
l1p1=[0,0]
l1p2=[1,1]
l2p1=[0,1]
l2p2=[1,0]
l1=[l1p1,l1p2]
l2=[l2p1,l2p2]
print 'exclude:'
print points_exclude(l1,l2)
print 'v_cross:'
print vector_cross(l1,l2)
print 'cross:'
print cross(l1,l2)
'''
print 'Info: begin of check cross----------------'
t=copy.deepcopy(ans_list2)
t2=copy.deepcopy(t)
dist=calc_total_dist(t2,rname,rx,ry,r_cg_domain)
dist_low_bound=dist
cross_flag=1
cntr=0
while (cross_flag and cntr<30):
#t=copy.deepcopy(t2) # refresh t
cross_flag=0
cntr+=1
print '========this is iter:'+str(cntr)
for i in range(len(t2)-1):
for j in range(i+1,len(t2)-1):
l1=reg_pair2line(t2[i],t2[i+1])
l2=reg_pair2line(t2[j],t2[j+1])
if cross(l1,l2):
print 'cross: 4regs [ind:%d,%d] (%d,%d)-(%d,%d)'%(i,j,t2[i],t2[i+1],t2[j],t2[j+1])
#cross_reg=[t2[i],t2[i+1],t2[j],t2[j+1]]
rn=t2[i]; print rn,rx[rn],ry[rn]
rn=t2[i+1]; print rn,rx[rn],ry[rn]
rn=t2[j]; print rn,rx[rn],ry[rn]
rn=t2[j+1]; print rn,rx[rn],ry[rn]
reverse(t2,i+1,j)
dist=calc_total_dist(t2,rname,rx,ry,r_cg_domain)
if dist>dist_low_bound:
print 'de-cross fail: %d > %d'%(dist,dist_low_bound)
reverse(t2,i+1,j)
else:
cross_flag=1
print 'de-cross succ: %d < %d'%(dist,dist_low_bound)
dist_low_bound=dist
print 'Info: iteration finished when cntr='+str(cntr)
total_dist_decross= calc_total_dist(t2,rname,rx,ry,r_cg_domain)
print 'Info: end of check cross-----------------'
#===============================================================================
# # AC algor:
#===============================================================================
ac_series=copy.deepcopy(series)
#===============================================================================
# # PLOT:
#===============================================================================
if GEN_PLOT:
#plot_a_cfg(series,'141','gx-',title_v='base order in scandef\n'+str(total_dist0)+ratio(total_dist0,series))
plot_a_cfg(ans_list,'142','rx-',title_v='nearest algthm\n'+str(total_dist_nearest)+ratio(total_dist_nearest,ans_list))
#plot_a_cfg(ans_list2,'143','bx-',title_v='random incr opt\n'+str(total_dist_random)+ratio(total_dist_random,ans_list2))
if LENGTH<=7:
plot_a_cfg(best_ll_yet,'144','cx-',title_v='enhaus\n'+str(best_dist)+ratio(best_dist,best_ll_yet))
else:
plot_a_cfg(t2,'144','cx-',title_v='decross\n'+str(total_dist_decross)+ratio(total_dist_decross,t2))
'''
plot_a_cfg(t2,'111','cx-',title_v='decross\n'+str(total_dist_decross)+ratio(total_dist_decross,t2))
'''
#plt.quiver()
plt.show()
'''
print t2[37],t2[38],t2[39],t2[40]
u=t2[37];print rx[u],ry[u]
u=t2[38];print rx[u],ry[u]
u=t2[39];print rx[u],ry[u]
u=t2[40];print rx[u],ry[u]
'''
'''
u=t2[50];print rx[u],ry[u]
u=t2[29];print rx[u],ry[u]
u=t2[32];print rx[u],ry[u]
u=t2[28];print rx[u],ry[u]
'''
'''
24 6 13 132
242 657
855 658
539 736
460 631
'''
'''
#i=37;j=39
l1=reg_pair2line(50,29)
l2=reg_pair2line(32,28)
print points_exclude(l1,l2)
print vector_cross(l1,l2)
print cross(l1,l2)
'''
<file_sep>/cpp/game/three_pig/shape.h
#ifndef SHAPE_H_
#define SHAPE_H_
#include "character.h"
class ShapeBase
{
public:
// MEMBER:
vector<vector<string>> board;
//int W;
//int H;
//METHOD:
ShapeBase() {
DENTER;
//vector<vector<int>> tboard={
// {0,1,1,0},
// {1,1,1,1},
// {1,1,1,1},
// {0,1,1,1},
//};
DRETURN;
};
void show() {
DEBUG_MARK;
DENTER;
DPRINT("-------------------------------");
for(auto v1:board)
{
for(auto i:v1)
{
DEBUG_MARK;
cout<<""<<i<<"\t";
}
cout<<""<<""<<endl;
}
DPRINT("-------------------------------");
DRETURN;
}
};
class Shape:public ShapeBase
{
public:
// MEMBER:
vector<Point> pList;
string name;
//METHOD:
Shape()
{
pList.push_back(Point(0,0));
pList.push_back(Point(1,0));
pList.push_back(Point(2,0));
//board={
// {"1"},
// {"1"},
// {"1"},
//};
};
Shape(vector<Point> s)
{
pList=s;
};
void transform()
{
for(Point& p:pList )
{
p.transform();
}
};
void mirrorX()
{
for(Point& p:pList )
{
p.mirrorX();
}
};
void r90()
{
transform();
mirrorX();
};
Point loc;
void setLoc(Point p) { loc=p; }
void setLoc(int x,int y) {
loc.x=x;
loc.y=y;
}
void moveTo00() { };
void turn() { };
bool apply(vector<vector<string>>& targetBoard,vector<vector<string>>& boardRef)
{
// zjc here
for(auto thisP:pList)
{
int offsetX=loc.x+thisP.x;
int offsetY=loc.y+thisP.y;
//DLOG(offsetX);
//DLOG(offsetY);
if(offsetX>=(int)targetBoard.size())
return 0;
if(offsetY>=(int)targetBoard[0].size())
return 0;
//DLOG(targetBoard.size());
//DLOG(targetBoard[0].size());
if(regex_match(boardRef[offsetX][offsetY],regex("^0.*")))
{
DPRINT("CONFLICT with ^0.* !!!");
return 0;
}
targetBoard[offsetX][offsetY]+=name;
//DPRINT("APPLY targetBoard["<<offsetX<<"]["<<offsetY<<"]="<<targetBoard[offsetX][offsetY]);
//DLOG(targetBoard[offsetX][offsetY]);
//DLOG(regex_match(targetBoard[offsetX][offsetY],regex("^0.*")));
}
return 1;
};
void print() {
cout<<"Shape:"<<this<<""<<endl;
cout<<"Loc:"<<loc.x<<","<<loc.y<<endl;
cout<<"pList:"<<""<<endl;
for(auto p:pList)
{
cout<<""<<p.x<<","<<p.y<<endl;
}
}
bool operator% (const Shape& rhs) const // Shape hit Shape
{
for(auto p1:pList )
for(auto p2:rhs.pList)
{
if(p1==p2)
return true;
}
return false;
}
bool operator% (Character & rhs) // Shape hit Character
{
auto p2=rhs.getLoc();
for(auto p1:pList )
{
if(p1==p2)
return true;
}
return false;
}
};
#endif
<file_sep>/cpp/exe_game/tetris/s.cpp
//--------------------------------------
// include lib files
//--------------------------------------
//#include <curses.h>
#include "global.h"
#include "Display.class.h"
#include "Control.class.h"
//#include "TetrisCalc.class.h"
#include "Matrix.class.h"
#include "unit_test.h"
using namespace std;
//--------------------------------------
// include local files
//--------------------------------------
//#include "include/f13_2.h"
//#include "lib.h"
//#include "include.top.h"
//#include "gnuplot_i.h"
//--------------------------------------
#ifdef UNIT_TEST
int main()
{
cout<<"UNIT_TEST MODE"<<""<<endl;
//test_Control();
PRINT_DEBUG_INFO();
//test_Matrix();
//test_flow();
test_flow_tick();
//test_time_engine();
//test_Point();
//test_deleteFromVector();
return 0;
}
#else
int main()
{
int WIDTH=20;
int HEIGHT=30;
//
Display* d=new Display();
d->showTitle();
//
Matrix* m=new Matrix(HEIGHT,WIDTH,"X");
d->show();
//
return 0;
}
#endif
<file_sep>/cpp/POJ_separated/1018/poj1001.cpp
#include "include.top.h"
#include <math.h>
#include <iomanip>
using namespace std;
#include <fstream>
void poj1001 ()
{
cout<<"-----------------------------------------------"<<endl;
cout<<"poj1001"<<endl;
//----------------------------------------------------------
string filename="input/poj1001.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj1001.out";
std::ofstream outfile(filename_out);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
double a, b;
double result;
while (infile >> a >> b)
{
result=pow(a,b);
outfile<<a<<"\t^\t"<<b<<"\t=\t"<<setprecision(3000)<<result<<setprecision(10)<<endl;
}
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch2/shellSorting/s.cpp
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <regex>
#include <map>
#include <assert.h>
#include "../../include/include.h"
using namespace std;
//=========================================================================================
int cntCompare=0;
class ShellSorting {
public:
template <class T>
T less(T& a,T& b) {
cntCompare++;
//DPRINT("less:"<<a<<","<<b);
auto r= a<b?1:0;
//DLOG(r);
return r;
}
template <class T>
void exch(T&a,T&b)
{
//DPRINT("exch:"<<a<<","<<b);
T tmp=a;
a=b;
b=tmp;
}
double getRandData(int min,int max,unsigned seed)
{
//unsigned seed=(unsigned)time(NULL)*1000;
srand(seed);
double m1=(double)(rand()%101)/101; // 计算 0,1之间的随机小数,得到的值域近似为(0,1)
min++; //将 区间变为(min+1,max),
double m2=(double)((rand()%(max-min+1))+min); //计算 min+1,max 之间的随机整数,得到的值域为[min+1,max]
m2=m2-1; //令值域为[min,max-1]
return m1+m2; //返回值域为(min,max),为所求随机浮点数
}
vector<double> genRandom(int n)
{
vector<double> r;
while(n>0)
{
unsigned seed=(unsigned)time(NULL)*1000+n;
r.push_back(getRandData(0,100,seed));
n--;
}
return r;
}
template <class T>
int count(vector<T> a, int n)
{
int r=0;
for(auto i:a)
{
if(i==n)
r++;
}
return r;
}
template <class T>
bool check (vector<T> a,vector<T> b)
{
for(T i:a)
{
int c1=count(a,i);
int c2=count(b,i);
if(c1!=c2)
{
DPRINT("check fail:"
<<"i:"<<i
<<",c1:"<<c1
<<",c2:"<<c2
);
return false;
}
}
return true;
}
template <class T>
void sort(vector<T>& a)
{
//DLOG(a);
int h=0;
int N=a.size();
while(h<=N/3)
h=h*3+1;
while(h>=1)
{
for(int i=h;i<N;i+=1)
{
for(int j=i;j>=h && less(a[j],a[j-h]);j-=h)
{
//DPRINT("i:"<<i<<",j:"<<j<<",h:"<<h);
exch(a[j-h],a[j]);
//DLOG(a);
}
}
int len=N/h;
DLOG(len);
DLOG(cntCompare );
DLOG(cntCompare/len);
cntCompare=0;
DLOG(h);
h/=3;
}
//DLOG(a);
return;
}
};
#if LNX
int main()
{
clock_t start, end;
start = clock();
////////////////////////////////////////////////
ShellSorting sol;
//vector<int> height={2,0,3,0,7,11,22,33,44444,55,66,77,1,2,0,3,0,7,1,5,8,2};
int SIZE=20000;
vector<double> dvec=sol.genRandom(SIZE);
auto bk=dvec;
//height={2,0,3};
//auto ans=sol.combinationSum(height,6);
DLOG(dvec);
sol.sort(dvec);
DLOG(dvec);
DLOG(sol.check(dvec,bk));
DLOG(cntCompare );
DLOG((double)cntCompare/SIZE);
//DLOG(cntSort);
//DLOG(cntPushPop);
////////////////////////////////////////////////
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
}
#endif
#if 0
#endif
<file_sep>/cpp/POJ/include/poj3295.h
#ifndef POJ3295_H
#define POJ3295_H
#include "include.top.h"
//#include "gnuplot_i.h"
//#include "gnuplot_i.new.hpp"
#define L_and "K"
#define L_or "A"
#define L_not "N"
#define L_imply "C"
#define L_equal "E"
//static vector<char> legalChars={
//'K',
//'A',
//'N',
//'C',
//'E',
//'p',
//'q',
//'r',
//'s',
//'t'};
void poj3295();
#endif
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/Graph.h
#ifndef GRAPH_H_
#define GRAPH_H_
#include "GraphBase.h"
#include <set>
typedef vector<int> PATHTYPE;
class Graph:public GraphBase {
/////////////////////////////////
// P333 Table 4.1.1 Graph API
/////////////////////////////////
public:
Graph(int ve);
Graph(string fname);
int V();
int E();
void addEdge(int v,int w);
vector<int> adj(int v);
private:
int mV;
int mE;
vector<vector<int>> mAdj;
/////////////////////////////////
// P342 Table 4.1.5 Paths
/////////////////////////////////
public:
vector<PATHTYPE> paths(int s);// all paths from node s
bool has_path_to(int from,int through,int to);// path exists from through to
PATHTYPE get_one_path_to(int from,int through,int to);
vector<PATHTYPE> get_all_path(int from,int through, int to);// like report_timing
void report_path(int s,int v);// like report_timing
/////////////////////////////////
// P349 Table 4.1.6 CC (connected component)
/////////////////////////////////
public:
void CC(); // pre constr
int CC_getCount(); // # of CC
int CC_getId(int v); // id of CC of node v
private:
vector<bool> CC_marked;
vector<int> CC_id;
int CC_count;
/////////////////////////////////
/////////////////////////////////
/////////////////////////////////
};
#if 1
void testGraph();
#endif
#endif
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/4.9.cpp
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <iomanip>
#include "4.9.h"
#include "lib.h"
using namespace std;
int f4_9 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
cout<<"------------------------"<<endl;
for (int i=1;i<=9;i++) {
for (int j=1;j<=9;j++) {
cout<<setw(4)<<i*j;
//cout<<i*j;
}
cout<<endl;
}
cout<<"------------------------"<<endl;
for (int i=1;i<=9;i++) {
for (int j=1;j<=9;j++) {
if (i>=j) {
cout<<setw(4)<<i*j;
}
//cout<<i*j;
}
cout<<endl;
}
cout<<"------------------------"<<endl;
for (int i=1;i<=9;i++) {
for (int j=1;j<=9;j++) {
if (i<=j) {
cout<<setw(4)<<i*j;
} else {
cout<<setw(4)<<"";
}
//cout<<i*j;
}
cout<<endl;
}
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/cpp/POJ/include/poj1753.h
#include "include.top.h"
class Board
{
public:
Board() ;
Board(string ) ;
//Board(vector<vector<bool>> );
//-----------------------------------------------------------
void show();
void random(int);
virtual void flip(int,int);
const vector<vector<bool>>& getBoard() const {return board;};
void setBoard(int row,int col,bool v)
{
board[row][col]=v;
};
int getWidth() const {return board.size();};
int getHeight() const {return board[1].size();};
bool isAllBlack()
{
for(int row=0;row<getHeight();row++)
{
for(int col=0;col<getWidth();col++)
{
if (board[row][col]!=0)
return false;
}
}
return true;
};
bool isAllWhite()
{
for(int row=0;row<getHeight();row++)
{
for(int col=0;col<getWidth();col++)
{
if (board[row][col]!=1)
return false;
}
}
return true;
};
bool isPure() {return (isAllBlack() || isAllWhite());};
int transformIsCombined(vector<Board> basicTransforms) {
int ind=0;
for(auto b:basicTransforms)
{
if((*this)%b)
{
cout<<"======================"<<endl;
cout<<"transformIsCombined:"<<endl;
this->show();
b.show();
cout<<"======================"<<endl;
return ind;
}
ind++;
}
return -1;
};
virtual void showTransformationSteps (bool mode_from_1=0, string out_fname="") {
if (out_fname!="")
{
std::ofstream outChannel(out_fname,ios::app);
for(int row=0;row<getHeight();row++)
{
for(int col=0;col<getWidth();col++)
{
if (board[row][col])
if (mode_from_1)
outChannel<<""<<row+1<<" "<<col+1<<""<<endl;
else
outChannel<<""<<row<<" "<<col<<""<<endl;
}
}
//outChannel.close();
}
else
{
for(int row=0;row<getHeight();row++)
{
for(int col=0;col<getWidth();col++)
{
if (board[row][col])
if (mode_from_1)
cout<<""<<row+1<<" "<<col+1<<""<<endl;
else
cout<<""<<row<<" "<<col<<""<<endl;
}
}
}
};
int serialize();
void deserialize(long,bool as_binary=false);
void transformed_by(Board t);
void transformed_by(Board t,bool details);
int sumOfTrue() const
{
int r=0;
for(int row=0;row<getHeight();row++)
{
for(int col=0;col<getWidth();col++)
{
if (board[row][col])
r++;
}
}
return r;
};
//-----------------------------------------------------------
void operator= (const Board & rhs) ;
bool operator== (const Board & rhs) const;
bool operator!= (const Board & rhs) const;
bool operator< (const Board & rhs) const;
bool operator> (const Board & rhs) const;
bool operator% ( Board & rhs) ; // set contains
Board operator+ (Board & rhs) ;
Board operator- (Board & rhs) ; // set sub
//-----------------------------------------------------------
protected:
vector<vector<bool>> board;
};
void poj1753();
void show_board(vector<vector<bool>> board);
string DecimalToBinaryString(int a);
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/GraphProperties.h
/////////////////////////////////
// P361 Table 4.1.10 GraphProperties
/////////////////////////////////
class GraphProperties
{
private:
vector<bool> mMarked;// MEMBER
vector<int> mEccentricity;
vector<int> mId;// MEMBER
Graph* mG;
bool mSingleCC;
BreadthFirstPaths* mBfs;
public:
GraphProperties(Graph* G)// METHOD
{
mG=G;
mMarked.resize(G->V(),0);
mEccentricity.resize(G->V(),0);
mSingleCC=1;
CC* cc=new CC(G);
if(cc->count()>1)
{
DPRINT("Graph has more than 1 CC, return");
mSingleCC=0;
return;
}
for(int ii=0;ii<mG->V();ii++)
{
mEccentricity[ii]=eccentricity(ii);
}
}
int eccentricity(int v) // the min distance the farest node of node v
{
if(!mSingleCC) return -1;
mBfs=new BreadthFirstPaths(mG,v);
mBfs->getEccentricity();
}
int diameter() // the max value of eccentricity of all nodes
{
if(!mSingleCC) return -1;
int max=-1;
for(int ii=0;ii<mG->V();ii++)
{
if(mEccentricity[ii]>max)
{
max=mEccentricity[ii];
}
}
return max;
}
int radius() // the min value of eccentricity of all nodes
{
if(!mSingleCC) return -1;
int min=9999;
for(int ii=0;ii<mG->V();ii++)
{
if(mEccentricity[ii]<min)
{
min=mEccentricity[ii];
}
}
return min;
}
int center() // nodes whose diameter==radius
{
if(!mSingleCC) return -1;
for(int ii=0;ii<mG->V();ii++)
{
auto d=diameter();
auto r=radius();
DLOG(ii);
DLOG(d);
DLOG(r);
if(d==r)
return ii;
}
return -1;
}
//void dfs(Graph* G,int v)// METHOD
//{
// //DLOG(v);
// mEccentricity[v]=eccentricity(v);
// mMarked[v]=1;
// for(int w:G->adj(v))
// if(!mMarked[w])
// {
// dfs(G,w);
// }
//}
};
class TestGraphProperties// METHOD
{
public:
TestGraphProperties(Graph* G)//METHOD
{
GraphProperties* gp=new GraphProperties(G);
DLOG(gp->eccentricity(1));
DLOG(gp->diameter());
DLOG(gp->radius());
DLOG(gp->center());
}
};
void testGraphProperties()//METHOD
{
Graph* g=new Graph("tinyG.connected.txt");
DLOG(g->toString());
new TestGraphProperties(g);
}
<file_sep>/cpp/codewar/best_travel/ver_20170519/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define SIMPLE_LOG
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
class BestTravel
{
public:
static int chooseBestSum(int t, int k, std::vector<int>& ls);
static int chooseBestSum(std::vector<int>& keepInd,int up_bound,int findItemCnt,std::vector<int>& ls,std::map<std::vector<int>,int>& cache_keep_max);
static int findLargestOne(std::vector<int> keepInd,int up_bound, std::vector<int>& ls,std::map<std::vector<int>,int>& cache_keep_max);
};
int BestTravel::findLargestOne(std::vector<int> keepInd,int up_bound,std::vector<int>& ls,std::map<std::vector<int>,int>& cache_keep_max)
{
sort(keepInd.begin(),keepInd.end());
if(cache_keep_max.count(keepInd)!=0)
{
#ifndef SIMPLE_LOG
std::cout<<"USE CACHE: cache_keep_max";
for (auto v:keepInd)
std::cout<<"\t"<<v;
std::cout<<"=\t"<<cache_keep_max[keepInd];
PRINT_ENDL();
#endif
return cache_keep_max[keepInd];
}
int sum=0;
for(auto i:keepInd) // add sum of index kept
sum+=ls[i];
int max=-1;
for(int i=0;i<ls.size();i++)
{
if(std::find(keepInd.begin(),keepInd.end(),i)!=keepInd.end())
continue;
if(ls[i]+sum>up_bound)
continue;
max=ls[i];
break;
}
if(max==0)
return max;
for(int i=0;i<ls.size();i++)
{
if(std::find(keepInd.begin(),keepInd.end(),i)!=keepInd.end())
continue;
if(max<ls[i] && ls[i]+sum<=up_bound)
max=ls[i];
}
//PRINT_VECTOR_hor(keepInd);
//PRINTVAR(max);
cache_keep_max[keepInd]=max;
return max;
}
int BestTravel::chooseBestSum(std::vector<int>& keepInd,int up_bound,int findItemCnt,std::vector<int>& ls,std::map<std::vector<int>,int>& cache_keep_max)
{
#ifndef SIMPLE_LOG
PRINT_COUT("-->");
PRINT_COUT(__FUNCTION__);
PRINTVAR_hor(up_bound);
PRINTVAR_hor(findItemCnt);
PRINT_ENDL();
//PRINT_VECTOR_hor(keepInd);
//PRINT_VECTOR_hor(ls);
std::cout<<"ls:\t";
int cntr=0;
for(auto u=ls.begin();u!=ls.end();u++) {
bool keep=0;
for(auto i:keepInd)
if(i==cntr)
{
keep=1;
break;
}
if(keep)
std::cout<<cntr<<":"<<*u<<"*\t";
else
std::cout<<cntr<<":"<<*u<<"\t";
cntr++;
}
std::cout<<""<<std::endl;
#endif
sort(keepInd.begin(),keepInd.end());
if(cache_keep_max.count(keepInd)!=0)
{
#ifndef SIMPLE_LOG
std::cout<<"USE CACHE top: cache_keep_max";
for (auto v:keepInd)
std::cout<<"\t"<<v;
std::cout<<"=\t"<<cache_keep_max[keepInd];
PRINT_ENDL();
#endif
return cache_keep_max[keepInd];
}
//std::cout<<std::endl;
//PRINT_DEBUG_INFO_PREFIX("=====================");
int sum=0;
for(auto i:keepInd) // add sum of index kept
sum+=ls[i];
//PRINTVAR_hor(sum);
if(sum>up_bound)
return -1; // means that the sum of index kept will > up_bound
//PRINT_DEBUG_INFO_PREFIX("ENTER chooseBestSum ====================>");
int sum_bk=sum;
if(findItemCnt==1) // find the largest one
{
auto value=findLargestOne(keepInd,up_bound,ls,cache_keep_max);
if(value!=-1)
sum+=value;
else
sum=-1;
}
else //
{
int maxValue=-1;
for(int choose_next_fixed_ind=0; choose_next_fixed_ind!=ls.size();choose_next_fixed_ind++)
{
int i=choose_next_fixed_ind;
if(std::find(keepInd.begin(),keepInd.end(),i)!=keepInd.end())
continue;
std::vector<int> newKeepInd=keepInd;
newKeepInd.push_back(i);
int newSum=0;
for(auto i:newKeepInd) // add newSum of index kept
newSum+=ls[i];
//PRINT_DEBUG_INFO_PREFIX("CALL-----");
//PRINT_VECTOR_hor(keepInd);
//PRINT_VECTOR_hor(newKeepInd);
//PRINTVAR(up_bound);
//PRINTVAR(newSum);
auto tmp=chooseBestSum(newKeepInd,up_bound,findItemCnt-1,ls,cache_keep_max); // recur
if(tmp==-1)
continue;
if(maxValue<tmp)
maxValue=tmp;
}
PRINTVAR(maxValue);
if(maxValue==-1)
return -1;
if(maxValue>sum)
sum=maxValue;
}
PRINTVAR(sum);
cache_keep_max[keepInd]=sum;
return sum;
}
int BestTravel::chooseBestSum(int t, int k, std::vector<int>& ls)
{
clock_t start, end;
start = clock();
std::map<std::vector<int>,int> cache_keep_max;
std::vector<int> lsLessThanT;
for(auto i:ls)
{
if(i<=t)
lsLessThanT.push_back(i);
}
PRINTVAR(ls.size());
PRINTVAR(lsLessThanT.size());
if(k>lsLessThanT.size())
return -1;
std::vector<int> keepInd;
end = clock(); std::cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
auto ans= chooseBestSum(keepInd,t,k,lsLessThanT,cache_keep_max);
PRINT_VECTOR_hor(ls);
PRINT_VECTOR_hor(lsLessThanT);
PRINTVAR_hor(t);
PRINTVAR_hor(k);
PRINT_DEBUG_INFO_PREFIX("=====================");
PRINTVAR(ans);
//std::cout<<std::endl;
end = clock();
//std::cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
//std::cout << "CPU-TIME START " << start << "\n";
//std::cout << "CPU-TIME END " << end << "\n";
//std::cout << "CPU-TIME END - START " << end - start << "\n";
std::cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return ans;
}
int main ()
{
//std::vector<int> arr = {17, 0, -4, 3, 15};
//std::vector<int> arr = {3,4,8,9,10};
#if 0
std::vector<int> arr = {91,74,73,73,73,73,73};
std::map<std::vector<int>,int> cache_keep_max;
BestTravel::chooseBestSum(300,3,arr);
#endif
std::vector<int> arr = {100, 76, 56, 44, 89, 73, 68, 56, 64, 123, 2333, 144, 50, 132, 123, 34, 89 };
auto r=BestTravel::chooseBestSum(880,8,arr);
//PRINTVAR(BestTravel::findLargestOne(std::vector<int>(),100,arr,cache_keep_max));
//PRINT_DEBUG_INFO_PREFIX("================================================");
//std::vector<int> a={1,2,3};
//std::vector<int> b={1,3,2};
//sort(b.begin(),b.end());
//PRINTVAR((a==b));
//PRINT_DEBUG_INFO_PREFIX("================================================");
PRINTVAR(r);
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/ch_7.5.bubble_sort.cpp
#include <stdio.h>
#include <iostream>
//#include <iostream.h>
#include "ch_7.5.h"
#include "lib.h"
using namespace std;
int f_ch_7_5() {
//double a[]={3,2,1,4,6,-8,100,10};
//double a[]={8,7,6,5,4,3,2,1};
double a[]={1,2,3,4,5,6,7,8};
cout<<"before:"<<endl;
int len=sizeof(a)/sizeof(double);
cout<<"length:"<<len<<endl;
show_array(a,len,true,0);
int r_list[2];
sort_bubble(a,len,r_list);
cout<<"after:"<<endl;
show_array(a,len,true,0);
cout <<"diff_cnt,swap_cnt="<<r_list[0]<<","<<r_list[1]<<endl;
}
<file_sep>/python/workspace_python/dive_into_python/src/1/word_sum/word_sum.py
import re
#import xlrd
#import xlwt
def sort_by_value(d):
items=d.items()
backitems=[[v[1],v[0]] for v in items]
backitems.sort()
return [ backitems[i][1] for i in range(0,len(backitems))]
#f=open('D:\workspace_python\dive_into_python\src\1\word_sum\liric.txt','r')
f=open('D:\liric.eng.txt','r')
#f=open('D:\\fhw.txt','r')
f_info= f.read()
f_info_LOW=f_info.lower()
tmp = re.sub(r'\'re', ' are', f_info_LOW)
tmp1= re.sub(r'don\'t', 'do not', tmp)
tmp = re.sub(r'\'ll', ' will', tmp1)
tmp1= re.sub(r'"', '', tmp)
tmp = re.sub(r',', ' ', tmp1)
tmp1= re.sub(r'\'m', ' am', tmp)
tmp = re.sub(r'\'s', ' is', tmp1)
f_info=tmp
print f_info
f_info_list=re.split(r'\s+', f_info)
print f_info_list[4]
print f_info_list
word_cnt= len(f_info_list)
#sum=None
sum={'':0}
for w in f_info_list:
if w in sum:
sum[w]=sum[w]+1
else:
sum[w]=1
print '----------'
#print sum
for k in sort_by_value(sum):
pr_value=(float(sum[k])/word_cnt)
if (pr_value>0.01):
print k,":",'%6.2f'%pr_value
pass
# open read xls
# open write xls
cntr=1
for k in sort_by_value(sum):
#print k,":",'%6.2f'%(float(sum[k])/word_cnt)
value='%6.2f'%(float(sum[k])/word_cnt)
#print table.cell(cntr,2)
cntr=cntr+1
# SAVE
#book.save('D:\workspace_python\exe_out.xlsx')<file_sep>/python/workspace_python/k_means/src/test_kmeans_py.py
#################################################
# kmeans: k-means cluster
# Author : zouxy
# Date : 2013-12-25
# HomePage : http://blog.csdn.net/zouxy09
# Email : <EMAIL>
#################################################
from numpy import *
import time
import matplotlib.pyplot as plt
import k_means
## step 1: load data
print "step 1: load data..."
dataSet = []
fileIn = open('D:\workspace_python\k_means\src\sample.txt')
for line in fileIn.readlines():
lineArr = line.strip().split('\t')
dataSet.append([float(lineArr[0]), float(lineArr[1])])
## step 2: clustering...
print "step 2: clustering..."
dataSet = mat(dataSet)
k = 2
centroids, clusterAssment = k_means.kmeans(dataSet, k)
## step 3: show the result
print "step 3: show the result..."
k_means.showCluster(dataSet, k, centroids, clusterAssment)<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/3.5.h
int main3_5 () ;
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/Node.cpp
#include <include.top.h>
//Node::Node(int v,Node* n) {
// a=v;
// next=n;
//}
//
//void Node::setA(int v) {a=v;}
//void Node::setNext(Node* n) {next=n;}
//int Node::getA() {return a;}
//Node* Node::getNext(){return next;}
<file_sep>/cpp/POJ_separated/1018_NOT_USE/s.handout.cpp
#include <vector>
#include <string>
#include <iostream>
#include <map>
typedef std::map<int, std::map<int, std::map<int, int>>> TYPEMAP ;
class BestTravel
{
public:
static int chooseBestSum(int t, int k, std::vector<int>& ls);
static int chooseBestSum(int start_from,int up_bound,int findItemCnt,std::vector<int>& ls, TYPEMAP& cache_keep_max);
static int max(int a,int b) {return a>b?a:b;};
};
int BestTravel::chooseBestSum(int start_from,int up_bound,int findItemCnt,std::vector<int>& ls,TYPEMAP& cache_keep_max) // recur
{
if(findItemCnt<=0)
return 0;
if(findItemCnt+start_from>ls.size())// cannot find findItemCnt items
return -1;
if( cache_keep_max.count(start_from)!=0 &&
cache_keep_max[start_from].count(up_bound)!=0 &&
cache_keep_max[start_from][up_bound].count(findItemCnt)!=0
)
return cache_keep_max[start_from][up_bound][findItemCnt];
int sum;
if(start_from>=ls.size()-1) // the last one item;
{
if(ls[start_from]>up_bound)
sum=-1;
else
sum= ls[start_from];
}
else
{
if(ls[start_from]>up_bound)
sum= chooseBestSum(start_from+1,up_bound,findItemCnt,ls,cache_keep_max);
else
{
int left=chooseBestSum(start_from+1,up_bound-ls[start_from],findItemCnt-1,ls,cache_keep_max);
int right =chooseBestSum(start_from+1,up_bound,findItemCnt,ls,cache_keep_max);
int sum_of_left=(left==-1)?-1:(left+ ls[start_from]);
sum= max( sum_of_left, right );
}
}
cache_keep_max[start_from][up_bound][findItemCnt]=sum;
return sum;
}
int BestTravel::chooseBestSum(int t, int k, std::vector<int>& ls)
{
TYPEMAP cache_keep_max;
std::vector<int> lsLessThanT;
for(auto i:ls)
{
if(i<=0)
return -1;
if(i<=t)
lsLessThanT.push_back(i);
}
if(k>lsLessThanT.size())
return -1;
auto ans= chooseBestSum(0,t,k,lsLessThanT,cache_keep_max);
return ans;
}
int main ()
{
//std::vector<int> arr = {17, 0, -4, 3, 15};
//std::vector<int> arr = {3,4,8,9,10};
#if 0
std::vector<int> arr = {91,74,73,73,73,73,73};
std::map<std::vector<int>,int> cache_keep_max;
auto r=BestTravel::chooseBestSum(300,3,arr);
#endif
#if 0
std::vector<int> arr = {1,2,91,74,73,82,71};
std::map<std::vector<int>,int> cache_keep_max;
auto r=BestTravel::chooseBestSum(500,5,arr);
#endif
#if 0
std::vector<int> arr = {100, 76, 56, 44, 89, 73, 68, 56, 64, 123, 2333, 144, 50, 132, 123, 34, 89 };
//std::vector<int> arr = {100, 44, 89, 73, 68, 56, 64, 123, 34, 89 };
auto r=BestTravel::chooseBestSum(500,5,arr);
#endif
#if 0
std::vector<int> arr = { 91,74,73,85,73,81,87};
auto r=BestTravel::chooseBestSum(331,5,arr);
#endif
#if 1
std::vector<int> arr = { 91,74,73,85,73,81,87 };
auto r=BestTravel::chooseBestSum(331,4,arr);
#endif
return 0;
}
<file_sep>/python/workspace_python/design_pattern/src/factory_method/FactoryOfCalc.py
import CalcAbstract
class FactoryOfCalc():
def __init__(self):
pass
def get_calc(self):
s=CalcAbstract.CalcAbstract()
class FactoryOfCalcAdd(FactoryOfCalc):
def __init__(self):
pass
def get_calc(self):
s=CalcAbstract.CalcAdd()
return s
class FactoryOfCalcSub(FactoryOfCalc):
def __init__(self):
pass
def get_calc(self):
s=CalcAbstract.CalcSub()
return s
class FactoryOfCalcMul(FactoryOfCalc):
def __init__(self):
pass
def get_calc(self):
s=CalcAbstract.CalcMul()
return s
class FactoryOfCalcDiv(FactoryOfCalc):
def __init__(self):
pass
def get_calc(self):
s=CalcAbstract.CalcDiv()
return s
if __name__ == "__main__":
sf=FactoryOfCalcDiv()
s=sf.get_calc()
ans=s.calc(1, 2)
print ans<file_sep>/cpp/exe_TSP/bat.sh
source run.sh
cd pr_data/
source run.sh
cd ..
<file_sep>/cpp/game/three_pig/character.h
#ifndef CHARACTER_H_
#define CHARACTER_H_
class Point
{
public:
Point() {x=0;y=0;};
Point(int ix,int iy) {x=ix;y=iy;};
int x;
int y;
bool isIn(){return 0;};
bool operator== (const Point& rhs) const
{
return (x==rhs.x && y==rhs.y);
}
void transform()
{
int tmp=x;
x=y;
y=tmp;
}
void mirrorX()
{
y=-y;
}
};
class Character
{
public:
string type; // P pig, W wolf
Character()
{
type="P";
}
Character(string t)
{
type=t;
}
Character(string t,int x,int y)
{
type=t;
setLoc(x,y);
}
void setLoc(int ix,int iy) {
loc.x=ix;
loc.y=iy;
};
Point getLoc(){
return loc;
};
string getType()
{
return type;
}
bool isLegal() {}
Point loc;
};
#endif
<file_sep>/cpp/POJ/include/poj1000.h
void poj1000 () ;
<file_sep>/cpp/exe_UNIT_TEST_tool_Catch/test_catch.cpp
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
//--------------------------------------
// include lib files
//--------------------------------------
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_MAP(a) std::cout<<#a<<":"<<endl;for(auto u:a) {std::cout<<u.first<<"\t->\t"<<u.second<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
using namespace std;
unsigned int Factorial( unsigned int number ) {
return number <= 1 ? number : Factorial(number-1)*number;
}
TEST_CASE( "Factorials are computed", "[factorial]" ) {
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800 );
}
#ifndef CATCH_CONFIG_MAIN
int main ()
{
cout<<"hello"<<""<<endl;
cout<<""<<Factorial(5)<<""<<endl;
}
#endif
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch2/exe2.1e4/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
//#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#include <vector>
#include <string>
#include <iostream>
#include <deque>
#include <stack>
#include <algorithm>
#include <assert.h>
using namespace std;
vector<string>* genSeries(int n);
vector<vector<int>>* genAllValidSum(int n);
int main ()
{
stack<int> s ;
//TreeNode* expected = new TreeNode(17, new TreeNode(0, new TreeNode(3), new TreeNode(15)), new TreeNode(-4));
//Assert::That(*Solution::arrayToTree(arr), Equals(*expected));
//*Solution::arrayToTree(arr);
s.push(1);
s.push(2);
s.push(3);
PRINTVAR(s.top());
genAllValidSum(2);
//genSeries(3);
return 0;
}
#if 0
vector<string>* genSeries(int n)
{
stack<int> left,bottom;
vector<int> right;
// init in left side:
for(int i=1;i<=n;i++)
left.push(i);
auto left.bk=left;
int go_r_cnt=0;
int go_b_cnt=0;
int go_r_cnt2=0;
}
#endif
# if 0
1
1 1
2
1 1 1
1 2
3
#endif
void show_v_v(vector<vector<int>> vv)
{
for(auto v:vv)
{
for(auto i:v)
cout<<""<<i<<"\t";
cout<<""<<""<<endl;
}
}
vector<vector<int>>* genAllValidSum(int n)
{
if(n==1)
{
auto r=new vector<vector<int>>();
vector<int> v;
v.push_back(1);
r->push_back(v);
return r;
}
else
{
auto r=genAllValidSum(n-1);
auto r_new=new vector<vector<int>>();
vector<vector<int>>& old=*r;
vector<vector<int>> old_scratch=old;
vector<vector<int>>& newvv=*r_new ;
PRINT_DEBUG_INFO_PREFIX("newvv:");
show_v_v(newvv);
for(auto v:old_scratch ) // vector<int>
{
for(auto i:v)
{
}
}
PRINT_DEBUG_INFO_PREFIX("newvv:");
show_v_v(newvv);
}
}
<file_sep>/python/workspace_python/PKU Online Judge/poj_C15H.py
# -*- coding:gb2312 -*-
__author__ = 'jc'
'''
C15H:Lucky Draw
查看 提交 统计 提问
总时间限制: 4000ms 内存限制: 65536kB
描述
In the Lucky village, people are crazy on a game called Lucky Draw. In this game,
N players stand in a line,
and each one is assigned an integer number.
Then, the village master would randomly choose
K continuous players.
Among these K players, the one who has the largest number will win the first prize of A dollars.
Also, the one with the second smallest number will win the second prize of B dollars.
Different players may have same numbers.
As an agreement, only the rightmost player who has the largest number owns the first prize,
and the leftmost player who has the second smallest number owns the second prize.
Note that the second smallest number should be greater than the smallest number.
Therefore, if all of these K players have the same number, no one will win the second prize.
A big problem in this game is about fairness.
Some players may have much more chance to win prizes than others.
So, the village master wants to know how fair the game is.
You should tell the village master how many players have the opportunity to win the prize.
In addition, you need to calculate the variance of the expected prize moneys of these potential prize winners.
输入
The first line contains four integers,
N, K, A, B, as described before. (1 ≤ K ≤ N ≤ 1000000, 1 ≤ A, B ≤ 1000).
{
N players stand in a line
K continuous players
first prize of A dollars
second prize of B dollars
}
The second line contains N integers, indicate the numbers assigned to those players,
listed from left to right. The numbers are guaranteed to fit in 32-bit signed integers.
输出
Output only one line containing an integer M and a real number V, separated by a single space.
M is the number of players who have any chance to win the prize money.
V is the variance of the expected prize money of these M players, rounded to four digits after the decimal point.
样例输入
6 3 1 2
1 2 1 3 3 3
样例输出
4 0.1719
提示
In the sample case, assuming players are represented by P1, P2, ..., P6 from left to right.
If players P1, P2, P3 are chosen, whose assigned numbers are 1 2 1, P2 wins 3 dollars.
If players P2, P3, P4 are chosen, whose assigned numbers are 2 1 3, P4 wins 1 dollar and P2 wins 2 dollars.
If players P3, P4, P5 are chosen, whose assigned numbers are 1 3 3, P5 wins 1 dollar and P4 wins 2 dollars.
If players P4, P5, P6 are chosen, whose assigned numbers are 3 3 3, only P6 wins 1 dollar.
P2, P4, P5 and P6 have a chance to win, and the expected prize moneys are 1.25, 0.75, 0.25 and 0.25 respectively.
The average expected prize money of these four players is 0.625 and the variance is 0.1719.
'''
def find_right_largest(ll):
max=-999
for ind in range(len(ll)):
if ll[ind]>=max:
maxInd=ind
max=ll[ind]
print("the right largest of {} is ll[{}]={}".format(ll,maxInd,ll[maxInd]))
return maxInd
find_right_largest([1,2,3,2,3,1])
def find_left_2nd_smallest(ll):
min=999
min_2nd=999
minInd=-1
min_2ndInd=-1
for ind in range(len(ll)):
if ll[ind]<min:
min_2ndInd=minInd
min_2nd=min
minInd=ind
min=ll[ind]
elif ll[ind]==min:
pass
elif ll[ind]<min_2nd:
min_2ndInd=ind
min_2nd=ll[ind]
v=ll[min_2ndInd]
if min_2ndInd==-1:
v='NA'
print("the left 2nd smallest of {} is ll[{}]={}".format(ll,min_2ndInd,v))
return min_2ndInd
find_left_2nd_smallest([2,3,2,3,1])
find_left_2nd_smallest([1,2,3,2,3,1])
find_left_2nd_smallest([3,3,2,3,1])
find_left_2nd_smallest([1,2,3,2,3,1])
find_left_2nd_smallest([2,2,2,2,2])
N=6
K=3
A=1
B=2
plist=[1,2,1,3,3,3]
money=[]
for i in plist:
money.append(0)
den=N-K+1
for i in range(N-K+1):
choosen=plist[i:i+3]
print(" {}".format(plist))
print("CHOOSEN:{}{}{}".format(" X "*i,choosen," X "*(N-K-i)))
max=-999
min=999
min_2nd=999
prize_1_winner=find_right_largest(choosen)
trueInd1=prize_1_winner+i
print("UP the right largest is plist[{}]={}".format(trueInd1,plist[trueInd1]))
prize_2_winner=find_left_2nd_smallest(choosen)
money[prize_1_winner+i]+=A
if prize_2_winner!=-1:
trueInd2=prize_2_winner+i
print("UP the left 2nd smallest is plist[{}]={}".format(trueInd2,plist[trueInd2]))
money[prize_2_winner+i]+=B
for i in range(len(money)):
money[i]=money[i]/den
print(money)<file_sep>/cpp/6_EXEs/src/map_with_sort.cpp
#include<map>
#include<string>
#include<iostream>
//#include "include.top.h"
#include "map_with_sort.h"
using namespace std;
typedef pair<string, int> PAIR;
ostream& operator<<(ostream& out, const PAIR& p) {
return out << p.first << "\t << *iter << endl; " << p.second;
}
int map_with_sort_wrp() {
//map<string, int> name_score_map; // here
map<string, int, is_less<string> > name_score_map; // here
name_score_map["LiMin"] = 90;
name_score_map["ZiLinMi"] = 79;
name_score_map["BoB"] = 92;
name_score_map.insert(make_pair("Bing",99));
name_score_map.insert(make_pair("Albert",86));
for (map<string, int>::iterator iter = name_score_map.begin();
iter != name_score_map.end();
++iter) {
cout<<""<<*iter<<""<<endl;
}
foo(name_score_map);
return 0;
}
void foo(map<string, int, is_less<string> > m) {
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.2_directed_graph/Topological.h
class Topological
{
private:
vector<int> mOrder;
public:
Topological(Digraph*G)
{
DENTER;
DirectedCycle*cyclefinder=new DirectedCycle(G);
DLOG(cyclefinder->hasCycle());
if(!cyclefinder->hasCycle())
{
DepthFirstOrder* dfs=new DepthFirstOrder(G);
mOrder=dfs->reversePost();
reverse(mOrder.begin(),mOrder.end());
DLOG(mOrder);
DLOG(dfs->pre());
DLOG(dfs->post());
}
DRETURN;
}
bool isDAG() { return mOrder.size()!=0; }
vector<int> order() { return mOrder; }
};
class TestTopological
{
public:
TestTopological()
{
string fname="tinyG.nocycle.txt";
SymbolDigraph* sg=new SymbolDigraph(fname," ");
auto G=sg->G();
//DLOG(G->toString());
DLOG(sg->toString());
//G->dumpDOT("TestTopological.dot");
sg->dumpDOT("TestTopological.dot");
Topological* topo=new Topological(G);
DLOG(topo->isDAG());
for(int v:topo->order())
{
cout<<sg->name(v)<<"("<<v<<") ";
}
cout<<endl;
}
};
<file_sep>/cpp/codewar/fun_with_trees/array_to_tree/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
//#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#include <vector>
#include <string>
#include <iostream>
#include <deque>
#include <assert.h>
class TreeNode
{
public:
TreeNode(int value, TreeNode* left, TreeNode* right)
: m_value(value), m_left(left), m_right(right)
{
}
TreeNode(int value)
: m_value(value), m_left(NULL), m_right(NULL)
{
}
bool operator==(const TreeNode& rhs) const
{
//... // Already implemented for you and used in test cases
PRINT_DEBUG_INFO();
bool t=!(m_value==rhs.m_value);
if(t)
return false;
PRINT_DEBUG_INFO();
t=!(m_left==rhs.m_left);
if(t)
return false;
PRINT_DEBUG_INFO();
t=!(m_right==rhs.m_right);
if(t)
return false;
PRINT_DEBUG_INFO();
t= !(m_left==NULL) && !((*m_left)==(*(rhs.m_left)));
if(t)
return false;
PRINT_DEBUG_INFO();
t= !(m_right==NULL) && !((*m_right)==(*(rhs.m_right)));
if(t)
return false;
PRINT_DEBUG_INFO();
return true;
}
void show()
{
std::cout<<"show TreeNode:"<<this<<":"<<m_value<<std::endl;
}
bool have2Children()
{
return (m_left!=NULL && m_right!=NULL);
}
void setChild(TreeNode* childPtr)
{
if(m_left==NULL)
m_left=childPtr;
else if(m_right==NULL)
m_right=childPtr;
return;
}
//...
int m_value;
TreeNode* m_left;
TreeNode* m_right;
};
class Solution
{
public:
static TreeNode* arrayToTree(std::vector<int> arr)
{
TreeNode* rootNode;
std::deque<TreeNode*> queueOfNode;
int cntr=0;
for(auto i:arr)
{
auto node=new TreeNode(i);
if(cntr==0)
rootNode=node;
node->show();
// father point to children
if(!queueOfNode.empty())
{
auto fr=queueOfNode.front();
assert(!fr->have2Children());
fr->setChild(node);
}
// push to queue
queueOfNode.push_back(node);
// pop front of queue
if(!queueOfNode.empty())
{
auto fr=queueOfNode.front();
if(fr->have2Children())
queueOfNode.pop_front();
}
PRINTVAR(queueOfNode.size());
cntr++;
}
PRINT_VECTOR_hor(arr);
return rootNode; // TODO: implementation
}
};
int main ()
{
std::vector<int> arr = {17, 0, -4, 3, 15};
//TreeNode* expected = new TreeNode(17, new TreeNode(0, new TreeNode(3), new TreeNode(15)), new TreeNode(-4));
//Assert::That(*Solution::arrayToTree(arr), Equals(*expected));
//*Solution::arrayToTree(arr);
auto n1=TreeNode(1);
auto n2=TreeNode(1);
PRINTVAR((n1==n2));
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/main.cpp
#include "include.top.h"
using namespace std;
int main() {
cout<<"Hello world!"<<endl;
//f7_5();
//f4_10(10);
//f5_9(10);
//f8_2();
//f9_1();
f20_1();
return 0;
}
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch1_life_game/include/total.h
../src/lib.cpp:double myfac (int n) {// FUNC
../src/lib.cpp:double calc_sum_of_power (int n,int power=3) {// FUNC
../src/lib.cpp:bool is_tulip (int n, int power=3) {// FUNC
../src/lib.cpp:bool is_prime (int n, int print=0) {// FUNC
../src/lib.cpp:bool is_full_num (int n, int print=0) {// FUNC
../src/lib.cpp:double calc_use_do (double x, double stop=1e-8) {// FUNC
../src/lib.cpp:bool is_int (double v) {// FUNC
../src/lib.cpp://double integral(double from,double to){// FUNC
../src/lib.cpp:bool item_is_in_array (int i,int a[] ,int a_length) {// FUNC
../src/lib.cpp:void show_array(double a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) {// FUNC
../src/lib.cpp:void show_array(int a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) {// FUNC
../src/lib.cpp:void sort_bubble(double a [],int size,int return_list[]) {// FUNC
../src/life_game.cpp:void main_life_game() {//FUNC
../src/utility.cpp:bool user_say_yes() {//FUNC
<file_sep>/python/workspace_python/TreeGui/easygui.py
__author__ = 'jc'
import easygui
print (easygui.abouteasygui)<file_sep>/python/workspace_python/extend_snake/src/food.py
import pygame
import random
import gl
class Food_piece(object):
def __init__(self, pos, color=(255, 0, 0)):
self.m_x = pos[0]
self.m_y = pos[1]
self.x = self.m_x * 10
self.y = self.m_y * 10
self.color = color
def blit(self, screen):
rect = pygame.Rect(self.x, self.y, 10, 10)
pygame.draw.rect(screen, self.color, rect)
class Food(object):
def __init__(self):
self.food = list()
self.time = 3000
self.time_tick = 300
def random_pos(self, snake):
running = True
while running:
x, y = random.randint(1, 39), random.randint(1, 39)
running = False
for t in snake.tail :
if t.m_x == x and t.m_y == y :
running = True
if x == snake.x and y == snake.y :
running = True
for p in self.food :
if p.m_x == x and p.m_y == y :
running = True
return x, y
def restart(self):
self.food = []
self.time = 300
def update(self, dt, screen, snake):
self.time += dt
if self.time >= self.time_tick or len(self.food) <= 0:
self.time = 0
x, y = self.random_pos(snake)
f_piece = Food_piece((x, y))
self.food.append(f_piece)
for f_piece in self.food :
if f_piece.m_x == snake.x and f_piece.m_y == snake.y :
snake.increase_length(1, 5)
self.food.remove(f_piece)
f_piece.blit(screen)
<file_sep>/cpp/game/three_pig/run.sh
rm a.out; g++ -v -g -Wall -std=c++11 threePig.cpp > compile.log ; ./a.out
#rm a.out; g++ -v -g -Wall -std=c++11 s.handout.cpp ; ./a.out
# debug macro:
# g++ -E -v -g -Wall -std=c++11 s.cpp > trans_macro.auto.cpp
<file_sep>/python/workspace_python/dive_into_python/src/1/1/advanced.py
# advanced topics:
# slicing:
i=range(3,20,2)
print i
print i[5:]
# slice of string
print 'abcdefg'[-2:]
# Iteration:
for j in 'abcde'[:3]:
print j
d={'a':1,'b':2,'c':3}
for j in d.itervalues():
print j
d={'a':1,'b':2,'c':3}
for j in d.iteritems():
print j
print "-------------"
for char in "user_id":
print char
# filter
print [x * x for x in range(1, 12)]
print [x * x for x in range(1, 12) if x>6]
print [d for d in 'abcde']
print [m+n for m in 'ABC' for n in 'XYZ']
import os
print [os.listdir('.')]
# generator:
l=[x*x for x in range(5)]
g=(x*x for x in range(5))
print l
print g
print g.next()
for i in g:
print i
# lambda
f=lambda x:x*x
print "3 * 3 is ",f(3)
g=lambda x,y:x**y
print g(2,3)
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/7.5.h
void f7_5() ;
double calc_diag_sum(double a[][10],int n) ;
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/include/include.h
#ifndef INCLUDE_H_
#define INCLUDE_H_
#define SIMPLE_LOG 0
#define LNX 1
#if (!SIMPLE_LOG)
#define DLOG(x) cout<<#x<<"="<<x<<" @"<<__FILE__<<":"<<__LINE__<<endl;
#define DLOG1(x) cout<<#x<<"="<<x<<"\t";
#else
#define DLOG(x)
#define DLOG1(x)
#endif
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@["<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()]"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#if (!SIMPLE_LOG)
#define DENTER \
LVCALL++; PRLVCALL; ::std::cout<<"-->"<<__FUNCTION__<<::std::endl;
#define DENTERV(x) \
LVCALL++; PRLVCALL; ::std::cout<<"-->"<<__FUNCTION__<<"("<<x<<")"<<::std::endl;
#define DRETURN \
PRLVCALL; ::std::cout<<"<--"<<__FUNCTION__<<"@["<<__FILE__<<":"<<__LINE__<<"]"<<::std::endl; LVCALL--;
#define DRETURNV(x) \
PRLVCALL; ::std::cout<<"<--"<<__FUNCTION__<<"("<<x<<")@["<<__FILE__<<":"<<__LINE__<<"]"<<::std::endl; LVCALL--;
#endif
#define DEBUG_MARK PRINT_DEBUG_INFO()
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define DPRINT(x) \
(::std::cout<<x<<::std::endl )
#define DPRINT_hor(x) \
(::std::cout<<x )
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@["<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()]"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#if SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define DEBUG_MARK
#define PRINT_DEBUG_INFO_PREFIX(p)
#define DPRINT(x)
#define DPRINT_hor(x)
#define PRINT_COUT(p)
#define DENTER
#define DENTERV
#define DRETURN
#define DRETURNV
#endif
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <deque>
#include <regex>
#include <map>
#include <assert.h>
using namespace std;
#if !SIMPLE_LOG
static int LV=0;
static int LVCALL=-1;
#define PRLV std::cout<<LV<<"\t"; for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLV for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLVCALL std::cout<<"L"<<LVCALL<<"\t"; for(int u12=LVCALL;u12>0;u12--) {std::cout<<" .. ";}
template <class U>
std::ostream & operator <<(std::ostream &os, const std::vector<U> &m)
{
if(m.size()==0)
return os;
os << std::endl;
PRLV(LV);
os << "->";
os << std::endl;
LV++;
PRLV(LV);
for (const auto &p : m)
{
os << p << ", " ;
}
os << std::endl;
LV--;
PRLV(LV);
os << "<-";
return os;
}
template <class U>
std::ostream & operator <<(std::ostream &os, const std::deque<U> &m)
{
if(m.size()==0)
return os;
os << std::endl;
PRLV(LV);
os << "->";
os << std::endl;
LV++;
PRLV(LV);
for (const auto &p : m)
{
os << p << ", " ;
}
os << std::endl;
LV--;
PRLV(LV);
os << "<-";
return os;
}
template <class U, class V>
std::ostream & operator <<(std::ostream &os, const std::map<U, V> &m)
{
os << "->";
os << std::endl;
for (const auto &p : m)
{
os << p.first << ": " << p.second;
os << std::endl;
}
os << "<-";
return os;
}
#endif
//=========================================================================================
#if LNX
//int main()
//{
//}
#endif
#endif
<file_sep>/python/workspace_python/basic_algorithm_of_python/Joseph_ring.py
__author__ = 'jc'
def show():
print("-----------------------")
for i in list_name:
print(str(i)+"\t",end=" ")
print()
for i in list_name:
print(str(hash_live[i])+"\t",end=" ")
print()
print("-----------------------")
TOTAL_NUMBER=30 ;# total number
PERIOD=9 ;# period
FROM=1 ;# from
list_name=range(1,TOTAL_NUMBER+1)
hash_live={}
for i in list_name:
hash_live[i]=1
#print("name:"+str(i)+" live"+str(hash_live[i]))
dead_cnt=0
counter=0
pointer=0
print ("============")
print ("START:")
print ("============")
show()
while dead_cnt<=TOTAL_NUMBER-PERIOD:
pointer+=1
if pointer>TOTAL_NUMBER:
pointer=1
if hash_live[pointer]==1:
counter+=1
print("pointer"+str(pointer)+" says:"+str(counter),end="")
if counter%PERIOD==0:
print(' DIE!')
hash_live[pointer]=0
dead_cnt+=1
counter=0
show()
else:
print()
else:
print("pointer"+str(pointer)+" is DEAD")
print ("============")
print ("END:")
print ("============")
show()<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph/GraphBase.h
class GraphBase {
public:
GraphBase();
GraphBase(int v);
virtual int V();
virtual int E();
virtual void addEdge(int v,int w);
virtual vector<int> adj(int v);
string toString();
int degree(int v);
int maxDegree();
int avgDegree();
int numberOfSelfLoops();
private:
};
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch1_life_game/include/cpp2h.sh
grep FUNC ../src/* > total.h
<file_sep>/python/workspace_python/dive_into_python/src/1/MS_interview_book/1.1.py
import time
cnt=0
v=0
while True:
for i in range(5):
print 'sleep'
time.sleep(0.01)<file_sep>/tcl/tcl_call_cpp/3/main.c
#include <tcl.h>
#include <stdio.h>
int Tcl_AppInit(Tcl_Interp *interp);
int main(int argc, char *argv[]) {
Tcl_Main(argc, argv, Tcl_AppInit);
}
int Tcl_AppInit(Tcl_Interp *interp) {
/* Initialize Tcl */
if (Tcl_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
/* Initialize our extension */
if (Fract_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
return TCL_OK;
}
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/include/f13_3.h
#include "include.top.h"
#define YES 1
#define NO 0
#define PRINT_DEBUG_INFO() \
(cout<<"DEBUG: " <<__FILE__<<":" <<__LINE__<<" compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<endl)
void f13_3() ;
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/5.9.cpp
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <iomanip>
#include "4.10.h"
#include "5.9.h"
#include "lib.h"
using namespace std;
int f5_9 (int year) {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
for (int n=0;n<=year;n++) {
cout<<"head of year:"<<n<<"\tsum:"<<sum(n)<<"\tsum_big:"<<sum_big(n)<<endl;
}
cout<<"------------------------"<<endl;
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
int sum(int n) {
if (n==0) {
return 1;
} else {
return sum(n-1)+new_born(n);
}
}
int sum_big(int n) {
if (n<=3) {
return 0;
} else {
return sum(n-4);
}
}
int sum_small(int n) {
return sum(n)-sum_big(n);
}
int new_born(int n) {
return sum_big(n);
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/11.2.cpp
#include "include.top.h"
using namespace std;
void f11_2(){
Cat frisky;
frisky.SetAge(5);
frisky.Meow();
cout <<"cat age="
<<frisky.GetAge()
<<endl;
frisky.Meow();
}
<file_sep>/tcl/book_Practical_Programming_in_Tcl_Tk/ch44/random.c
/*
* random.c
*/
# include <tcl.h>
int RandomCmd(ClientData clientData,
Tcl_Interp *interp,
int argc, char * argv[]);
int RandomObjCmd(ClientData clientData,
Tcl_Interp* interp,
int objc, Tcl_Obj *CONST objv[]);
int Random_Init(Tcl_Interp * interp){
if(Tcl_InitStubs(interp, "8.1",0)==NULL){
return TCL_ERROR;
}
Tcl_CreateCommand(interp,
"random",
RandomCmd,
/*
(ClientData)NULL,
(const
Tcl_CmdDeleteProc*)
NULL
*/
NULL,
NULL
);
Tcl_CreateObjCommand(interp, "orandom", RandomObjCmd,
(ClientData)NULL,
(Tcl_CmdDeleteProc*)NULL);
Tcl_PkgProvide(interp,
"random", "1.1");
return TCL_OK;
}
int RandomCmd(ClientData clientData,
Tcl_Interp* interp,
int argc,
char* argv[])
{
int rand,error;
int range=0;
if(argc>2){
interp->result="Usage: random ?range?";
return TCL_ERROR;
}
if(argc==2){
if(Tcl_GetInt(interp,argv[1],&range)!=TCL_OK) {
return TCL_ERROR;
}
}
rand=random();
if(range!=0){
rand=rand%range;
}
sprintf(interp->result, "%d", rand);
return TCL_OK;
}
<file_sep>/cpp/tree_structure/tree.class.cpp
// NODE CLASS
template <typename DATA_TYPE>
Node<DATA_TYPE>::Node()
{
mData=0;
mNextSibling=0;
mFirstChild=0;
mIdInATree="";
}
template <typename DATA_TYPE>
Node<DATA_TYPE>::Node(DATA_TYPE v){
mData=v;
mNextSibling=0;
mFirstChild=0;
mIdInATree="";
};
template <typename DATA_TYPE>
Node<DATA_TYPE>::Node(DATA_TYPE v,Node* ns,Node* fc){
mData=v;
mNextSibling=ns;
mFirstChild=fc;
mIdInATree="";
};
template <typename DATA_TYPE>
Node<DATA_TYPE>* Node<DATA_TYPE>::getmNextNSibling(int n){
assert(n>=0);
if(n==0)
return this;
if(n==1)
return mNextSibling;
else
return mNextSibling->getmNextNSibling(n-1);
};
template <typename DATA_TYPE>
void Node<DATA_TYPE>::show(){
std::cout<<"----------------------------------------------------------------------------------------------------"<<std::endl;
std::cout<<"Node obj at =\t"<<this<<std::endl;
std::cout<<"Node mData =\t"<<mData<<std::endl;
std::cout<<"Node mNextSibling=\t"<<mNextSibling<<std::endl;
std::cout<<"Node mFirstChild =\t"<<mFirstChild<<std::endl;
std::cout<<"Node mIdInATree =\t"<<mIdInATree<<std::endl;
std::cout<<"----------------------------------------------------------------------------------------------------"<<std::endl;
};
// TREE CLASS
template <typename NODE_DATA_TYPE>
Tree<NODE_DATA_TYPE>::Tree(){
Root=new NODE_T();
list.push_back(Root);
};
template <typename NODE_DATA_TYPE>
Tree<NODE_DATA_TYPE>::~Tree(){
for(auto n:list)
{
delete n;
}
//delete Root;
}
template <typename NODE_DATA_TYPE>
void Tree<NODE_DATA_TYPE>::insertNode(NODE_T* brother,NODE_T* newNode)
{
assert(brother);
newNode->setmNextSibling(brother->getmNextSibling());
brother->setmNextSibling(newNode);
return;
};
template <typename NODE_DATA_TYPE>
void Tree<NODE_DATA_TYPE>::insertNode(NODE_T* parent,unsigned nth,NODE_DATA_TYPE newNodeData)
{
PRINT_DEBUG_INFO();
Node<NODE_DATA_TYPE>* newNode=new NODE_T(newNodeData);
insertNode(parent,nth, newNode);
};
template <typename NODE_DATA_TYPE>
void Tree<NODE_DATA_TYPE>::insertNode(NODE_T* parent,unsigned nth,NODE_T* newNode)
{
PRINT_DEBUG_INFO();
list.push_back(newNode);
bool flag_got_parent_node=false;
for(auto p:list)
{
if(p==parent)
{
flag_got_parent_node=true;
break;
}
}
if(!flag_got_parent_node)
{
std::cout<<"in insertNode(), cannot get parent node: "<<parent<<std::endl;
return;
}
NODE_T* target;
PRINT_DEBUG_INFO();
if(nth==0)
{
PRINT_DEBUG_INFO();
target=parent;
assert(target);
newNode->setmNextSibling(target->getmFirstChild());
target->setmFirstChild(newNode);
return;
}
else if(nth==1)
{
PRINT_DEBUG_INFO();
target=parent->getmFirstChild();
assert(target);
newNode->setmNextSibling(target->getmNextSibling());
target->setmNextSibling(newNode);
return;
}
else
{
PRINT_DEBUG_INFO();
target=parent->getmFirstChild();
assert(target);
int cntr=nth;
while(cntr!=0)
{
target=target->getmNextSibling();
cntr--;
}
assert(target);
newNode->setmNextSibling(target->getmNextSibling());
target->setmNextSibling(newNode);
return;
}
};
//template <typename NODE_DATA_TYPE>
//void Tree<NODE_DATA_TYPE>::insertNode(NODE_T* parent,NODE_T* newNode)
//{
// unsigned i=0;
// insertNode(parent,i,newNode);
//};
template <typename NODE_DATA_TYPE>
void Tree<NODE_DATA_TYPE>::deleteNode(string id)
{
if(id=="0") // you cannot delete root node
assert(0);
vector<int> idVector=stoi(split(id,"_"));
NODE_T* curNode=Root->getmFirstChild();
NODE_T* lastNode=Root;
assert(curNode);
int ind=1;
PRINTVAR(idVector.size());
while(ind<idVector.size())
{
int nth=idVector[ind];
assert(curNode);
lastNode=curNode;
curNode=curNode->getmNextNSibling(nth);
assert(curNode);
if(ind!=idVector.size()-1) // if not reach the target node, go one level deeper
{
lastNode=curNode;
curNode=curNode->getmFirstChild();
}
ind++;
}
if(id.back()=='0') // is the first child
lastNode->setmFirstChild(curNode->getmNextSibling());
else
lastNode->setmNextSibling(curNode->getmNextSibling());
return ;
}
template <typename NODE_DATA_TYPE>
void Tree<NODE_DATA_TYPE>::deleteNode(NODE_T* targetNode)
{
}
template <typename NODE_DATA_TYPE>
NODE_T* Tree<NODE_DATA_TYPE>::getRoot()
{
//return list[0];
return Root;
};
template <typename NODE_DATA_TYPE>
NODE_T* Tree<NODE_DATA_TYPE>::getNodeById(string id)
{
if(id=="0")
return Root;
vector<int> idVector=stoi(split(id,"_"));
NODE_T* curNode=Root->getmFirstChild();
assert(curNode);
int ind=1;
PRINTVAR(idVector.size());
while(ind<idVector.size())
{
PRINTVAR(ind);
int nth=idVector[ind];
PRINTVAR(nth);
assert(curNode);
curNode->show();
curNode=curNode->getmNextNSibling(nth);
assert(curNode);
if(ind!=idVector.size()-1) // if not reach the target node, go one level deeper
curNode=curNode->getmFirstChild();
ind++;
}
return curNode;
};
// zjc
template <typename NODE_DATA_TYPE>
void Tree<NODE_DATA_TYPE>::_print_used_in_show(Node<int>* node)
{
int lv=split(node->getmIdInATree(),"_").size();
while(lv!=0)
{
cout<<"\t";
lv--;
}
cout<<node->getmIdInATree()<<"\t@"<<node<<endl;
}
template <typename NODE_DATA_TYPE>
void Tree<NODE_DATA_TYPE>::show()
{
traverseDFS(Root,"0",_print_used_in_show);
//traverseDFS(Root,"0");
};
template <typename NODE_DATA_TYPE>
void Tree<NODE_DATA_TYPE>::traverseDFS(NODE_T* fromNode,string fromNodeId,void (*func)(NODE_T*))
{
vector<int> curIdInATreeVec;
if(fromNodeId!="")
{
fromNode->setmIdInATree(fromNodeId);
curIdInATreeVec=stoi(split(fromNodeId,"_"));
}
else
{
fromNode->setmIdInATree("0");
curIdInATreeVec.push_back(0);
}
//std::cout<<"calling traverseDFS for:\t"<<fromNode->getmData()<<"\t@"<<fromNode<<std::endl;
NODE_T* curNode=fromNode;
//curNode->show();
// do some thing
if(func)
func(curNode);
if(curNode->getmFirstChild())
{
NODE_T* curChild=curNode->getmFirstChild();
curIdInATreeVec.push_back(0);
traverseDFS(curChild,join(itos(curIdInATreeVec),"_"),func);
while(curChild->getmNextSibling())
{
curChild=curChild->getmNextSibling();
//
int curIdTail=curIdInATreeVec.back();
curIdTail++;
curIdInATreeVec.pop_back();
curIdInATreeVec.push_back(curIdTail);
//
traverseDFS(curChild,join(itos(curIdInATreeVec),"_"),func);
//traverseDFS(curChild);
}
}
};
template <typename NODE_DATA_TYPE>
void Tree<NODE_DATA_TYPE>::traverseBFS(NODE_T* fromNode,string fromNodeId,void (*func)(NODE_T*))
{
vector<int> curIdInATreeVec;
if(fromNodeId!="")
{
//PRINTVAR(fromNodeId);
fromNode->setmIdInATree(fromNodeId);
curIdInATreeVec=stoi(split(fromNodeId,"_"));
}
else
{
fromNode->setmIdInATree("0");
curIdInATreeVec.push_back(0);
}
//std::cout<<"calling traverseBFS for:\t"<<fromNode->getmData()<<"\t@"<<fromNode<<std::endl;
NODE_T* curNode=fromNode;
//curNode->show();
std::deque<NODE_T*> queue;
queue.push_back(curNode);
while(queue.size()!=0)
{
curNode=queue.front();
queue.pop_front();
// do some thing
if(func)
func(curNode);
int cnt_child=0;
NODE_T* curChild=curNode->getmFirstChild();
if(!curChild)
continue;
vector<int> baseIdVec= stoi(
split(curNode->getmIdInATree(),"_")
);
baseIdVec.push_back(cnt_child);
//PRINTVAR( join( itos(baseIdVec) ,"_"));
curChild->setmIdInATree(
join(
itos(baseIdVec)
,"_"
)
);
baseIdVec.pop_back();
//PRINTVAR(cnt_child);
while(curChild)
{
queue.push_back(curChild);
curChild=curChild->getmNextSibling();
//PRINTVAR(curChild);
if(!curChild)
break;
cnt_child++;
//PRINTVAR(cnt_child);
baseIdVec.push_back(cnt_child);
//PRINTVAR( join( itos(baseIdVec) ,"_"));
curChild->setmIdInATree(
join(
itos(baseIdVec)
,"_"
)
);
baseIdVec.pop_back();
}
}
};
<file_sep>/python/workspace_python/PKU Online Judge/poj_C15J.py
__author__ = 'jc'
import math
import random
import numpy as np
#import pygame,sys
#from pygame.locals import *
def four_axis_aligned(p1,p2,p3,p4):
lx=[p1[0],p2[0],p3[0],p4[0]]
ly=[p1[1],p2[1],p3[1],p4[1]]
lx_uniq=np.unique(lx)
ly_uniq=np.unique(ly)
if len(lx_uniq)==2 and len(ly_uniq)==2:
return True
else:
return False
def three_maybe_axis_aligned(p1,p2,p3):
lx=[p1[0],p2[0],p3[0]]
ly=[p1[1],p2[1],p3[1]]
lx_uniq=np.unique(lx)
ly_uniq=np.unique(ly)
if len(lx_uniq)>2 or len(ly_uniq)>2:
return False
else:
return True
star=[]
WIDTH=10
HEIGHT=100
N=10
for i in range(N):
flag_match=1
while flag_match:
flag_match=0
rx=random.randint(1,WIDTH)
ry=random.randint(1,HEIGHT)
for u in star:
if u[0]==rx and u[1]==ry:
flag_match=1
cord=[rx,ry]
star.append(cord)
ans_list=[]
for i in range(N):
print("ITER: %d"%(i))
for j in range(i+1,N):
if i==j:
continue
for k in range(j+1,N):
if k==i or k==j:
continue
if not three_maybe_axis_aligned(star[i],star[j],star[k]):
continue
for l in range(k+1,N):
if l==i or l==j or l==k:
continue
pass
if four_axis_aligned(star[i],star[j],star[k],star[l]):
new_clct={i,j,k,l}
if not new_clct in ans_list:
ans_list.append({i,j,k,l})
print("AXIS_ALIGNED:")
print(str(star[i]))
print(str(star[j]))
print(str(star[k]))
print(str(star[l]))
#plt.plot(star[i],star[j],star[k],star[l])
print('================END')
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/include/f13_4.h
#include "include.top.h"
void f13_4() ;
<file_sep>/cpp/POJ/src/poj2965.cpp
#include "include.top.h"
#include <math.h>
#include <iomanip>
#include <map>
#include "poj1753.h"
#include "poj2965.h"
using namespace std;
#include <fstream>
void poj2965 ()
{
cout<<"-----------------------------------------------"<<endl;
cout<<"poj2965"<<endl;
//----------------------------------------------------------
string filename="input/poj2965.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj2965.out";
// clean the file "output/poj2965.out"
std::ofstream outfile_init(filename_out);
outfile_init.close();
std::ofstream outfile(filename_out,ios::app);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
GateOfRefrigerator gate_read_file("input/poj2965.in");
cout<<"gate_read_file.show()"<<endl;
gate_read_file.show();
//gate_read_file.flip(1,2);
//gate_read_file.show();
GateOfRefrigerator gate_read_file_bk=gate_read_file;
vector<Board> solution_tranformations;
for(int seed0=0;seed0<pow(2,16);seed0++)
{
gate_read_file=gate_read_file_bk;
Board t;
t.deserialize(seed0);
//PRINTVAR(seed0);
//cout<<"before:"<<endl;
//gate_read_file.show();
gate_read_file.transformed_by(t);
//cout<<"after:"<<endl;
//gate_read_file.show();
if (gate_read_file.isAllBlack())
{
solution_tranformations.push_back(t);
std::cout << "GOT\n";
t.show();
}
}
cout<<"GOT "<<solution_tranformations.size()<<" solutions:"<<endl;
sort(solution_tranformations.begin(),solution_tranformations.end());
std::cout << "----------------------------------------\n";
cout<<"solution_tranformations"<<endl;
for (auto t:solution_tranformations)
{
t.show();
cout<<"**"<<endl;
cout<<t.sumOfTrue()<<endl;
outfile<<t.sumOfTrue()<<endl;
//outfile.close();
t.showTransformationSteps(true);
t.showTransformationSteps(true,"output/poj2965.out");
cout<<"**"<<endl;
}
std::cout << "----------------------------------------\n";
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
//----------------------------------------------------------
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
outfile.close();
}
void GateOfRefrigerator::flip(int row,int col)
{
//cout<<"calling GateOfRefrigerator::flip()"<<endl;
int r,c;
r=row;
c=col;
for(int r=0;r<=3;r++)
{
board[r][c]=!board[r][c];
}
r=row;
c=col;
for(int c=0;c<=3;c++)
{
board[r][c]=!board[r][c];
}
r=row;
c=col;
board[r][c]=!board[r][c];
}
<file_sep>/cpp/5_BOOK_CPP_PRIMER/include/include.top.h
#ifndef INCLUDE_TOP_H
#define INCLUDE_TOP_H
//--------------------------------------
// macro
//--------------------------------------
#define PI 3.14159265358
#define GET_VALUE(x) (x)
#define SQUARE_VOLUME(a) (a*a*a)
#define SPHERE_VOLUME(a) (4/3*PI*a*a*a)
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<std::endl;
//#define PRINTVAR(a) printf("%s\t=\t%s\n",#a,a)
//--------------------------------------
// include lib files
//--------------------------------------
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <algorithm>
//using namespace std; // you'd better not use using command in header files.
//--------------------------------------
// include local files
//--------------------------------------
//#include "include/f13_2.h"
#include "lib.h"
#include "exe_2.3.1.h"
#include "ch3.h"
#include "exe_3.2.h"
#include "exe_3.16.h"
#include "exe_3.22.h"
#include "include.top.h"
//--------------------------------------
#endif
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/DepthFirstSearch.h
#include "Graph.h"
class DepthFirstSearch {
/////////////////////////////////
// P337 Table 4.1.4 Search
/////////////////////////////////
private:
bool* mMarked;
int mCount;
public:
DepthFirstSearch() {}
DepthFirstSearch(Graph* G,int s)
{
mMarked=new bool[G->V()];
dfs(G,s);
}
void dfs(Graph* G,int v)
{
mMarked[v]=true;
mCount++;
for(int w:G->adj(v))
if(!mMarked[w]) dfs(G,w);
}
bool marked(int w) { return mMarked[w]; }
int count() { return mCount; }
};
class Search:public DepthFirstSearch
{
public:
Search(Graph* G,int s) { }
};
class TestSearch {
public:
TestSearch(Graph* G,int s)
{
DENTER;
Search* search=new Search(G,s);
for(int v=0;v<G->V();v++)
if(search->marked(v))
cout<<v<<" ";
cout<<""<<endl;
if(search->count()!=G->V())
cout<<"NOT ";
cout<<"connected."<<endl;
DRETURN;
}
TestSearch(string fnameGraph,int s)
{
Graph* G=new Graph(fnameGraph);
TestSearch(G,s);
}
private:
;
};
void testSearch()
{
DENTER;
Graph* g=new Graph ("tinyG.txt");
DLOG(g->toString());
int SOURCE=1;
new TestSearch(g,SOURCE);
DRETURN;
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/Cycle.h
/////////////////////////////////
// P352 Table 4.1.7 Cycle
/////////////////////////////////
class Cycle
{
private:
vector<bool> mMarked;// MEMBER
bool mHasCycle;// MEMBER
vector<int> mCycle;
public:
Cycle(Graph* G)// METHOD
{
mMarked.resize(G->V(),0);
mCycle={};
for(int s=0;s<G->V();s++)
if(!mMarked[s])
dfs(G,s,s);
}
void dfs(Graph* G,int v,int u)// METHOD
{
// print some cycles but not all
// how to print all cycles?
//DENTER;
mMarked[v]=1;
mCycle.push_back(v);
#if 0
cout<<"mMarked:";
for(int ii=0;ii<mMarked.size();ii++)
{
if(mMarked[ii])
cout<<ii<<" ";
}
cout<<endl;
#endif
//DLOG(mCycle);
//DPRINT("set mId["<<v<<"]="<<mCount );
for(int w:G->adj(v))
{
//PRINTVAR_hor(v);
//DPRINT_hor(" ref:"<<u<<",");
//DPRINT(w<<" of adj("<<v<<")");
if(!mMarked[w])
{
dfs(G,w,v);
}
else if(w!=u)
{
auto iter=find(mCycle.begin(),mCycle.end(),w);
if(iter!=mCycle.end())
{
int ind=iter-mCycle.begin();
mCycle.push_back(w);
//DPRINT("hasCycle because: "<<w<<"!="<<u);
DPRINT("hasCycle:");
for(int ii=ind;ii<mCycle.size();ii++)
{
cout<<mCycle[ii]<<" ";
}
cout<<endl;
mHasCycle=true;
mCycle.pop_back();
}
}
}
mCycle.pop_back();
//DRETURN;
}
//bool connected(int v,int w) { return mId[v]==mId[w]; }// METHOD
//int id(int v){return mId[v];}// METHOD
//int count(){return mCount;}// METHOD
};
class TestCycle// METHOD
{
public:
TestCycle(Graph* G)//METHOD
{
Cycle* cy=new Cycle(G);
}
};
void testCycle()//METHOD
{
Graph* g=new Graph("tinyG.txt");
DLOG(g->toString());
new TestCycle(g);
}
<file_sep>/cpp/6_EXEs/include/use_std_sort.h
int use_std_sort();
<file_sep>/python/workspace_python/use_baidu/test.py
#! /usr/bin/env python
# coding=utf-8
import gl
gl.printGB '中abc'<file_sep>/cpp/POJ/include/poj1006.h
void poj1006 ();
int calc_next_triple_peak (int p_last,int e_last,int i_last,int d_start);
bool is_divided(int a,int b);
void analyze_is_divided(int a,int b);
<file_sep>/python/workspace_python/design_pattern/src/AbstractFactory/AbstractFactory.py
__author__ = 'by jc'
# Abstract Factory
'''
client
|
AbsFactory abstract_product
|
ConcreteFactory1 ConcreteFactory2 -> concrete_product1 concrete_product2
'''
class Person:
def say(self):
pass
class Teacher(Person):
def say(self):
print 'I\'m a teacher'
class Farmer(Person):
def say(self):
print 'I\'m a farmer'
if __name__ == "__main__":
i=Farmer()
i.say()
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.2_directed_graph/DirectedCycle.h
/////////////////////////////////
// P372 Table 4.2.5 DirectedCycle
/////////////////////////////////
class DirectedCycle
{
private:
vector<bool> mMarked;// MEMBER
vector<int> mEdgeTo;// MEMBER
vector<int> mDirectedCycle;
vector<bool> mOnStack;
bool mHasDirectedCycle;// MEMBER
public:
DirectedCycle(Digraph * G)// METHOD
{
auto v=G->V();
mOnStack.resize(v,0);
mEdgeTo.resize(v,-1);
mMarked.resize(v,0);
for(int s=0;s<v;s++)
if(!mMarked[s])
dfs(G,s);
reverse(mDirectedCycle.begin(),mDirectedCycle.end());
}
private:
void dfs(Digraph* G,int v)// METHOD
{
//DENTER;
mOnStack[v]=1;
mMarked[v]=1;
for(int w:G->adj(v))
if(hasCycle())
return;
else if(!mMarked[w])
{
mEdgeTo[w]=v;
dfs(G,w);
}
else if(mOnStack[w])
{
mDirectedCycle={};
for(int x=v;x!=w;x=mEdgeTo[x])
mDirectedCycle.push_back(x);
mDirectedCycle.push_back(w);
mDirectedCycle.push_back(v);
}
mOnStack[v]=0;
//DRETURN;
}
public:
bool hasCycle() {
bool r= mDirectedCycle.size()!=0;
if(r)
DLOG(mDirectedCycle);
return r;
}
vector<int> cycle() {return mDirectedCycle;}
};
class TestDirectedCycle// METHOD
{
public:
TestDirectedCycle()//METHOD
{
Digraph* g=new Digraph("tinyG.hasDirectedCycle.txt");
//Digraph* g=new Digraph("tinyG.nocycle.txt");
DLOG(g->toString());
g->dumpDOT("TestDirectedCycle.dot");
auto dc=new DirectedCycle(g);
DLOG(dc->hasCycle());
}
};
<file_sep>/cpp/7_EXEs_separated/exe_append_file/s.cpp
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <glob.h>
using namespace std;
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_MAP(a) std::cout<<#a<<":"<<std::endl;for(auto u:a) {std::cout<<u.first<<"\t->\t"<<u.second<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_POINTER1(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER2(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<"\t->\t"<<**a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER3(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<"\t->\t"<<**a; \
std::cout<<"\t->\t"<<***a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER(a) PRINT_POINTER1(a)
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//inline std::vector<std::string> glob(const std::string& pat);
inline std::vector<std::string> glob(const std::string& pat){
using namespace std;
glob_t glob_result;
glob(pat.c_str(),GLOB_TILDE,NULL,&glob_result);
vector<string> ret;
for(unsigned int i=0;i<glob_result.gl_pathc;++i){
ret.push_back(string(glob_result.gl_pathv[i]));
}
globfree(&glob_result);
return ret;
}
int copy() {
clock_t start, end;
start = clock();
ifstream source("from.ogv", ios::binary);
ofstream dest("to.ogv", ios::binary);
istreambuf_iterator<char> begin_source(source);
istreambuf_iterator<char> end_source;
ostreambuf_iterator<char> begin_dest(dest);
copy(begin_source, end_source, begin_dest);
source.close();
dest.close();
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
int main()
{
PRINT_DEBUG_INFO();
std::fstream fs;
// glob
auto v=glob("/home/delon/workspace/exe/cpp/exe_append_file/*ist*");
PRINT_VECTOR(v);
PRINTVAR(v.size());
PRINTVAR(v[0]);
/////
int found;
string str=v[0];
cout << "Splitting: " << str << endl;
found=str.find_last_of("/\\");
cout << " folder: " << str.substr(0,found) << endl;
cout << " file: " << str.substr(found+1) << endl;
/////
// rename
//std::string oldname="existing";
std::string oldname=v[0];
std::string newname="test.txt";
int result=rename(oldname.c_str(),newname.c_str());
assert(result==0);
// append
fs.open ("test.txt", std::fstream::app);
fs << " more lorem ipsum "<<endl;
fs.close();
// copy
copy();
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/8.2.h
void f8_2() ;//FUNC
<file_sep>/cpp/exe_game/tetris/run.sh
#ctags -R --c++-kinds=+p --fields=+iaS --extra=+q
rm a.out;
# only do it once:
#g++ tests-main.cpp -c
#g++ tests-main.o tests-factorial.cpp -o tests && ./tests -r compact
#g++ -g -Wall -std=c++11 tests-main.o tests.cpp s.cpp Shape.class.cpp Matrix.class.cpp Display.class.cpp unit_test.cpp && ./a.out
g++ -g -Wall -std=c++11 s.cpp Shape.class.cpp Matrix.class.cpp Display.class.cpp unit_test.cpp lib.cpp && ./a.out
#rm a.out ; g++ -std=c++0x -g -Wall s.cpp && ./a.out
<file_sep>/python/workspace_python/basic_algorithm_of_python/ten_classic_C_programs.py
__author__ = 'jc'
import math
print('1=================')
#ll=[1,2,3,4]
ll=range(1,5,1)
cnt=0
for i in ll:
for j in ll:
for k in ll:
if( i!=j and i!=k and j!=k):
print('%d%d%d'%(i,j,k))
cnt+=1
print('----')
print('totally '+str(cnt)+' number')
print('2=================')
input_num=35.5
list_band =[10, 20, 40, 60, 100, 999999]
list_ratio=[0.1,0.075,0.05,0.03,0.015,0.01]
length=len(list_band)
for ind in range(length):
u=list_band[ind]
v=list_ratio[ind]
print("%d\t%d\t%f"%(ind,u,v))
left=input_num
avenue=0
old_u=0
for ind in range(length):
u=list_band[ind]
v=list_ratio[ind]
if left<=u:
add=left*v
avenue+=add
print('avenue+= %f * %f=%f'%(left,v,add))
break
else:
diff=u-old_u
add=diff*v
avenue+=add
print('avenue+= (%f-%f) * %f=%f'%(u,old_u,v,add ))
left=left-diff
old_u=u
print('avenue= %f'%(avenue))
avg_rate=avenue/input_num
print("average_rate=%f"%(avg_rate))
print('3=================')
def is_squre(n):
up_bound=math.floor(math.sqrt(n))+1
for i in range(1,up_bound,1):
if n==i**2:
print("%d = %d^2"%(n,i))
return True
return False
for i in range(100000):
u=i+100
v=i+168
print("ITER: %d %d %d"%(i,u,v))
if is_squre(i) and is_squre(u):
print("GET: %d %d %d"%(i,u,v))
break
print("======== a printvar proc:")
a = 123
b = 46
c = 'aaaa'
def printvar(varname):
if varname in globals():
print("Info: {} = {}".format(varname, globals()[varname]))
printvar('a')
printvar('b')
printvar('c')
print('4=================')
year=1992
month=3
day=15
if year%4==0:
length_list=[31,29,31,30,31,30,31,31,30,31,30,31]
else:
length_list=[31,28,31,30,31,30,31,31,30,31,30,31]
day_cnt=0
for i in range(1,month):
printvar('i')
day_add=length_list[i-1]
printvar('day_add')
day_cnt+=day_add
printvar('day_cnt')
day_cnt+=day
printvar('day_cnt')
print('5=================')
#n0,n1,n2=input("input 3 number:").split(',')
ll=[6,5,4,2,1,11,5]
#printvar('n0')
#printvar('n1')
lls=sorted(ll,key=lambda item:int(item))
print(lls)
print('6=================')
print(" "+"*"*8+" ")
print("*"+" "*8+"*")
for i in range(4):
print("*")
print("*"+" "*8+"*")
print(" "+"*"*8+" ")
print('7=================')
a=chr(176)
b=chr(219)
print("{}{}{}{}{}".format(b,a,a,a,b))
print("{}{}{}{}{}".format(a,b,a,b,a))
print("{}{}{}{}{}".format(a,a,b,a,a))
print("{}{}{}{}{}".format(a,b,a,b,a))
print("{}{}{}{}{}".format(b,a,a,a,b))
print('8=================')
for a in range(10):
if a==2:
print("-"*100)
for b in range(10):
if b==2:
print("|",end="")
print("%5d"%(a*b),end="")
print(" ",end=" ")
print()
print('9=================')
for a in range(9):
for b in range(9):
if (a+b)%2==0:
print(" ",end="")
else:
print("**",end="")
print()
print('10=================')
print("|^.^|^.^|")
for a in range(9):
print(" "*9,end="")
for b in range(9):
if a==b:
print("|_",end="")
else:
print(" ",end="")
print()
<file_sep>/cpp/5_BOOK_CPP_PRIMER/include/exe_3.22.h
void f_3_22() ;
<file_sep>/python/workspace_python/extend_snake/src/ss_simple_snake.py
import pygame
import food
import player
import AI
import gl
class Game_Window(object):
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((400, 400), 0, 32)
self.clock = pygame.time.Clock()
# self.player = player.Snake(400,400)
gl.snake_list = []
for i in range(2):
name='s'+str(i)
objname='player'+str(i)
#self.player=AI.AI(i,i,name)
#gl.snake_list.append(self.player)
gl.snake_list.append(AI.AI(i*3,i*3,name))
self.Food = food.Food()
self.font = pygame.font.SysFont('Comic Sans MS', 40)
def blit_grid(self):
for x in range(40):
pygame.draw.aaline(self.screen, (255, 255, 255), (x * 10, 0), (x * 10, 400))
for y in range(40):
pygame.draw.aaline(self.screen, (255, 255, 255), (0, y * 10), (400, y * 10))
def game_over(self):
running = True
time = 0
while running :
time += self.clock.tick()
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN and time > 1500:
running = False
self.screen.fill((255, 255, 255))
text = self.font.render('GAME OVER ', True, (255, 0, 0))
self.screen.blit(text, (200 - text.get_width() / 2, 200 - text.get_height()))
for i in gl.snake_list:
t2 = 'POINT : ' + str(i.point)
# t2 = 'POINT : ' + str(self.player.point)
text2 = self.font.render(t2, True, (255, 0, 0))
self.screen.blit(text2, (200 - text2.get_width() / 2, 200 + text2.get_height()))
pygame.display.update()
for snake in gl.snake_list:
snake.is_dead = False
# self.player.is_dead = False
# self.player2.is_dead = False
self.clock.tick()
for snake in gl.snake_list:
snake.restart()
# self.player.restart()
# self.player2.restart()
self.Food.restart()
def run(self):
while True :
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
self.screen.fill((255, 255, 255))
dt = self.clock.tick()
#print("DEBUG:dt="+str(dt))
for snake in gl.snake_list:
snake.update(dt, self.screen)
self.Food.update(dt, self.screen, snake)
# self.player.update(dt,self.screen)
# self.Food.update(dt,self.screen,self.player)
# self.player2.update(dt,self.screen)
# self.Food.update(dt,self.screen,self.player2)
self.blit_grid()
for snake in gl.snake_list:
if snake.is_dead:
print 'DEAD:' + snake.name + 'IN:' + str(snake.x) + ' ' + str(snake.y)
self.game_over()
for snake in gl.snake_list:
point = self.font.render(str(snake.point), True, (0, 0, 0))
self.screen.blit(point, (0, 0))
pygame.display.update()
if __name__ == '__main__':
app = Game_Window()
app.run()
<file_sep>/tcl/bdd/run.sh
#!/bin/bash
grep "^proc " bdd.tcl | awk '{print $2}' > proc.list.rpt
grep -f proc.list.rpt bdd.tcl -n > call.tree.rpt
rm *.dot *.svg
/usr/bin/tclsh bdd.tcl 2>&1 | tee -i log
for f in `ls *.dot`
do
echo "f=$f"
dot -Tsvg -o $f.svg $f
done
<file_sep>/cpp/ch1.1.cpp/run.sh
g++ hello_world.cpp -o hw.out
<file_sep>/cpp/exe_map/main.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int,map<int,map<int,string>>> m;
m[0][0][0]="000";
m[0][0][1]="001";
m[0][0][2]="002";
m[0][1][0]="010";
m[0][1][1]="011";
m[0][1][2]="012";
m[1][2][0]="120";
m[1][2][1]="121";
std::cout<<"------------------------------"<<std::endl;
std::cout<<"SHOW:"<<std::endl;
for(auto l1:m)
{
//std::cout<<"el.first="<<el.first;
//std::cout<<"el.first="<<el.first;
//std::cout<<"\t"
//PRINTVAR(el.second);
for (auto l2:l1.second)
{
for (auto l3:l2.second)
{
PRINTVAR_hor(l1.first);
PRINTVAR_hor(l2.first);
PRINTVAR_hor(l3.first);
std::cout<<":\t";
PRINTVAR_hor(l3.second);
std::cout<<std::endl;
}
}
}
std::cout<<"------------------------------"<<std::endl;
}
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/include/f13_5.h
#include "include.top.h"
void f13_5() ;
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/4.9.h
int f4_9 () ;
<file_sep>/cpp/exe_game/tetris/Display.class.h
#ifndef DISPLAY_CLASS_H
#define DISPLAY_CLASS_H
//--------------------------------------
// include lib files
//--------------------------------------
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
#include "Matrix.class.h"
using namespace std;
class Display {
public:
Display(){
};
~Display(){
};
void clear() {system("clear");};
void showTitle(){
//clear();
cout<<""<<""<<endl;
cout<<""<<""<<endl;
cout<<""<<""<<endl;
cout<<"========================================================================================================================="<<""<<endl;
cout<<"\t\t\tTetrix\t\t\t"<<""<<endl;
cout<<"========================================================================================================================="<<""<<endl;
cout<<""<<""<<endl;
cout<<""<<""<<endl;
cout<<""<<""<<endl;
PRINT_DEBUG_INFO();
};
//void showBoard(Matrix* m){
//m->show(1);
//};
void show(bool compacted=1);
void show(int markRow,int markCol, string marker="X");
Matrix* m;
private:
};
#endif
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN_good/include/2.1_func.h
bool compare(int a,int b);
bool visit(int* a);
<file_sep>/cpp/6_EXEs/src/stable_sort.cpp
#include "include.top.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
bool operator<(const Employee &lhs, const Employee &rhs) {
return lhs.age < rhs.age;
}
int stable_sort()
{
std::vector<Employee> v = {
Employee(108, "Zaphod"),
Employee(32, "Arthur"),
Employee(18, "Ford"),
Employee(108, "Ford"),
Employee(33, "Ford"),
Employee(208, "Ford"),
Employee(108, "Alice"),
Employee(108, "Chandler"),
Employee(108, "Bob"),
};
cout<<"-----------------------------"<<endl;
for (const Employee &e : v) {
std::cout << e.age << ",\t " << e.name << '\n';
}
cout<<"-----------------------------"<<endl;
// sort age
std::stable_sort(v.begin(), v.end());
cout<<"-----------------------------"<<endl;
for (const Employee &e : v) {
std::cout << e.age << ",\t " << e.name << '\n';
}
cout<<"-----------------------------"<<endl;
// sort name
std::stable_sort(v.begin(), v.end(),
[] (Employee a,Employee b)
{
return a.name<b.name;
}
);
cout<<"-----------------------------"<<endl;
for (const Employee &e : v) {
std::cout << e.age << ",\t " << e.name << '\n';
}
cout<<"-----------------------------"<<endl;
}
<file_sep>/cpp/codewar/validate_credit_vard_number/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#define SIMPLE_LOG
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <regex>
#include <assert.h>
using namespace std;
class Kata {
public:
static bool validate(long long int n) {
vector<int> v;
// split
for(auto c:to_string(n))
{
PRINTVAR(c);
v.push_back(c-48);
}
PRINTVAR(v.size());
PRINT_VECTOR_hor(v);
// s1 double
int start=0;
if(v.size()%2==0)
{
start=0;
}
else
{
start=1;
}
int cntr=0;
for(int & i:v)
{
if((cntr-start)%2==0)
{
i=i*2;
while(i>9)
i-=9;
}
cntr++;
}
PRINT_VECTOR_hor(v);
// s2 9-
// s3 sum
long long sum=0;
for(int i:v)
{
sum+=i;
}
PRINTVAR(sum);
// s4 div by 10
if(sum%10==0)
return true;
//else
string r="FALSE";
PRINTVAR(r);
return false;
}
};
int main ()
{
Kata::validate(891);
Kata::validate(2121);
return 0;
}
<file_sep>/python/workspace_python/extend_snake/src/gl.py
snake_list=[]
SNAKE_SPEED=20<file_sep>/cpp/exe_split/use_own_func/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#define SIMPLE_LOG
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
std::vector<std::string> split(std::string str,std::string pattern)
{
std::string::size_type pos;
std::vector<std::string> result;
std::string str_bk=str,str_no_repeat_blank;
//PRINTVAR(str);
for (auto it=str.begin();it!=str.end();it++)
{
if(it!=str.begin() && *it==' ' && *(it-1)==' ')
;
else
str_no_repeat_blank+=*it;
}
//PRINTVAR(str_no_repeat_blank);
str=str_no_repeat_blank;
str+=pattern;
int size=str.size();
for(int i=0; i<size; i++)
{
pos=str.find(pattern,i);
if(pos<size)
{
std::string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+pattern.size()-1;
}
}
return result;
}
int main ()
{
std::string s="var_name ( + ) ";
auto v=split(s,"e");
PRINT_VECTOR(v);
return 0;
}
<file_sep>/cpp/7_EXEs_separated/exe_regexp_replace_lookahead/reg.cpp
#include <iostream>
#include <fstream>
#include <ctime>
#include <regex>
using namespace std;
int main() {
clock_t start, end;
start = clock();
ifstream source("from.ogv", ios::binary);
ofstream dest("to.ogv", ios::binary);
std::string line,tmp;
//dest << source.rdbuf();
//while(source>>line)
while(getline(source,line))
{
tmp=line;
std::cout<<"LINE=\t"<<line<<std::endl;
////////////////////////////////
std::cout<<"LINE=\t"<<line<<std::endl;
// PRE ENCODE
tmp = std::regex_replace(tmp, std::regex("&"), "%HLS_PREENCODE_amp%");
tmp = std::regex_replace(tmp, std::regex("<" ), "%HLS_PREENCODE_lt%");
tmp = std::regex_replace(tmp, std::regex(">" ), "%HLS_PREENCODE_gt%");
tmp = std::regex_replace(tmp, std::regex("<item" ), "%HLS_PREENCODE_begin_item%");
tmp = std::regex_replace(tmp, std::regex("><\\\/item>" ), "%HLS_PREENCODE_end_item%" );
tmp = std::regex_replace(tmp, std::regex("<annotationInfo>" ), "%HLS_PREENCODE_begin_anno%");
tmp = std::regex_replace(tmp, std::regex("<\\\/annotationInfo>"), "%HLS_PREENCODE_end_anno%" );
std::cout<<"tmp1=\t"<<tmp<<std::endl;
// convert
tmp = std::regex_replace(tmp, std::regex("&"), "&");
tmp = std::regex_replace(tmp, std::regex("<"), "<");
tmp = std::regex_replace(tmp, std::regex(">"), ">");
std::cout<<"tmp2=\t"<<tmp<<std::endl;
// POST DECODE
tmp = std::regex_replace(tmp, std::regex("%HLS_PREENCODE_amp%"), "&");
tmp = std::regex_replace(tmp, std::regex("%HLS_PREENCODE_lt%" ), "<" );
tmp = std::regex_replace(tmp, std::regex("%HLS_PREENCODE_gt%" ), ">" );
tmp = std::regex_replace(tmp, std::regex("%HLS_PREENCODE_begin_item%" ), "<item" );
tmp = std::regex_replace(tmp, std::regex("%HLS_PREENCODE_end_item%" ), "><\/item>");
tmp = std::regex_replace(tmp, std::regex("%HLS_PREENCODE_begin_anno%"), "<annotationInfo>" );
tmp = std::regex_replace(tmp, std::regex("%HLS_PREENCODE_end_anno%" ), "<\/annotationInfo>");
////////////////////////////////
std::cout<<"tmp3=\t"<<tmp<<std::endl;
dest<<tmp<<std::endl;
}
source.close();
dest.close();
//end = clock();
//cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
//cout << "CPU-TIME START " << start << "\n";
//cout << "CPU-TIME END " << end << "\n";
//cout << "CPU-TIME END - START " << end - start << "\n";
//cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph/main.cpp
#include "../../include/include.h"
#include "GraphAdjList.h"
int main()
{
//GraphAdjList* g=new GraphAdjList (10);
GraphAdjList* g=new GraphAdjList ("tinyG.txt");
//g->addEdge(1,2);
DLOG(g->toString());
return 0;
}
void testGraph()
{
GraphAdjList* g=new GraphAdjList ("tinyG.txt");
//g->addEdge(1,2);
DLOG(g->toString());
}
void testSearch(GraphAdjList* g)
{
int source=1;
for(int v=0;v<g->V();v++)
{
if(g->marked(source,v))
DLOG(v);
}
if(g->count(source )!=g->V())
DPRINT("NOT");
DPRINT("CONNECTED");
}
<file_sep>/cpp/codewar/k_primes/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define DLOG(x) PRINTVAR(x)
//#define SIMPLE_LOG
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <regex>
#include <assert.h>
#include <math.h>
using namespace std;
class KPrimes
{
public:
static std::vector<long long> countKprimes(int k, long long start, long long end);
static int puzzle(int s);
static bool isPrime(long long n);
static void genVPrime(long long n);
static bool getAllFactors(int n,vector<int>& v,int threshold=-1 );
//private:
static vector<int> mVecPrime;
static vector<int> mVecExceedPrimeCntr;
static long long mVecPrime_upbound;
static map<long long,vector<int>>* mPtr_MAP_n_all_fac;
};
vector<int> KPrimes::mVecPrime={};
vector<int> KPrimes::mVecExceedPrimeCntr={};
long long KPrimes::mVecPrime_upbound=-1;
map<long long,vector<int>>* KPrimes::mPtr_MAP_n_all_fac=new map<long long,vector<int>>;
std::vector<long long> KPrimes::countKprimes(int k, long long start, long long end)
{
PRINTVAR_hor(k);PRINTVAR_hor(start);PRINTVAR_hor(end);
cout<<endl;
auto ans=new std::vector<long long> ;
for(long long i=start;i<=end;i++)
{
if(i==1)
continue;
std::vector<int> v;
int count=mPtr_MAP_n_all_fac->count(i);
if(count==0)
{
bool r=getAllFactors(i,v,k);
if(r)
(*mPtr_MAP_n_all_fac)[i]=v;
else
mVecExceedPrimeCntr.push_back(i);
}
else
{
PRINT_DEBUG_INFO_PREFIX("SPEED UP!");
v=(*mPtr_MAP_n_all_fac)[i];
}
//cout<<"i:"<<i<<"\t";
PRINTVAR_hor(i);
PRINT_VECTOR_hor(v);
long long tobe=1;
int size=v.size();
PRINTVAR(size);
PRINTVAR(k);
if(size>k)
continue;
else if(v.size()==1)
tobe=pow(v[0],k);
else if(v.size()<k) // <k and !=1
continue;
else
{
for(auto n:v)
{
tobe*=n;
}
}
PRINTVAR(tobe);
PRINTVAR(i);
if(tobe==i)
ans->push_back(i);
}
return *ans;
}
int KPrimes::puzzle(int s)
{
cout<<"CALL puzzle: ";
DLOG(s);
vector<long long > v1=countKprimes(1,0,s);
KPrimes::mVecExceedPrimeCntr={};
vector<long long > v3=countKprimes(3,0,s);
KPrimes::mVecExceedPrimeCntr={};
vector<long long > v7=countKprimes(7,0,s);
PRINT_VECTOR_hor(v1);
PRINT_VECTOR_hor(v3);
PRINT_VECTOR_hor(v7);
int cnt=0;
for(auto i1:v1)
for(auto i3:v3)
for(auto i7:v7)
if(i1+i3+i7==s)
{
PRINTVAR(i1);
PRINTVAR(i3);
PRINTVAR(i7);
cnt++;
}
return cnt;
}
bool KPrimes::isPrime(long long n)
{
if(n<=mVecPrime_upbound)
{
auto result=find(mVecPrime.begin(),mVecPrime.end(),n);
if(result!=mVecPrime.end())
{
PRINT_DEBUG_INFO_PREFIX("GOT Prime fast!");
PRINTVAR(n);
return true;
}
else
{
return false;
}
}
else
{
for(int i=2;i<(int)sqrt(n)+1;i++)
{
if((int)((double)n/i)==(double)((double)n/i))
return false;
}
mVecPrime.push_back(n);
return true;
}
}
void KPrimes::genVPrime(long long n)
{
if(n<=mVecPrime_upbound)
return;
// gen map
map<long long,bool> MAP_i2isPrime;
for(int i=2;i<=n;i++)
MAP_i2isPrime[i]=1;
// mark numbers which is not prime
for(int i=2;i<=n;i++)
{
long long mul=2;
while(mul*i<=n)
{
MAP_i2isPrime[mul*i]=0;
mul++;
}
}
// store primes into mVecPrime
mVecPrime={};
for(int i=2;i<=n;i++)
if(MAP_i2isPrime[i])
mVecPrime.push_back(i);
PRINTVAR(mVecPrime.size());
mVecPrime_upbound=n;
}
bool KPrimes::getAllFactors(int n,vector<int>& v,int threshold )
{
cout<<endl;
cout<<"-->getAllFactors ";
PRINTVAR_hor(n);
PRINTVAR_hor(threshold);
cout<<"v=";
PRINT_VECTOR_hor(v);
cout<<endl;
if(threshold!=-1 && v.size()>threshold )
return false;
if(n<=1)
return true;
// use exceed cache
auto result=find(mVecExceedPrimeCntr.begin(),mVecExceedPrimeCntr.end(),n);
PRINT_DEBUG_INFO();
if(threshold!=-1 && result!=mVecExceedPrimeCntr.end())
{
PRINT_DEBUG_INFO();
return false;
}
if(threshold!=-1 && v.size()>threshold )
{
PRINT_DEBUG_INFO();
return false; // prime # exceed threshold
}
//PRINT_DEBUG_INFO_PREFIX("getAllFactors");
// use n2allfac cache
int count=mPtr_MAP_n_all_fac->count(n);
if(count!=0)
{
PRINT_DEBUG_INFO();
PRINT_DEBUG_INFO_PREFIX("SPEED UP2!");
PRINTVAR(n);
auto tmpv=(*mPtr_MAP_n_all_fac)[n]; // use cache
// concat tmpv into v
for(auto i:tmpv)
{
if(isPrime(i))
{
cout<<"PUSH "<<i<<endl;
v.push_back(i); // there is a bug
}
}
if(threshold!=-1 && v.size()>threshold )
return false;
return true;
}
PRINT_DEBUG_INFO();
if(isPrime(n))
v.push_back(n);
if(threshold!=-1 && v.size()>threshold )
return false;
for(int i=2;i<(int)sqrt(n)+1;i++)
{
PRINT_DEBUG_INFO();
if(
(int)((double)n/i)==(double)((double)n/i)
&& isPrime(i)
)
{
v.push_back(i);
PRINTVAR(i);
if(getAllFactors(n/i,v)==false)
return false;
(*mPtr_MAP_n_all_fac)[n]=v; // store into cache
break;
}
}
if(threshold!=-1 && v.size()>threshold )
return false;
PRINT_DEBUG_INFO();
return true;
}
int main ()
{
clock_t start, end;
start = clock();
//PRINTVAR(KPrimes::isPrime(3));
//PRINTVAR(KPrimes::isPrime(4));
//PRINTVAR(KPrimes::isPrime(5));
//PRINTVAR(KPrimes::isPrime(97));
vector<int> v;
//KPrimes::getAllFactors(12,v,3); PRINT_VECTOR_hor(v);
//auto b=KPrimes::getAllFactors(12,v,2); PRINT_VECTOR_hor(v); PRINTVAR(b);
//auto cv=KPrimes::countKprimes(2,29,31); PRINT_VECTOR_hor(cv);
//auto cv=KPrimes::countKprimes(2,0,100); PRINT_VECTOR_hor(cv);
//auto cv=KPrimes::countKprimes(3,0,1000); PRINT_VECTOR_hor(cv);
auto cv=KPrimes::countKprimes(5,500,600); PRINT_VECTOR_hor(cv);
//auto cv=KPrimes::countKprimes(5,6610309,6611738); PRINT_VECTOR_hor(cv);
v={};
KPrimes::mVecExceedPrimeCntr={};
KPrimes::mVecPrime_upbound=0;
KPrimes::mVecPrime={};
//KPrimes::(*mPtr_MAP_n_all_fac)={}; // need to be init
PRINT_VECTOR_hor(v);
auto succ=KPrimes::getAllFactors(567,v); PRINT_VECTOR_hor(v); PRINTVAR(succ);
//PRINTVAR(KPrimes::puzzle(138));
//PRINTVAR(KPrimes::puzzle(143));
//PRINTVAR(KPrimes::puzzle(250));
//KPrimes::genVPrime(6611738);
//PRINT_VECTOR_hor(KPrimes::mVecPrime);
end = clock();
std::cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
<file_sep>/cpp/POJ/include/poj2632.h
#ifndef POJ2632_H
#define POJ2632_H
#include "include.top.h"
#include "gnuplot_i.h"
//#include "gnuplot_i.new.hpp"
void poj2632();
#endif
<file_sep>/cpp/POJ/include/poj1003.h
#include <map>
using namespace std;
void poj1003 () ;
map<int,float> gen_map_card2length(map<int,float> &map_card2length,float) ;
float calc_center(float n,map<int,float> &map_card2length) ;
<file_sep>/cpp/exe_game/tetris/ShapeExist.class.h
#ifndef SHAPE_EXIST_CLASS_H
#define SHAPE_EXIST_CLASS_H
class ShapeExist: public Shape
{
public:
ShapeExist(int w_board,int h_board)
{
type=999;
ori="NA";
ul_row=0;
ul_col=0;
}
void merge(Shape * shape); // merge the new added shape, after the shape doesn't move
void checkDeleteRow(); // then check whether to delete a row or not
void update(); // update all location after deleting
vector<string> touch(Shape* shape);
// "NOT": not touch
// "HIT": mean one shape hit into another
// S:
// E:
// N:
// W:
}
#endif
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/4.4.h
int main4_4 () ;
<file_sep>/cpp/POJ/src/poj2632.cpp
#include "include.top.h"
#include "gnuplot_i.h"
#include "poj2632.h"
#include "MATRIX.class.h"
#include "ROBOT.class.h"
#include <math.h>
#include <iomanip>
#include <map>
#include <fstream>
using namespace std;
void poj2632 ()
{
#if 1
cout<<"-----------------------------------------------"<<endl;
cout<<"poj2632"<<endl;
//----------------------------------------------------------
string filename="input/poj2632.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj2632.out";
// clean the file "output/poj2632.out"
std::ofstream outfile_init(filename_out);
outfile_init.close();
std::ofstream outfile(filename_out,ios::app);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
//
std::cout << "parsing " << filename << " ...\n";
string line;
int cnt_line=0;
int NUM_OF_CASES;
int num_of_robots=0,num_of_inst;
int cnt_robert=0;
int cnt_do=-1;
bool flag_robert=0,flag_do=0;
vector<ROBOT*> list_robot;
MATRIX<int> m(1,1);
MATRIX<int> * board_ptr=&m;
while(getline(infile,line))
{
cnt_line++;
cout<<"-------------------------------------"<<endl;
cout<<"LINE="<<line<<endl;
if(cnt_line==1)
{
NUM_OF_CASES=stoi(line);
PRINTVAR(NUM_OF_CASES);
}
if(cnt_line==2)
{
stringstream ssin(line);
int width,height;
ssin>>width>>height;
PRINTVAR(width);
PRINTVAR(height);
//MATRIX<int> m(height,width,1);
m.setWidth(width);
m.setHeight(height);
m.fill(1);
}
if(cnt_line==3)
{
stringstream ssin(line);
ssin>>num_of_robots>>num_of_inst;
PRINTVAR(num_of_robots);
PRINTVAR(num_of_inst);
cnt_robert=0;
}
if(cnt_robert!=num_of_robots && cnt_line>3)
{
cnt_robert++;
cout<<"got robert "<<cnt_robert<<": "<<line<<endl;
int t1=stoi(split(line," ")[0])-1;
int t2=stoi(split(line," ")[1])-1;
Point<int> p(t1,t2);
string h=split(line," ")[2];
ROBOT* r=new ROBOT(p,h);
PRINT_DEBUG_INFO();
board_ptr->show();
PRINT_DEBUG_INFO();
r->setBoard(board_ptr);
list_robot.push_back(r);
r->show();
}
if(cnt_robert==num_of_robots && cnt_do<0)
{
cnt_do=0;
}
if(cnt_do!=num_of_inst && cnt_line>3+num_of_robots)
{
cnt_do++;
cout<<"got move "<<cnt_do<<": "<<line<<endl;
auto iv=split(line," ");
int robot_id=stoi(iv[0]);
vector<string>iv2(iv.begin()+1,iv.end());
string cmd=join(iv2);
PRINTVAR(robot_id);
PRINTVAR(cmd);
list_robot[robot_id-1]->exe(cmd);
}
if(cnt_line>=3+num_of_robots+num_of_inst)
{
cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<endl;
for(auto r:list_robot)
r->show();
cout<<"end of case <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<endl;
cnt_line=1;
cnt_do=-1;
}
//cout<<"LINE:"<<endl;
//PRINTVAR(flag_end_of_one_case);
}
// MATRIX<int> m(4,5,1);
// m.show();
// PRINTVAR(m.isOnEdge(1,2));
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
//----------------------------------------------------------
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
outfile.close();
string sss=string(" ")+">>>\t";
int u=3;
PRINT_DEBUG_INFO_PREFIX(u);
//for(int cnt=0;cnt<=100;cnt++)
//{
//float rx=((float)(random()%100))/100;
//float ry=((float)(random()%100))/100;
//cout<<rx<<" "<<ry<<endl;
//}
#endif
}
<file_sep>/cpp/exe_game/tetris/lib.cpp
#include "global.h"
//static void sleep_ms(unsigned int secs)
void sleep_ms(unsigned int secs)
{
struct timeval tval;
tval.tv_sec=secs/1000;
tval.tv_usec=(secs*1000)%1000000;
select(0,NULL,NULL,NULL,&tval);
}
void deleteFromVectorShape(vector<Shape*>* vecPtr, Shape* item)
{
PRINT_DEBUG_INFO_PREFIX("deleteFromVectorShape");
auto vec=*vecPtr;
int size=vec.size();
PRINTVAR(vec.size());
int cntr=0;
for (auto iter=vecPtr->begin();iter!=vecPtr->end();)
{
Shape* t=*iter; // t is Shape*
//int ind=t.transformIsCombined(unit_transforms_wo_zeros);
if (t==item)
{
//cout<<"erase Shape: ("<<item->x<<","<<item->y<<")"<<endl;
//vec.erase(iter); // delete the combined transform
vecPtr->erase(iter);
size=vecPtr->size();
}
else
{
iter++;
}
cntr++;
}
PRINTVAR(vec.size());
}
<file_sep>/java/Assignment6/NameSurfer.java
/*
* File: NameSurfer.java
* ---------------------
* When it is finished, this program will implements the viewer for
* the baby-name database described in the assignment handout.
*/
import acm.graphics.GObject;
import acm.graphics.GPoint;
import acm.program.*;
import acmx.export.javax.swing.JTextField;
import java.awt.event.*;
import java.util.HashMap;
import javax.swing.*;
public class NameSurfer extends Program implements NameSurferConstants {
// in order to pack to JAR:
public static void main(String[] args) {
new NameSurfer().start(args);
}
/* Method: init() */
/**
* This method has the responsibility for reading in the data base
* and initializing the interactors at the top of the window.
*/
public void init() {
// You fill this in, along with any helper methods //
contents = new HashMap<String, GObject>();
createController();
addActionListeners();
// addMouseListeners();
u_NameSurferGraph=new NameSurferGraph();
add(u_NameSurferGraph);
u_NameSurferDataBase=new NameSurferDataBase("names-data.txt");
u_NameSurferGraph.update();
// nse=new NameSurferEntry("Sam 1 2 3 4 5");
// println(nse.toString());
}
/* Creates the control strip at the bottom of the window */
private void createController() {
nameField = new JTextField(MAX_NAME);
nameField.addActionListener(this);
graphButton = new JButton("Graph");
clearButton = new JButton("Clear");
add(new JLabel("Name"), NORTH);
add(nameField, NORTH);
add(graphButton, NORTH);
add(clearButton, NORTH);
}
/* Method: actionPerformed(e) */
/**
* This class is responsible for detecting when the buttons are
* clicked, so you will have to define a method to respond to
* button actions.
*/
public void actionPerformed(ActionEvent e) {
// You fill this in //
Object source = e.getSource();
if (source == graphButton || source == nameField) {
//addBox(nameField.getText());
String name=nameField.getText();
name=name.substring(0, 1).toUpperCase()+name.substring(1);
this.println("Graph: \""+name+"\"");
NameSurferEntry nseOfInputName=u_NameSurferDataBase.findEntry(name);
u_NameSurferGraph.addEntry(nseOfInputName);
// this.println(nseOfInputName.getRank(1900));
this.println(nseOfInputName.toString());
this.println("DONE");
} else if (source == clearButton) {
this.println("Clear");
//removeContents();
}
}
/* Called on mouse press to record the coordinates of the click */
public void mousePressed(MouseEvent e) {
// last = new GPoint(e.getPoint());
// currentObject = getElementAt(last);
}
/* Called on mouse drag to reposition the object */
public void mouseDragged(MouseEvent e) {
}
/* Private constants */
private static final int MAX_NAME = 25;
// private static final double BOX_WIDTH = 120;
// private static final double BOX_HEIGHT = 50;
/* Private instance variables */
private HashMap<String, GObject> contents;
private JTextField nameField;
private JButton graphButton;
private JButton clearButton;
private NameSurferDataBase u_NameSurferDataBase;
private NameSurferGraph u_NameSurferGraph;
// private GObject currentObject;
// private GPoint last;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/4.6.cpp
#include <stdio.h>
#include <iostream>
#include "4.6.h"
#include "lib.h"
using namespace std;
int f4_6 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
for (int ans=1;ans<=10000;ans++) {
double left=ans;
for (int day=1;day<=10;day++) {
//cout<<"DAY "<<day<<"morning, peach left="<<left<<endl;
if (left==1 && day==10) {
cout <<"GET ANSWER: "<<ans<<"----------------"<<endl;
break;
}
left=left/2-1;
//cout<<"DAY "<<day<<"night, peach left="<<left<<endl;
if(left<0) {
//cout<<"got negative, break:"<<left<<endl;
break;
}
if(!is_int(left)) {
//cout<<"got non int, break:"<<left<<endl;
break;
}
}
}
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/python/workspace_python/dive_into_python/src/1/1/1p4_if_for.py
# if
#c=raw_input("input 3 num:")
u=1
v=2
w=3
if u>v and u>w:
print str(u)+" large"
elif w>v and u<w:
print str(w)+" large"
else:
print str(v)+" large"
# for
print ""
print "TEST of for"
t=range(3,14,2)
for i in t:
print i
print ""
print "SUM:"
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print sum
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/include/f13_2.h
void f13_2() ;
void showInfo() ;
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/8.4.h
void f8_4() ;//FUNC
void f_encrypt (char *c,int string_len,char* offset_list,int offset_list_len) ;
void f_decrypt(char*,int);
<file_sep>/cpp/leetcode/Combination_Sum/s.cpp
//#define SIMPLE_LOG
#ifdef SIMPLE_LOG
#define DBG 0
#else
#define DBG 1
#endif
#if (DBG)
#define DLOG(x) cout<<#x<<"="<<x<<" @"<<__LINE__<<endl;
#else
#define DLOG(x)
#endif
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#if (DBG)
#define DENTER \
LVCALL++; PRLVCALL; ::std::cout<<"-->"<<__FUNCTION__<<::std::endl;
#define DRETURN \
PRLVCALL; ::std::cout<<"<--"<<__FUNCTION__<<::std::endl; LVCALL--;
#endif
#define DEBUG_MARK PRINT_DEBUG_INFO()
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define DPRINT(x) \
(::std::cout<<x<<::std::endl )
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define DEBUG_MARK
#define PRINT_DEBUG_INFO_PREFIX(p)
#define DPRINT(x)
#define PRINT_COUT(p)
#define DENTER
#define DRETURN
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <regex>
#include <map>
#include <assert.h>
using namespace std;
#if DBG
static int LV=0;
static int LVCALL=0;
#define PRLV for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLVCALL for(int u12=LVCALL;u12>0;u12--) {std::cout<<" .. ";}
template <class U>
std::ostream & operator <<(std::ostream &os, const std::vector<U> &m)
{
os << std::endl;
PRLV(LV);
os << "->";
os << std::endl;
LV++;
PRLV(LV);
for (const auto &p : m)
{
os << p << ", " ;
}
os << std::endl;
LV--;
PRLV(LV);
os << "<-";
return os;
}
template <class U, class V>
std::ostream & operator <<(std::ostream &os, const std::map<U, V> &m)
{
os << "->";
os << std::endl;
for (const auto &p : m)
{
os << p.first << ": " << p.second;
os << std::endl;
}
os << "<-";
return os;
}
#endif
//=========================================================================================
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
DENTER;
auto r= searchInRange(candidates,target,0);
DRETURN;
return r;
}
vector<vector<int>> search(vector<int>& cand, int target){
DENTER;
if(cand.size()==0)
return {{}};
if(cand[0]>target)
return {{}};
vector<vector<int>> r;
vector<int> oneAns;
int res=target;
int ind=0;
int endInd=cand.size()-1;
DRETURN;
return {{0},{1,2,3}};
}
vector<vector<int>> searchInRange(vector<int>& cand,int target,int from) {
DENTER;
DLOG(from);
DLOG(target);
if(target<cand[from])
{
DRETURN;
return {{-1}};
}
vector<vector<int>> r;
int endInd=cand.size()-1;
if(from==endInd )
{
if(target==cand[endInd])
{
DRETURN;
DLOG(endInd);
return {{endInd}};
}
else
{
DRETURN;
return {{}};
}
}
else
{
// use cand[from]
int newTarget=target-cand[from];
auto newAns=searchInRange(cand,newTarget,from+1);
DLOG(newAns.size());
for(auto v1:newAns)
{
auto v1add=v1;
v1add.push_back(from);
r.push_back(v1add);
}
DLOG(r);
// not use cand[from]
auto newAns2=searchInRange(cand,target,from+1);
DLOG(newAns2.size());
for(auto v1:newAns2)
{
auto v1add=v1;
v1add.push_back(from);
r.push_back(v1add);
}
DLOG(r);
}
DLOG(from);
DLOG(target);
DLOG(r);
DRETURN;
return r;
}
int binSearch(vector<int>& cand, int target,int from,int to){
DENTER;
if(cand[from]>target)
return -1;
if(cand[to]<target)
return -1;
if(from>to)
return -1;
while(1)
{
DLOG(from);
DLOG(to);
if(to-from<5)
{
for(int i=0;i<cand.size();i++)
if(cand[i]==target)
return i;
return -1;
}
int mid=(from+to)/2;
if(cand[mid]==target)
return mid;
else if(cand[mid]>target)
{
to=mid;
}
else //cand[mid]<target
{
from=mid;
}
}
return -1;
}
};
//=========================================================================================
int main ()
{
Solution sol;
vector<int> cand={0,1,2,3,4,5,6,7,8,9,10};
DLOG(cand);
PRINT_VECTOR_hor(cand);
//DLOG(sol.binSearch(cand,13,0,cand.size()-1));
auto ans=sol.combinationSum(cand, 7);
DLOG(ans);
return 0;
}
<file_sep>/cpp/exe_game/tetris/Matrix.class.h
#ifndef MATRIX_CLASS_H
#define MATRIX_CLASS_H
#include <vector>
#include <string>
#include "Shape.class.h"
using namespace std;
class Matrix
{
public:
Matrix(unsigned height,unsigned width,string v="0");
Matrix(vector<vector<string> > m);
int getWidth() {return mWidth;};
int getHeight() {return mHeight;};
void setWidth(int w) {mWidth=w;};
void setHeight(int h) {mHeight=h;};
bool isOnEdge(unsigned row,unsigned col);
bool isOnEdge(int row,int col);
//void addShape(Shape* shape,int ul_row=0, int ul_col=0,string anchor="up");
void addShape(Shape* shape);
void deleteShape(Shape* shape);
Shape* getShape();
void applyShape(Shape* shape);
vector<Shape*> getShapeList(){return shapeList;};
bool tick(); // time++
void clear(); // apply all blank to board
void update(); // apply data to board
vector<vector<string> > getBoard() {return board;};
bool rowIsFull(int row);
bool rowIsEmpty(int row);
void cleanRow(int row);
void print();
bool getAllShapesAreSteady() {return allShapesAreSteady;};
private:
int mWidth;
int mHeight;
vector<vector<string> > board;
// X : blank
// 0 : dot
vector<Shape*> shapeList;
bool allShapesAreSteady;
};
# endif
<file_sep>/cpp/codewar/best_travel/others_time/others.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#define SIMPLE_LOG
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#if(SIMPLE_LOG)
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
#include <vector>
#include <string>
#include <algorithm>
class BestTravel
{
public:
static int chooseBestSum(int t, int k, std::vector<int>& ls);
};
int BestTravel::chooseBestSum(int t, int k, std::vector<int>& ls)
{
PRINT_DEBUG_INFO();
clock_t start, end;
start = clock();
//
unsigned int n = ls.size();
if ((unsigned int)k > n) return -1;
int max = -1, sum;
std::string bitmask(k, 1);
for(auto c:bitmask) { std::string s=c?"1":"0"; std::cout<<s<<"\t"; } PRINT_ENDL();
bitmask.resize(n, 0);
for(auto c:bitmask) { std::string s=c?"1":"0"; std::cout<<s<<"\t"; } PRINT_ENDL();
do {
//for(int i=0;i<bitmask.size();i++)
//PRINT_COUT(bitmask[i]);
for(auto c:bitmask) { std::string s=c?"1":"0"; std::cout<<s<<"\t"; } PRINT_ENDL();
//PRINT_ENDL();
sum = 0;
for (unsigned int i = 0; i < n; ++i)
if (bitmask[i]) sum += ls[i];
if ((sum >= max) && (sum <= t)) max = sum;
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
//
end = clock();
std::cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return max;
}
int main ()
{
//std::vector<int> arr = {17, 0, -4, 3, 15};
//std::vector<int> arr = {3,4,8,9,10};
#if 1
std::vector<int> arr = {91,74,73,73,73,73,73};
std::map<std::vector<int>,int> cache_keep_max;
auto r=BestTravel::chooseBestSum(300,3,arr);
#endif
#if 0
std::vector<int> arr = {1,2,91,74,73,82,71};
std::map<std::vector<int>,int> cache_keep_max;
auto r=BestTravel::chooseBestSum(500,5,arr);
#endif
#if 0
std::vector<int> arr = {100, 76, 56, 44, 89, 73, 68, 56, 64, 123, 2333, 144, 50, 132, 123, 34, 89 };
//std::vector<int> arr = {100, 44, 89, 73, 68, 56, 64, 123, 34, 89 };
auto r=BestTravel::chooseBestSum(500,5,arr);
#endif
#if 0
std::vector<int> arr = { 91,74,73,85,73,81,87};
auto r=BestTravel::chooseBestSum(331,5,arr);
#endif
#if 0
std::vector<int> arr = { 91,74,73,85,73,81,87 };
auto r=BestTravel::chooseBestSum(331,4,arr);
#endif
//PRINTVAR(BestTravel::findLargestOne(std::vector<int>(),100,arr,cache_keep_max));
//PRINT_DEBUG_INFO_PREFIX("================================================");
//std::vector<int> a={1,2,3};
//std::vector<int> b={1,3,2};
//sort(b.begin(),b.end());
//PRINTVAR((a==b));
//PRINT_DEBUG_INFO_PREFIX("================================================");
PRINTVAR(r);
//
//
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/11.5.cpp
#include "include.top.h"
using namespace std;
void f11_5() {
//Queue q;
//q.put(0);
//q.put(1);
//q.put(2);
//q.put(3);
//cout<<"GET:"<<q.get()<<endl;
//cout<<"GET:"<<q.get()<<endl;
//cout<<"GET:"<<q.get()<<endl;
//cout<<"GET:"<<q.get()<<endl;
//cout<<"GET:"<<q.get()<<endl;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/4.2.cpp
#include <iostream>
#include <math.h>
#include <iomanip>
#include <time.h>
#include <stdio.h>
#include "lib.h"
using namespace std;
int main4_2 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
double sum=0;
for (int cnt=1;cnt<=15;cnt++) {
double incr=myfac(cnt);
sum+=incr;
printf("ITER:%20d \tincr:%20.0f \tsum:%20.0f\n",cnt,incr,sum);
}
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/cpp/POJ/src/poj1006.cpp
#include "include.top.h"
#include <math.h>
#include <iomanip>
#include <map>
#include "poj1006.h"
using namespace std;
#include <fstream>
const int T_p=23;
const int T_e=28;
const int T_i=33;
void poj1006 ()
{
cout<<"-----------------------------------------------"<<endl;
cout<<"poj1006"<<endl;
//----------------------------------------------------------
string filename="input/poj1006.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj1006.out";
std::ofstream outfile(filename_out);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
double result;
int p,e,i,d;
int cntr_case=1;
int common_peak=-999;
while (infile >> p >>e >>i >>d)
{
if (p==-1
&& e==-1
&& i==-1
&& d==-1
)
break;
common_peak=calc_next_triple_peak(p,e,i,d);
cout<<"Case "<<cntr_case<<": the next triple peak occurs in "<<common_peak<<" days."<<endl;
outfile<<"Case "<<cntr_case<<": the next triple peak occurs in "<<common_peak<<" days."<<endl;
cntr_case++;
}
outfile<<"====================="<<endl;
//----------------------------------------------------------
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
}
int calc_next_triple_peak (int p_last,int e_last,int i_last,int d_start)
{
for(int j=d_start+1;j<=d_start+T_p*T_i*T_e;j++)
{
#if 0
cout<<j<<":\t";
if(is_divided(j-p_last,T_p))
cout<<"\tp";
if(is_divided(j-e_last,T_e))
cout<<"\te";
if(is_divided(j-i_last,T_i))
cout<<"\ti";
cout<<endl;
#endif
if(is_divided(j-p_last,T_p))
if(is_divided(j-e_last,T_e))
if(is_divided(j-i_last,T_i))
{
//analyze_is_divided(j-p_last,T_p);
//analyze_is_divided(j-e_last,T_e);
//analyze_is_divided(j-i_last,T_i);
//cout<<j<<":\t is the common peak!"<<endl;
return j-d_start;
}
}
}
bool is_divided(int a,int b)
{
return !(a%b);
}
void analyze_is_divided(int a,int b)
{
cout<<a<<"/"<<b<<"="<<a/b<<endl;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/5.2.cpp
#include <stdio.h>
#include <math.h>
#include <iostream>
#include "5.2.h"
#include "lib.h"
using namespace std;
int f5_2 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
cout<<"INTEGRAL= "<<integral(0,1)<<endl;
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
double target_func (double x) {
double y=exp(x)/(1+x*x);
//double y=sin(x);
return y;
}
double integral (double from,double to) {
int n=1;
double h=(to-from)/n;
double t=h/2*(target_func(from)+target_func(to));
double r=t;
double r_next=t,t_next=t;
while(true) {
n*=2;
h=(to-from)/n;
double sigma=0;
for (int j=0;j<=n-1;j++) {
sigma+=target_func(from+h*j+h/2);
}
t_next=t/2+h/2*(sigma);
r=r_next;
r_next=(4*t_next-t)/3;
cout<<"r_next="<<r_next<<endl;
if (fabs(r_next-r)<1e-8) {break;}
}
return r;
}
<file_sep>/cpp/POJ/src/WFF.cpp
#include "include.top.h"
#include "WFF.class.h"
#include <regex>
// WFF=Well-Formed Formula
//static string legalChars="KANCEpqrst";
bool WFF::isLegal()
{
isLegal(0);
}
bool WFF::isLegal(int level)
{
int indent=level;
string prefix="";
while(indent!=0)
{
prefix+=" ";
indent--;
}
//PRINT_DEBUG_INFO();
cout<<prefix<<"calling WFF::isLegal("<<mForm<<","<<level<<")"<<endl;
for (auto c:mForm) // search illegal chars
{
bool flag_match=0;
if(legalChars.find(c)==std::string::npos)
{
cout<<prefix<<"mForm has illegal char:"<<endl;
PRINTVAR(mForm);
//assert(0);
return false;
}
}
// parse Op and Arg
if(mForm.size()==0)
return false;
else if(mForm.size()==1) // only Arg is legal for 1-char0-WFF
{
char c=mForm[0];
if(islower(c))
{
mOp=' ';
cout<<prefix<<"legal:"<<mForm<<endl;
return true;
}
else
{
cout<<prefix<<"illegal:"<<mForm<<endl;
return false;
}
}
else // size >1
{
char c=mForm[0];
if(islower(c)) // first char is not Op && size > 1
{
cout<<prefix<<"illegal:"<<mForm<<endl;
return false;
}
else if(isupper(mForm[mForm.size()-1])) // last char is Op
{
cout<<prefix<<"illegal:"<<mForm<<endl;
return false;
}
else if(c=='N')
{
mOp='N';
//cout<<prefix<<"GOT Op:"<<c<<endl;
WFF* n_sub=new WFF("");
n_sub->setMForm(mForm.substr(1,mForm.size()));
mUnitWFFs.push_back(n_sub);
return n_sub->isLegal(level+1);
}
else // K,A,C,E
{
//cout<<prefix<<"GOT Op:"<<c<<endl;
this->mOp=mForm[0];
for(int ind=mForm.size()-1;ind!=1;ind--)
{
string head=mForm.substr(1,ind-1);
string tail=mForm.substr(ind,mForm.size());
//PRINTVAR(head);
//PRINTVAR(tail);
WFF *h=new WFF("");
WFF *t=new WFF("");
h->setMForm(head);
t->setMForm(tail);
//PRINTVAR(h->getMForm());
//PRINTVAR(h);
//PRINTVAR(t->getMForm());
//PRINTVAR(t);
cout<<prefix;
PRINTVAR_hor(head);
PRINTVAR_hor(tail);
cout<<endl;
if(t->isLegal(level+1)&& h->isLegal(level+1) )
{
cout<<prefix<<"legal:"<<mForm<<endl;
//PRINTVAR(mOp); PRINT_DEBUG_INFO();
//cout<<"h="<<h.getMForm()<<endl;
//cout<<"t="<<t.getMForm()<<endl;
mUnitWFFs.push_back(h);
mUnitWFFs.push_back(t);
PRINTVAR(mUnitWFFs.size());
for(auto i:mUnitWFFs)
i->show();
return true;
}
}
cout<<prefix<<"illegal:"<<mForm<<endl;
return false;
} // K,A,C,E
} // size >1
}
void WFF::show()
{
cout<<mForm<<endl;
}
void WFF::showMUnitWFFs(int indent)
{
if (mForm.size()>1) {
string prefix="";
while(indent!=0)
{
prefix+=" ";
indent--;
}
//cout<<prefix<<"*"<<mForm<<"*"<<endl;
cout<<prefix<<"*"<<mForm<<"=\t";
//PRINTVAR(this->getMForm());
cout<<prefix<<this->mOp<<":\t";
for(auto w:mUnitWFFs)
cout<<prefix<<w->getMForm()<<"\t";
cout<<endl;
//PRINTVAR(mUnitWFFs.size());
//for(auto i:mUnitWFFs)
//i->show();
for(auto w:mUnitWFFs)
{
w->showMUnitWFFs(indent+1);
}
cout<<endl;
}
}
#if 0
void WFF::breakIntoUnitWFFs()
{
cout<<"calling func breakIntoUnitWFFs("<<mForm<<")"<<endl;
if(mForm.size()==1 && islower(mForm[0]))
{
//mUnitWFFs=0;
return ;
}
else if(mForm[0]=='N')
{
WFF* t=new WFF();
t->setMForm(mForm.substr(1,mForm.size()));
mUnitWFFs.push_back(t);
t->breakIntoUnitWFFs();
// zjc
}
else{
string s="KACE";
if(s.find(mForm[0]))
{
WFF *h=new WFF();;
WFF *t=new WFF();;
for(int ind=mForm.size();ind!=1;ind--)
{
string head=mForm.substr(1,ind-1);
string tail=mForm.substr(ind,mForm.size());
h=head;
t=tail;
PRINTVAR_hor(head);
PRINTVAR_hor(tail);
cout<<endl;
//h.show();
//t.show();
//cout<<endl;
if(h.isLegal() && t.isLegal())
{
cout<<"head and tail are both legal, break!"<<endl;
break;
}
}
mUnitWFFs.push_back(h);
mUnitWFFs.push_back(t);
}
else
{
assert(0);
}
}
cout<<"mUnitWFFs:"<<endl;
for(auto w:mUnitWFFs)
w.show();
for(auto w:mUnitWFFs)
w.breakIntoUnitWFFs();
}
#endif
bool WFF::calcValue(string cond)
{
bool r;
if(mForm.size()==1)
{
int ind=cond.find(mForm);
r=cond[ind+1]=='1'?1:0;
//PRINTVAR_hor(r);
//PRINTVAR_hor(mForm);
//PRINTVAR_hor(cond);
//cout<<endl;
return r;
}
assert(legalChars.find(mOp)!=std::string::npos && isupper(mOp));
if(mOp=='N')
{
assert(mUnitWFFs.size()==1);
r= !mUnitWFFs[0]->calcValue(cond);
}
else if(mOp=='K')
{
assert(mUnitWFFs.size()==2);
bool u=mUnitWFFs[0]->calcValue(cond);
bool v=mUnitWFFs[1]->calcValue(cond);
r= u&&v;
}
else if(mOp=='A')
{
assert(mUnitWFFs.size()==2);
bool u=mUnitWFFs[0]->calcValue(cond);
bool v=mUnitWFFs[1]->calcValue(cond);
r= u||v;
}
else if(mOp=='C')
{
assert(mUnitWFFs.size()==2);
bool u=mUnitWFFs[0]->calcValue(cond);
bool v=mUnitWFFs[1]->calcValue(cond);
r= !u&&v;
}
else if(mOp=='E')
{
assert(mUnitWFFs.size()==2);
bool u=mUnitWFFs[0]->calcValue(cond);
bool v=mUnitWFFs[1]->calcValue(cond);
r= u==v;
}
//PRINTVAR_hor(r);
//PRINTVAR_hor(mForm);
//PRINTVAR_hor(cond);
//cout<<endl;
return r;
}
vector<string> WFF::genTestPatterns()
{
vector<string> patterns;
string primes;
for(auto c:mForm)
{
if(islower(c) && primes.find(c)==std::string::npos)
primes.push_back(c);
}
//PRINTVAR(primes);
string v_pattern;
for(auto c:primes)
{
v_pattern+='0';
}
//PRINTVAR(v_pattern);
string all0=v_pattern;
string all1=std::regex_replace(all0,std::regex("0"),"1");
//PRINTVAR(all0);
//PRINTVAR(all1);
while(true)
{
// gen mix
string mix="";
for(int ind=0;ind!=primes.size();ind++)
{
mix+=primes[ind];
mix+=v_pattern[ind];
}
sort(primes.begin(),primes.end());
//PRINTVAR(mix);
patterns.push_back(mix);
//---------
// judge and break
//PRINTVAR(v_pattern);
if(v_pattern==all1)
break;
//-- v_pattern++
for(int ind=v_pattern.size()-1;ind!=-1;ind--)
{
if(v_pattern[ind]=='0')
{
v_pattern[ind]='1';
break;
}
else
{
v_pattern[ind]='0';
}
}
//---
}
//PRINTVAR(patterns.size());
//PRINT_VECTOR(patterns);
return patterns;
}
vector<int> findAllMatchesInString(string str,string subStr)
{
int pos=str.find(subStr);
vector<int> positions;
while(pos!=string::npos)
{
positions.push_back(pos);
pos=str.find(subStr,pos+1);
}
return positions;
}
vector<int> findAllUpperLetterInString(string str)
{
vector<int> positions;
for(auto it=str.begin();it!=str.end();it++)
{
if(isupper(*it))
positions.push_back(it-str.begin());
}
return positions;
}
<file_sep>/cpp/ch12_6.cpp/Tdate.h
#include <iostream>
#include <math.h>
using namespace std;
class Tdate {
public:
Tdate();
Tdate(int d);
Tdate(int m, int d);
Tdate(int m,int d,int y);
protected:
int month;
int day;
int year;
};
Tdate::Tdate() {
month=1;
day=1;
year=1900;
}
<file_sep>/tcl/book_Practical_Programming_in_Tcl_Tk/ch44/zjc.sh
g++ random.c -I/home/zz/Downloads/tcl8.6.10/generic/ > compile.log
#g++ ~/Downloads/tcl8.6.10/generic/tclTest.c -I/home/zz/Downloads/tcl8.6.10/generic/ > compile.log
# gcc ~/Downloads/tcl7.6.10/generic/tclTest.c -I/home/zz/Downloads/tcl8.6.10/generic/ \
# -I/home/zz/Downloads/tcl8.6.10/unix/ \
# > compile.log
<file_sep>/cpp/case/include/poj1328.h
#ifndef POJ1328_H
#define POJ1328_H
#include "include.top.h"
#include "gnuplot_i.h"
class Point
{
public:
Point() {loc={0,0};D=0;};
Point(float x,float y)
{
loc={x,y};
D=0;
};
Point(float x,float y,float d)
{
loc={x,y};
D=d;
};
void setLoc(float x,float y){
//loc=make_pair(x,y);
loc={x,y};
};
void setD(float d) {D=d;};
float getD() {return D;};
pair<float,float> getLoc(){
return loc;
}
float getX () const { return loc.first; };
float getY () const { return loc.second; };
void show() {
cout<<"Point\t("<<getX()<<",\t"<<getY()<<"), D="<<D<<endl;
}
pair<float,float> getXCover(float) ;
bool coverPointOnXAxis(Point targetP) { // this point covers the targetP(type=coverPointOnXAxis) on x-axis
pair<float,float> cover=getXCover(D) ;
if(targetP.getX()>=cover.first && targetP.getX()<=cover.second)
{
return true;
}
return false;
};
friend ostream& operator<< (ostream& os, Point rhs) {
os<<"Point\t("<<rhs.getX()<<",\t"<<rhs.getY()<<"), D="<<rhs.getD()<<endl;
return os;
};
private:
pair<float,float> loc;
float D;
};
class PointOnXAxis:public Point
{
public:
PointOnXAxis():Point(){};
PointOnXAxis(float x,float y):Point(x,(float)0){};
PointOnXAxis(float x):Point(x,(float)0){};
bool isLeftBoardOfCoverage;
bool operator< (const PointOnXAxis rhs) const {return getX()<rhs.getX();};
//void coverIslandsPushBack(Point p){coverIslands.push_back(p);};
vector<Point> coverIslands;
private:
};
class Case
{
public:
int N;
float D;
//pair<float,float> coord;
vector<Point> islands;
vector<PointOnXAxis> radars;
vector<pair<float,float>> covers;
void show();
void solve();
bool checkLegality();
};
void poj1328();
std::vector<std::string> split(std::string str,std::string pattern) ;
void show(vector<pair<float,float>>) ;
void wait_for_key(); // Programm halts until keypress
class GUI
{
public :
GUI(){
GUI_DRAW_NPOINTS=50;
Gnuplot g("GUI");
g.reset_all();
g.reset_plot();
g.set_grid();
try {
}
catch (GnuplotException ge)
{
cout << ge.what() << endl;
}
};
void drawCircle(double xc,double yc,double r,string style,string info);
void drawPoint(Point p);
int GUI_DRAW_NPOINTS;
private:
Gnuplot g;
};
#endif
<file_sep>/python/workspace_python/dive_into_python/src/1/excel/excel_rd.py
import xlrd
data=xlrd.open_workbook('D:\workspace_python\exe.xlsx')
table=data.sheets()[0]
nrows=table.nrows
ncols=table.ncols
for i in range(nrows):
print table.row_values(i)
cell_A1=table.cell(0,0).value
print cell_A1
import xlrd
import xlwt
from datetime
def testXlrd(filename):
book=xlrd.open_workbook(filename)
sh=book.sheet_by_index(0)
print "Worksheet name(s): ",book.sheet_names()[0]
print 'book.nsheets',book.nsheets
print 'sh.name:',sh.name,'sh.nrows:',sh.nrows,'sh.ncols:',sh.ncols
print 'A1:',sh.cell_value(rowx=0,colx=1)
#如果A3的内容为中文
print 'A2:',sh.cell_value(0,2).encode('gb2312')
def testXlwt(filename):
book=xlwt.Workbook()
sheet1=book.add_sheet('hello')
book.add_sheet('word')
sheet1.write(0,0,'hello')
sheet1.write(0,1,'world')
row1 = sheet1.row(1)
row1.write(0,'A2')
row1.write(1,'B2')
sheet1.col(0).width = 10000
sheet2 = book.get_sheet(1)
sheet2.row(0).write(0,'Sheet 2 A1')
sheet2.row(0).write(1,'Sheet 2 B1')
sheet2.flush_row_data()
sheet2.write(1,0,'Sheet 2 A3')
sheet2.col(0).width = 5000
sheet2.col(0).hidden = True
book.save(filename)
if __name__=='__main__':
testXlrd(u'你好。xls')
testXlwt('helloWord.xls')
base=datetime.date(1899,12,31).toordinal()
tmp=datetime.date(2013,07,16).toordinal()
print datetime.date.fromordinal(tmp+base-1).weekday()
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN_good/src/2.1_func.cpp
#include "include.top.h"
using namespace std;
int f_test_linear_list() {
int u[5]={101,77,303,7,21};
MyList l0(u,23,"l0");
//MyList l0(u,23);
cout<<l0.ListLength()<<endl;
//return 0;
MyList l1(u,5,"l1");
MyList lX(l1);
l1.PrintList(5);
l1.PrintList(5,true);
cout<<"LENGTH="<<l1.ListLength()<<endl;
cout<<"GET ELEMENT="<<l1.GetElem(4)<<endl;
if (0) {
cout<<"ClearList..."<<endl;
l1.ClearList();
cout<<"GET ELEMENT="<<l1.GetElem(4)<<endl; // will cause segment fault
}
cout<<"LocateElem:"<<endl;
cout<<l1.LocateElem(3,compare)<<endl;
cout<<"copy constructor:============"<<endl;
MyList ltemp(l1);
l1.PrintList(-1,true);
ltemp.PrintList(-1,true);
//return 0;
cout<<"PriorElem:============"<<endl;
cout<<l1.PriorElem(7)<<endl;
printf("NextElem:===================\n");
cout<<l1.NextElem(1)<<endl;
printf("ListInsert:===================\n");
l1.PrintList(-1,true);
l1.ListInsert(5,999);
l1.PrintList(-1,true);
//return 0;
printf("ListDelete:===================\n");
l1.PrintList(-1,true);
l1.ListDelete(5);
l1.PrintList(-1,true);
printf("ListTraverse,pre_order:===================\n");
l1.ListTraverse(visit);
printf("ListTraverse,post_order:===================\n");
l1.ListTraverse(visit,false);
printf("ListPush:=========\n");
l1.PrintList(-1);
l1.ListPush(9);
l1.ListPush(8);
l1.ListPush(7);
l1.PrintList(-1);
printf("ListPop:=========\n");
l1.PrintList(-1);
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
l1.PrintList(-1);
printf("ListUnion:=========\n");
return 0;
l1.PrintList(-1);
int v[5]={33,44,55,66,77};
MyList l2(v,5,"l2");
l2.PrintList(-1);
MyList lunion(v,5,"lunion");
l1.ListUnion(l2,lunion);
lunion.PrintList(-1);
return 0;
printf("ListSwap:=========\n");
l1.PrintList(-1);
l1.ListSwap(0,1);
l1.PrintList(-1);
printf("ListSort:=========\n");
l1.ListPush(-3);
l1.ListPush(-5);
l1.PrintList(-1);
l1.ListSort();
l1.PrintList(-1);
printf("ListReverse:=========\n");
l1.PrintList(-1);
l1.ListReverse();
l1.PrintList(-1);
l1.ListSort();
l1.PrintList(-1);
printf("HeapRealloc:==========\n");
MyList l3(v,15,"l3");
l1.PrintList(-1);
l1.ListPush(1);
l1.ListPush(1);
l1.ListPush(1);
l1.ListPush(1);
return 0;
}
bool compare(int a,int b)
{
//if (a==b){return true;}
//return false;
return (a==b);
}
bool visit(int *a)
{
printf("visit (%x)%d\n",a,*a);
}
<file_sep>/python/workspace_python/use_baidu/search.py
# coding=utf-8
import urllib2
#import string
#import urllib
import HTMLParser
import re
import gl
def my_urlencode(str1):
reprStr = repr(str1).replace(r'\x','%')
return reprStr[1:-1]
def clearTag(text):
p = re.compile(u'<[^>]+>')
retval = p.sub("",text)
return retval
def get_res_list_and_next_page_url(target_url):
res = urllib2.urlopen(target_url)
html=res.read()
file_object = open('thefile.html','w')
file_object.write(html)
#content = unicode(html, 'utf-8','ignore')
#zjc:
# html_parser=HTMLParser.HTMLParser()
# txt=html_parser.unescape(html)
# print txt
#获取res_list
# pattern = re.compile(r'<table.*?class="result".*?>[\s\S]*?</table>')#大部分情况
pattern = re.compile(r'><em>.*<\em>')#大部分情况
resList_1 = pattern.findall(html)
print 'resList_1'
for i in resList_1:
print i+'\n'
file_object.write('DEBUG')
file_object.writelines(resList_1)
pattern = re.compile(r'<div class="result-op c-container.*?>[\s\S]*?</div>.*?</div>')#少数情况
resList_2 = pattern.findall(html)
res_lists = resList_1 + resList_2 #合并搜索结果
file_object.close( )
#获取next_page_url
pattern = re.compile(r'<p id="page".*?>[\s\S]*</p>')
m = pattern.search(html)
if m:
t = m.group()
pattern = re.compile(r'<a href=".*?"')
mm = pattern.findall(t)
tt = mm[len(mm)-1]
tt = tt[9:len(tt)-1]
next_page_url = 'http://www.baidu.com'+tt
return res_lists,next_page_url
def get_title(div_data):
pattern = re.compile(r'<a[\s\S]*?>.*?<em>.*?</em>')
m = pattern.search(div_data)
if m:
title = clearTag(m.group(0).decode('utf-8').encode('gb18030'))
pattern = re.compile(r'</em>.*?</a>') #加?号是最小匹配
m=pattern.search(div_data)
if m:
title += clearTag(m.group(0).decode('utf-8').encode('gb18030'))
return title.strip()
def get_url(div_data):
pattern = re.compile(r'mu="[\s\S]*?"')
m = pattern.search(div_data)
if m: #mu模式
url = m.group(0)
url = url.replace("mu=","")
url = url.replace(r'"',"")
else: #href模式
pattern = re.compile(r'href="[\s\S]*?"')
mm = pattern.search(div_data)
if mm:
url = mm.group(0)
url = url.replace("href=","")
url = url.replace(r'"',"")
return url
def get_abstract(div_data):
pattern = re.compile(r'<div class="c-abstract">[\s\S]*?</div>')
m = pattern.search(div_data)
if m: #普通模式
abstract=clearTag(m.group(0))
else: #奇怪模式1,貌似是外国网站
pattern = re.compile(r'<div class="op_url_size".*?</div>')
mm = pattern.search(div_data)
if mm:
abstract=clearTag(mm.group(0))
else:#奇怪模式2,貌似是百科等自己的,反正和别人用的不是一个div class~
pattern = re.compile(r'<div class="c-span18 c-span-last">[\s\S]*?</p>')
mmm = pattern.search(div_data)#这里用match和search结果不一致
#match是从字符串的起点开始做匹配,而search是从字符串做任意匹配。
if mmm:
abstract=clearTag(mmm.group(0))
else:
abstract="No description!"
#print i
return abstract.strip()
if __name__ == "__main__":
#初始化
#keyword = raw_input('Please enter the keyword you want to search:')
s=['中文','甲','乙','丙','丁']
for i in s:
gl.printGB (i+'\n')
gl.printGB (my_urlencode(i))
gl.printGB ('\n')
keyword = '望京'
#url = 'http://www.baidu.com/s?wd=' + my_urlencode(keyword) + '&rsv_bp=0&rsv_spt=3&rsv_n=2&inputT=6391'
url= 'http://bj.lianjia.com/ershoufang/rs'+my_urlencode(keyword)
#url = 'http://www.baidu.com/s?q1='+kwAll+'&q2='+kwFull+'&q3='+kwAny1+'+'+kwAny2+'&q4='+kwExclude+'&rn=10'+'&lm=1'+'&ct=1'+'&ft=&q5=&q6='+www.sohu.com+'&tn=baiduadv'
target_urls = []
target_urls.append(url)
page_num = 1 #想多少页就多少页。。只要你有。。
for cnt in range(page_num):
gl.printGB ("=============== 第 %s 页 ==============="%(cnt+1))
if target_urls[cnt] == "END_FLAG":
break
res_lists,next_page_url = get_res_list_and_next_page_url(target_urls[cnt])
if next_page_url: #考虑没有“下一页”的情况
target_urls.append(next_page_url)
else:
target_urls.append("END_FLAG")
titles = []
urls = []
abstracts = []
for index in range(len(res_lists)):
print "第",index+1,"个搜索结果..."
#获取title
title = get_title(res_lists[index])
titles.append(title)
print "标题:",title
#获取URL
url = get_url(res_lists[index])
urls.append(url)
print "URL:",url
#获取描述
abstract = get_abstract(res_lists[index])
abstracts.append(abstract)
print "概要:",abstract
print "\r\n\r\n"
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/5.1.cpp
#include <stdio.h>
#include <math.h>
#include <iostream>
#include "5.1.h"
#include "lib.h"
using namespace std;
int f5_1 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
for(int i=1;i<=1000;i++) {
if(is_prime(i)) {
cout<<i<<"\tis prime!"<<endl;
}
}
//cout<<is_prime(6)<<endl;
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/4.2.h
int main4_2 () ;
<file_sep>/tcl/tcl_call_cpp/2_swig/zjc.sh
/usr/bin/tclsh test.tcl
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/4.10.cpp
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <iomanip>
#include "4.10.h"
#include "lib.h"
using namespace std;
int f4_10 (int year) {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
cout<<"------------------------"<<endl;
int sum=1;
int count_of_birthable=0;
int sum_old1=0;
int sum_old2=0;
int sum_old3=0;
int sum_old4=0;
int sum_old5=0;
for (int n=0;n<=year;n++) {
//if (n>=4) {
// count_of_birthable=1;
//}
int new_birth_of_4_years_ago=sum_old4-sum_old5;
count_of_birthable+=new_birth_of_4_years_ago;
sum+=count_of_birthable;
cout<<"the head of year"<<setw(4)<<n<<" sum:"<<sum<<" count_of_birthable:"<<count_of_birthable<<endl;
cout<<setw(5)
<<"_"<<sum
<<"_"<<sum_old1
<<"_"<<sum_old2
<<"_"<<sum_old3
<<"^"<<sum_old4
<<"_"<<sum_old5
<<"_"<<endl;
sum_old5=sum_old4;
sum_old4=sum_old3;
sum_old3=sum_old2;
sum_old2=sum_old1;
sum_old1=sum;
}
cout<<"------------------------"<<endl;
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/5.6.h
double poly(double n, double x) ;
void f5_6() ;
<file_sep>/cpp/5_BOOK_CPP_PRIMER/include/ch3.h
void ch3();
<file_sep>/tcl/tcl_call_cpp/3/fract.c
double myfract(int n)
{
double res=1.0;
int j;
for (j=1;j<=n;j++)
{
res *= j;
}
return(res);
}
<file_sep>/python/workspace_python/basic_algorithm_of_python/solve_resolution.py
__author__ = 'jc'
freshWaterAmount=10;
clothWaterRemain=10;
powderAmount=1000;
totalStep=10000;
freshWaterAmountPerStep=freshWaterAmount/totalStep;
densityList=[];
powderLeft=powderAmount
currentDensity=powderLeft/clothWaterRemain;
densityList.append(currentDensity)
for i in range(totalStep):
print("ITER:"+str(i))
nextDensity=clothWaterRemain*currentDensity/(clothWaterRemain+freshWaterAmountPerStep)
print("DENSITY "+str(currentDensity)+' -> '+str(nextDensity))
currentDensity=nextDensity
print(str(1000**0.5))<file_sep>/python/workspace_python/dive_into_python/src/1/1/group.py
def f():
pass
def check_group(subset,f):
for i in subset:
for j in subset:
for k in subset:
if f(f(i,j),k)!=f(i,f(j,k)):
print ("combination rule is not match to: %d %d %d",i,j,k)
print ("f(i,j) is %d",f(i,j))
print ("f(j,k) is %d",f(j,k))
print ("f(i,j) is %d",f(i,j))
print ("f(i,j) is %d",f(i,j))
return False
return True
# MAIN:
subset=[0,1]
def f1(a,b):
u=[
[0,0],
[0,0],
]
u[0][0]=1
u[0][1]=1
u[1][0]=0
u[1][1]=1
return u[a][b]
#print f1(*subset)
print check_group(subset,f1)<file_sep>/cpp/5_BOOK_CPP_PRIMER/src/ch3.cpp
#include "include.top.h"
//using std::string;
using namespace std;
void ch3(){
string s="hello CH3!";
PRINTVAR(s);
for(int i=0;i<=10;i++) {
string s2(i,'*');
cout<<""<<s2<<""<<endl;
}
}
<file_sep>/cpp/ex3.4/run.sh
g++ hello_world.cpp
<file_sep>/cpp/POJ/include/poj1860.h
#ifndef POJ1860_H
#define POJ1860_H
#include "include.top.h"
#include "gnuplot_i.h"
//#include "gnuplot_i.new.hpp"
void poj1860();
#endif
<file_sep>/cpp/sort_algorithms/src/main.cpp
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include "1_bubble_sort.h"
#include "lib.h"
#include <list>
#include <algorithm>
#include <string>
#include <vector>
#include <numeric>
using namespace std;
int PrintIt (string& StringToPrint) {
cout <<StringToPrint <<" ";
}
int main() {
cout<<"Hello world!"<<endl;
int MAX_TRY_RUN=1000;
int LIST_LENGTH=20;
int max_assign_cnt=0;
int max_cmpr_cnt=0;
//int * list_that_caused_max_assign_cnt;
list <string> list_assign_cnt_str;
list <int> list_assign_cnt,list_cmpr_cnt;
//ms.push_back("v0");
for (int i=0;i<MAX_TRY_RUN;i++) {
int r_cnt[3];
func_1_bubble_sort(r_cnt,LIST_LENGTH,i);
int curr_cmpr_cnt=r_cnt[0];
int curr_assign_cnt=r_cnt[1];
//stringstream ss;
//ss<<curr_assign_cnt;
//string curr_assign_cnt_str=ss.str();
list_cmpr_cnt.push_back(curr_cmpr_cnt);
list_assign_cnt.push_back(curr_assign_cnt);
string curr_assign_cnt_str=int2string(curr_assign_cnt);
list_assign_cnt_str.push_back(curr_assign_cnt_str);
if (max_assign_cnt<curr_assign_cnt ) {max_assign_cnt=curr_assign_cnt;}
if (max_cmpr_cnt<curr_cmpr_cnt ) {max_cmpr_cnt=curr_cmpr_cnt;}
}
//int* r=gen_rand_array_int(0,3);
//for(int i=0;i<=8;i++) {
// cout<<r[i]<<" ";
//}
//cout<<endl;
for_each(list_assign_cnt_str.begin(),list_assign_cnt_str.end(),PrintIt);
cout<<endl;
double avg_assign_cnt=0;
double avg_cmpr_cnt=0;
avg_assign_cnt=std::accumulate(list_assign_cnt.begin(),list_assign_cnt.end(),0.0)/ list_assign_cnt.size();
avg_cmpr_cnt=std::accumulate(list_cmpr_cnt.begin(),list_cmpr_cnt.end(),0.0)/ list_cmpr_cnt.size();
cout<<"LIST_LENGTH="<<LIST_LENGTH<<endl;
cout<<"max_cmpr_cnt="<<max_cmpr_cnt<<endl;
cout<<"avg_cmpr_cnt="<<avg_cmpr_cnt<<endl;
cout<<"max_assign_cnt="<<max_assign_cnt<<endl;
cout<<"avg_assign_cnt="<<avg_assign_cnt<<endl;
return 0;
}
//int main (void) {
// list <string> ms;
// ms.push_back("v0");
// ms.push_back("v1");
// for_each(ms.begin(),ms.end(),PrintIt);
//}
<file_sep>/cpp/POJ/include/poj2109.h
#ifndef POJ2109_H
#define POJ2109_H
#include "include.top.h"
#include "bigInt.h"
//#include "gnuplot_i.h"
typedef BigInt::Rossi R;
void poj2109();
int solve_root(R& ans,BigInt::Rossi p,int n,R p1=R(0),R p2=R(0));
R pow(int k , int n);
R pow(R k , int n);
R pow(int k , R n);
#endif
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/4.1.cpp
#include <iostream>
#include <math.h>
#include <iomanip>
#include <time.h>
#include <stdio.h>
#include "lib.h"
using namespace std;
int main4_1 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
double now =calc_use_do (1,1e-8);
double ideal=calc_use_do (1,1e-14);
double diff=ideal-now;
cout<<ideal<<endl;
printf("%e = %e - %e \n",diff,ideal,now);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch1_life_game/include/life.h
#include <utility.h>
class Life {
public:
Life(int ,int );
void update();
void init();
void make_live(int,int);
void make_dead(int,int);
void show();
void show_neighbour_cnt();
void update_neighbour_cnt();
int calc_neighbour_cnt(int,int);
protected:
int width;
int cout_table_width;
int height;
int SHOW_WIDTH;
int SHOW_HEIGHT;
int origin_col;
int origin_row;
int big_col;
int big_row;
bool matrix[100][100];
int neighbour_cnt[100][100];
};
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/9.1.cpp
#include <iostream>
#include "include.top.h"
using namespace std;
const int size=10;
#if 0
int f9_1()
{
int a[size];
int n=0;
unsigned seed=(unsigned)time(NULL)*1000;
srand(seed);
cout<<"please input:"<<size<<"datas:"<<endl;
for(int i=0;i<size;i++)
{
//cin>>a[i];
a[i]=rand()%100;
cout<<a[i]<<", ";
}
cout<<endl;
//findmax_use_ptr(a,size,0,&n);
int(&a_ref)[size]=a; //<==> reference an array!
//findmax_use_ref(a_ref[size],size,0,&n);
findmax_use_ref(a_ref,size,0,&n);
cout<<"max:"<<a[n]<<"index:"<<n<<endl;
return 0;
}
void findmax_use_ptr(int*a,int size, int i, int*pk)
{
if(i<size)
{
if(a[i]>a[*pk])
{
*pk=i;
}
findmax_use_ptr(a,size,i+1,&(*pk));
}
}
void findmax_use_ref(int(&a)[size],int size, int i, int&pk)
{
//if(i<size)
//{
// if(a[i]>a[pk])
// {
// pk=i;
// }
// findmax_use_ptr(a,size,i+1,pk);
//}
}
#endif
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/Cat.h
class Cat
{
public:
int GetAge();
void SetAge(int age);
void Meow();
protected:
int itsAge;
};
<file_sep>/cpp/case/src/poj1328.cpp
#include "include.top.h"
#include "gnuplot_i.h"
#include "poj1328.h"
#include <math.h>
#include <iomanip>
#include <map>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__)
#include <conio.h> //for getch(), needed in wait_for_key()
#include <windows.h> //for Sleep()
void sleep(int i) { Sleep(i*1000); }
#endif
#define SLEEP_LGTH 2 // sleep time in seconds
//#include <boost/chrono/chrono_io.hpp>
//#include <boost/chrono/floor.hpp>
//#include <boost/chrono/round.hpp>
//#include <boost/chrono/ceil.hpp>
//using namespace boost;
#include <fstream>
using namespace std;
void poj1328 ()
{
cout<<"-----------------------------------------------"<<endl;
cout<<"poj1328"<<endl;
//----------------------------------------------------------
string filename="input/poj1328.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj1328.out";
// clean the file "output/poj1328.out"
std::ofstream outfile_init(filename_out);
outfile_init.close();
std::ofstream outfile(filename_out,ios::app);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
float a,b;
float x,y,r;
int n;
bool flag_end_of_one_case=false;
bool flag_start_of_one_case=true;
string line;
//while(infile >> line)
vector<Case> cases;
Case c;
Point p;
float D;
while(getline(infile,line))
{
//cout<<"LINE:"<<endl;
PRINTVAR(line);
//PRINTVAR(flag_end_of_one_case);
if (line == "") // end of one case
{
flag_end_of_one_case=true;
}
else
{
float a=stof(split(line," ")[0]);
float b=stof(split(line," ")[1]);
if(a==0 && b==0)// end
break;
if(flag_start_of_one_case)
{
cout<<"NEW CASE HERE!"<<endl;
int N=a;
D=b;
PRINTVAR(N);
PRINTVAR(D);
c.N=N;
c.D=D;
cases.push_back(c);
}
else
{
// body:
p.setLoc(a,b);
float d=cases[cases.size()-1].D;
p.setD(d);
cases[cases.size()-1].islands.push_back(p);
}
if(flag_end_of_one_case)
{
flag_end_of_one_case=false;
}
}
flag_start_of_one_case=flag_end_of_one_case;
}
for (auto c:cases)
c.show();
for (auto c:cases)
{
//if(!c.checkLegality())
//{
// std::cout << "Error: illegal! " << " \n";
// return;
//}
assert(c.checkLegality());
c.solve();
}
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
//----------------------------------------------------------
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
outfile.close();
}
//--------------------------------------
// DEF
std::vector<std::string> split(std::string str,std::string pattern)
{
std::string::size_type pos;
std::vector<std::string> result;
string str_bk=str,str_no_repeat_blank;
//PRINTVAR(str);
for (auto it=str.begin();it!=str.end();it++)
{
if(it!=str.begin() && *it==' ' && *(it-1)==' ')
;
else
str_no_repeat_blank+=*it;
}
//PRINTVAR(str_no_repeat_blank);
str=str_no_repeat_blank;
str+=pattern;
int size=str.size();
for(int i=0; i<size; i++)
{
pos=str.find(pattern,i);
if(pos<size)
{
std::string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+pattern.size()-1;
}
}
return result;
}
void Case::show() {
cout<<"case.show()"<<endl;
cout<<"-----------------------------------------------"<<endl;
PRINTVAR(N);
PRINTVAR(D);
cout<<"islands:"<<endl;;
for (auto i:islands)
i.show();
cout<<"radars:"<<endl;;
for (auto i:radars)
{
i.show();
}
cout<<"-----------------------------------------------"<<endl;
};
void Case::solve() {
PRINT_DEBUG_INFO();
cout<<"get covers:"<<endl;
for(Point i:islands)
{
auto c=i.getXCover(D);
covers.push_back(c);
i.show();
cout<<"\tcover: ("<<c.first<<",\t"<<c.second<<")"<<endl;
}
//::show(covers);
vector<Point> islands_left=islands;
while (islands_left.size()!=0) {
//----------------------
// update covers_left
vector<pair<float,float>> covers_left;
for(Point i:islands_left)
{
auto c=i.getXCover(D);
covers_left.push_back(c);
}
PRINTVAR(covers_left.size());
//----------------------
// gen xAxis
multimap<PointOnXAxis,int> xAxis;
for(auto c:covers_left)
{
PointOnXAxis leftBoard(c.first);
PointOnXAxis rightBoard(c.second);
leftBoard.isLeftBoardOfCoverage=true;
rightBoard.isLeftBoardOfCoverage=false;
xAxis.insert(pair<PointOnXAxis,int>(leftBoard,0));
xAxis.insert(pair<PointOnXAxis,int>(rightBoard,0));
}
//----------------------
cout<<"***************************************"<<endl;
cout<<"SHOW xAxis:"<<endl;
cout <<"cntr\tisLeftBoardOfCoverage\tPointOnXAxis"<<endl;
int cntr=0;
for(auto x:xAxis)
{
PointOnXAxis f=x.first;
if (f.isLeftBoardOfCoverage)
cntr++;
else
cntr--;
x.second=cntr;
cout
<<x.second <<":\t"
<<f.isLeftBoardOfCoverage <<":\t"
<<f<<":\t"
<<"\n";
}
//----------------------
cout<<"***************************************"<<endl;
cout<<"find peak point on xAxis(PPOX):"<<endl;
cntr=0;
int cntr_max=0;
PointOnXAxis peak_point;
for(auto x:xAxis)
{
PointOnXAxis f=x.first;
if (f.isLeftBoardOfCoverage)
cntr++;
else
cntr--;
if(cntr>cntr_max)
{
cntr_max=cntr;
peak_point=f;
}
x.second=cntr;
}
PRINTVAR(cntr_max);
PRINTVAR(peak_point);
peak_point.setD(D);
//----------------------
cout<<"***************************************"<<endl;
cout<<"find Points covering PPOX:"<<endl;
vector<Point> gotCoveringPoints;
for (auto island:islands_left)
{
if(island.coverPointOnXAxis(peak_point))
{
PRINTVAR(island);
gotCoveringPoints.push_back(island);
}
}
//----------------------
// store covered islands into radar
for (auto i:gotCoveringPoints)
{
peak_point.coverIslands.push_back(i);
}
radars.push_back(peak_point);
//----------------------
cout<<"***************************************"<<endl;
cout<<"remove Points covering PPOX:"<<endl;
cout<<"BEFORE:"<<islands_left.size()<<endl;
for(auto iter=islands_left.begin();iter!=islands_left.end();)
{
bool flag_get=false;
auto curIsland=*iter;
for(auto g:gotCoveringPoints)
{
if(curIsland.getX()==g.getX() &&curIsland.getY()==g.getY())
flag_get=true;
}
if (flag_get)
islands_left.erase(iter);
else
iter++;
}
cout<<"AFTER:"<<islands_left.size()<<endl;
cout<<"***************************************"<<endl;
//----------------------
}
cout<<"***************************************"<<endl;
cout<<"got radars"<<endl;
for (auto r:radars)
{
PRINTVAR(r);
cout<<"\tcovers islands:"<<endl;
for (auto i:r.coverIslands)
{
cout<<"\t";
PRINTVAR(i);
}
}
try {
//GUI gui;
////gui.drawCircle(0,0,1,"lines");
//
//for (auto i:islands)
//{
// i.setD(0.1);
// gui.drawPoint(i);
//}
//for (auto r:radars)
//{
// gui.drawPoint(r);
//}
//wait_for_key();
//Gnuplot g("GUI");
Gnuplot g("GUI");
g.reset_all();
g.reset_plot();
g.set_grid();
}
catch (GnuplotException ge)
{
cout << ge.what() << endl;
}
cout<<"***************************************"<<endl;
}
bool Case::checkLegality() {
PRINT_DEBUG_INFO();
//1
PRINTVAR(N);
PRINTVAR(islands.size());
if(N!=islands.size())
{
PRINT_DEBUG_INFO();
return false;
}
//2
float maxY=0;
for (auto p:islands)
{
if(p.getY()<=0)
{
PRINT_DEBUG_INFO();
return false;
}
if(p.getY()>maxY)
maxY=p.getY();
}
PRINTVAR(maxY);
PRINTVAR(D);
if(maxY>D)
{
cout<<"maxY > D, no solution"<<endl;
PRINT_DEBUG_INFO();
return false;
}
//3
vector<Point>::iterator ip=islands.begin(),iq=islands.begin();
for (;ip!=islands.end();ip++)
{
Point p=*ip;
for (iq=ip+1;iq!=islands.end();iq++)
{
Point q=*iq;
if(p.getX()==q.getX() && p.getY()==q.getY())
{
PRINT_DEBUG_INFO();
return false;
}
}
}
// pass all checks finally
return true;
}
pair<float,float> Point::getXCover(float D)
{
//PRINT_DEBUG_INFO();
//show();
float x=getX(),y=getY();
float l=sqrt(D*D-y*y);
//PRINTVAR(l);
pair<float,float> loc={x-l,x+l} ;
//PRINTVAR(x-l);
//PRINTVAR(x+l);
return loc;
}
bool canMerge(pair<float,float> a,pair<float,float> b)
{
if (a.first>b.second || b.first>a.second )
return false;
else
return true;
}
pair <float,float> merge(pair<float,float> a,pair<float,float> b)
{
float right=min(a.second,b.second);
float left=max(a.first,b.first);
pair <float,float> p={left,right};
return p;
}
void show(vector<pair<float,float>> v)
{
//PRINT_DEBUG_INFO();
for (auto i:v)
cout<<"("<<i.first<<",\t"<<i.second<<")"<<endl;
}
void wait_for_key ()
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__) // every keypress registered, also arrow keys
cout << endl << "Press any key to continue..." << endl;
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
_getch();
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
cout << endl << "Press ENTER to continue..." << endl;
std::cin.clear();
std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cin.get();
#endif
return;
}
void GUI::drawCircle(double xc,double yc,double r,string style,string info="")
{
std::vector<double> x, y ;
//const double PI=3.1415926;
double theta=0;
double theta_step=2*PI/GUI_DRAW_NPOINTS;
for (int i = 0; i < GUI_DRAW_NPOINTS; i++) // fill double arrays x, y, z
{
x.push_back(xc+r*(double)cos(theta)); // x[i] = i
y.push_back(yc+r*(double)sin(theta)); // y[i] = i^2
theta+=theta_step;
}
//cout << endl << endl << "*** user-defined lists of points (x,y)" << endl;
//string style="points";
g.set_style(style);
g.plot_xy(x,y,info);
}
void GUI::drawPoint(Point p)
{
drawCircle(p.getX(),p.getY(),0.01,"lines");
drawCircle(p.getX(),p.getY(),p.getD(),"lines");
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/4.8.h
void print_font_in_the_mid(int line_width,int c_cnt, char c) ;
int f4_8();
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/3.6.cpp
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
typedef int INT;
int main3_6 () {
INT cnt=0;
const int width=20;
int i;
while (true) {
cin>>i;
if (i>100 ) { cout<<"Error"<<endl;
} else if (i<0 ) { cout<<"Error"<<endl;
} else if (i>=90 ) { cout<<"A"<<endl;
} else if (i>=80) { cout<<"B"<<endl;
} else if (i>=70) { cout<<"C"<<endl;
} else if (i>=60) { cout<<"D"<<endl;
} else if (i>=0) { cout<<"E"<<endl;
} else { cout <<"Error"<<endl;}
}
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/20.2.cpp
#include "include.top.h"
// zjc here
void f20_2() {
}
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN/include/2.3_link_list.h
#ifndef M_2_3_LINK_LIST_H
#define M_2_3_LINK_LIST_H
class Node{
public:
Node(){
}
Node(int d ,Node* p)
{
m_data=d;
m_next=p;
}
~Node()
{
}
int GetData(){return m_data;}
Node* GetNext(){
return m_next;
}
private:
int m_data;
Node* m_next;
};
class MyLinkList {
public:
MyLinkList(); // a blank list, name is NA
MyLinkList(string name);
MyLinkList(int[],int);
MyLinkList(int[],int,string);
MyLinkList(MyLinkList& other);//copying construct func
MyLinkList & operator=(MyLinkList& other);//copying construct func
~MyLinkList();
void SetName(string);
void PrintItem(int);
void PrintList(int printLength=-1,bool b=false); // default value setting is only allowed in declaration(h files)
void ClearList();
bool ListEmpty();
int ListLength();
int GetElem(int ind);
void SetElem(int ind,int value);
int LocateElem(int e,bool (*compare)(int,int)); // notice: the format of function-pointer
int PriorElem(int cur_e);
int NextElem (int cur_e);
void ListInsert(int ind , int e);
void ListPush(int e);
int ListPop();
void ListUnshift(int e);
int ListShift();
void ListDelete(int ind );
void ListTraverse(bool (*visit)(int*),bool pre_order=true);
void ListUnion(MyLinkList&,MyLinkList& Lunion); // how to use the reference of a class
void ListSwap(int ind1,int ind2);
void ListSort(); // bubble sort
void ListReverse();
void HeapRealloc();
private:
Node* HeadPtr;
string m_name;
};
//LNode * head;
#endif //M_2_3_LINK_LIST_H
<file_sep>/python/workspace_python/basic_algorithm_of_python/ex_5_5_word_freq.py
__author__ = 'jc'
import re
f=open('ttt')
ll=f.readlines()
hash_word_cnt=dict()
pattern_list=[]
for i in '->?()[]{}""|&^*%#@!+-~=_$,1234567890abcdefghijklmnopqrstuvwxyz/\\.:;<>`\'':
pattern_list.append(i)
for line in ll:
line=line.lower()
for i in pattern_list:
line=line.replace(i," ")
list_words=line.split()
for word in list_words:
#print(word)
#word=word.lower()
if re.match(r'[a-z]',word) or re.match(r'^\d+$',word):
continue
if word in hash_word_cnt.keys():
hash_word_cnt[word]+=1
else:
hash_word_cnt[word]=1
l1=sorted(hash_word_cnt.items(),key=lambda d:d[1],reverse=True)
#print (l1)
for i in l1[:1000]:
print('%-80s%10s'%(i[0],i[1]))
'''
for word in l1:
print('%-20s%10s'%(word,hash_word_cnt[word]))
'''
f.close()
<file_sep>/cpp/exe_game/tetris/unit_test.cpp
#include "unit_test.h"
#include "lib.h"
void test_Control() { // FUNC
// test control
cout<<"==================="<<""<<endl;
cout<<"TEST CLASS: Constrol"<<""<<endl;
cout<<"==================="<<""<<endl;
Control c; c.run();
cout<<"==================="<<""<<endl;
}
void test_Matrix() // FUNC
{
cout<<"==================="<<""<<endl;
cout<<"TEST CLASS: Matrix"<<""<<endl;
cout<<"==================="<<""<<endl;
int WIDTH=10;
int HEIGHT=5;
//
Display* d=new Display();
d->showTitle();
//
Matrix* m=new Matrix(HEIGHT,WIDTH,"X");
d->show();
//
cout<<"==================="<<""<<endl;
}
void test_flow() // FUNC
{
// INIT:
int WIDTH=10;
int HEIGHT=10;
//
Display* display=new Display();
display->showTitle();
//
Matrix* m=new Matrix(HEIGHT,WIDTH,"X");
display->m=m;
display->show();
Control controller;
// LOOP:
while(true)
{
char ch;
cout<<"ch (q to break)=";
ch=controller.getch();
cout<<ch<<""<<endl;
if(ch=='q')
break;
if(ch=='o')// add new shape
{
cout<<"ADD NEW SHAPE!"<<""<<endl;
Shape* shape=new Shape(WIDTH,HEIGHT);
//Shape* shape=new Shape(WIDTH,HEIGHT,5);
shape->init();
shape->update();
m->addShape(shape);
m->update();
}
if(ch=='r') // will instead by timing-triggered
{
cout<<"REFRESH!"<<""<<endl;
// REFRESH Matrix
display->show();
cout<<"TICK!"<<""<<endl;
m->tick();
cout<<"UPDATE!"<<""<<endl;
m->update();
cout<<"UPDATED!"<<""<<endl;
m->print();
// Display
display->show();
// call
}
if(ch=='p') // for debug
{
cout<<"UPDATE!"<<""<<endl;
m->update();
cout<<"UPDATED!"<<""<<endl;
m->print();
// Display
display->show();
}
Shape* shape=m->getShape();
if( ch=='s')
shape->move("S");
if( ch=='a')
shape->move("W");
if( ch=='d')
shape->move("E");
if( ch=='w')
shape->turn("left");
if( ch=='e')
shape->turn("right");
}
}
void test_flow_tick() // FUNC
{
//for(int u=0;u<10;u++)
// cout<<"RAND:"<<rand()%3<<""<<endl;
//assert(0);
PRINT_DEBUG_INFO();
// INIT:
int WIDTH=10;
int HEIGHT=10;
//
Display* display=new Display();
display->showTitle();
//
Matrix* m=new Matrix(HEIGHT,WIDTH,"X");
display->m=m;
display->show();
Control controller;
char ch='0';
int cntr=0;
unsigned Tms=50;
// LOOP:
while(true)
{
//cout<<"ch (q to break)=";
ch=controller.getch();
assert(ch);
//cout<<ch<<""<<endl;
if(ch=='q')
break;
if(ch=='o')// add new shape
{
cout<<"ADD NEW SHAPE!"<<""<<endl;
//Shape* shape=new Shape(WIDTH,HEIGHT);
//Shape* shape=new Shape(WIDTH,HEIGHT,5);
Shape* shape=new Shape(WIDTH,HEIGHT,rand()%7);
shape->init();
shape->setMatrixPtr(m);
shape->update();
m->addShape(shape);
m->update();
}
if(ch=='r') // will instead by timing-triggered
{
cout<<"REFRESH!"<<""<<endl;
// REFRESH Matrix
display->show();
cout<<"TICK!"<<""<<endl;
m->tick();
cout<<"UPDATE!"<<""<<endl;
m->update();
cout<<"UPDATED!"<<""<<endl;
m->print();
// Display
display->show();
// call
}
if(ch=='p') // for debug
{
//-------------------------------
// PRINT
cout<<"UPDATE!"<<""<<endl;
m->update();
// Display
display->show();
//-------------------------------
}
Shape* shape=0;
if(m)
shape=m->getShape();
//assert(shape);
if(shape)
{
if(ch=='s')
shape->move("S");
if(ch=='a')
shape->move("W");
if(ch=='d')
shape->move("E");
if(ch=='w')
shape->turn("left");
if(ch=='e')
shape->turn("right");
}
bool isDead=false;
sleep_ms(Tms);
if(cntr%10==0)
{
cout<<ch<<""<<endl;
PRINTVAR(ch);
//PRINTVAR(cntr);
cout<<"TICK!"<<""<<endl;
isDead=!(m->tick());
//-------------------------------
// PRINT
cout<<"UPDATE!"<<""<<endl;
m->update();
cout<<"UPDATED!"<<""<<endl;
m->print();
// Display
display->show();
//-------------------------------
if(m->getAllShapesAreSteady() && !isDead) // all steady -> add new
{
cout<<"STEADY, ADD NEW SHAPE!"<<""<<endl;
//Shape* shape=new Shape(WIDTH,HEIGHT);
//Shape* shape=new Shape(WIDTH,HEIGHT,5);
Shape* shape=new Shape(WIDTH,HEIGHT,rand()%7);
shape->init();
shape->setMatrixPtr(m);
shape->update();
m->addShape(shape);
m->update();
}
}
if(isDead)
break;
if(cntr==99999)
cntr=0;
cntr++;
}
}
void test_Point() // FUNC
{
vector<Point> vp;
vp.push_back(Point(0,0));
vp.push_back(Point(0,1));
vp.push_back(Point(0,2));
PRINT_VECTOR(vp);
cout<<"------------------"<<""<<endl;
for(auto p:vp)
{
PRINTVAR(p);
p.x++;
PRINTVAR(p);
}
}
void test_deleteFromVector() // FUNC
{
vector<Point*> v;
v.push_back(new Point(0,0));
v.push_back(new Point(0,1));
v.push_back(new Point(0,2));
//PRINT_VECTOR_hor(v);
cout<<"--------"<<""<<endl;
for(auto p:v)
cout<<""<<*p<<"\t@"<<p<<endl;
for(Point* p:v)
{
if(p->x==0&& p->y==1)
deleteFromVector(&v,p);
}
cout<<"--------"<<""<<endl;
for(auto p:v)
cout<<""<<*p<<"\t@"<<p<<endl;
//PRINT_VECTOR_hor(v);
}
void test_time_engine()
{
int cnt=0;
while(true)
{
unsigned T=1;// seconds
cout<<"cnt="<<cnt<<""<<endl;
sleep(T);
cnt++;
}
}
void deleteFromVector(vector<Point*>* vecPtr, Point* item) // FUNC
{
auto vec=*vecPtr;
int size=vec.size();
int cntr=0;
for (auto iter=vecPtr->begin();iter!=vecPtr->end();)
{
Point* t=*iter; // t is Point*
//int ind=t.transformIsCombined(unit_transforms_wo_zeros);
if (t==item)
{
//cout<<"erase:"<<endl;
//vec.erase(iter); // delete the combined transform
vecPtr->erase(iter);
size=vecPtr->size();
}
else
{
iter++;
}
cntr++;
}
}
<file_sep>/cpp/exe_game/tetris/unit_test.h
#ifndef UNIT_TEST_H
#define UNIT_TEST_H
#include "global.h"
#include "Display.class.h"
#include "Control.class.h"
#include "TetrisCalc.class.h"
#include "Matrix.class.h"
//--------------------------------------
using namespace std;
void test_Control() ; // FUNC
void test_Matrix() ;// FUNC
void test_flow() ;// FUNC
void test_flow_tick() ;// FUNC
void test_Point() ;// FUNC
void test_deleteFromVector(); // FUNC
void test_time_engine();
void deleteFromVector(vector<Point*>* vecPtr, Point* item); // FUNC
#endif
<file_sep>/cpp/6_EXEs/include/stable_sort.h
struct Employee {
Employee(int age, std::string name) : age(age), name(name) { }
int age;
std::string name; // Does not particpate in comparisons
};
bool operator<(const Employee &lhs, const Employee &rhs) ;
int stable_sort();
<file_sep>/python/workspace_python/dive_into_python/src/1/1/1p1.py
'''
Created on 2014-9-27
@author: admin
'''
print 'TEST'
for i in range(0,10):
print i
else:
print 'loop is over'
# INPUT:
#name= raw_input("What's your name:\n");
name="john"
print "Hello, "+name+"!"
# BRANCH:
if cmp(name,'john')==0:
print "your name is john"
else:
print "you are not john"
# MULTI-LINE
print '''line1
...line2
...line3'''
# BOOLEAN
a=9
b=5
c=1
def swap(s1,s2):
return s2,s1;# func can return 2 values in Python!!
if a>b and b>c:
print "series is full reverse"
else:
print "series is NOT full reverse"
if a>b:
a,b=swap(a,b)
if b>c:
b,c=swap(b,c)
if a>b:
a,b=swap(a,b)
print a,b,c
<file_sep>/cpp/7_EXEs_separated/exe_copy_file/copy.cpp
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
int main() {
clock_t start, end;
start = clock();
ifstream source("from.ogv", ios::binary);
ofstream dest("to.ogv", ios::binary);
dest << source.rdbuf();
source.close();
dest.close();
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/8.4.cpp
#include "include.top.h"
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
void f8_4() {//FUNC
cout<<"=================="<<endl;
cout<<"encrypt and decrypt"<<endl;
cout<<"=================="<<endl;
char c[200];
char k[20];
strcpy(c,"the result of 3 and 2 is not 8#");
strcpy(k,"4962873");
//cout<<"encrypt:"<<encrypt(&c,3)<<endl;
//int len_str=sizeof(c)/sizeof(char);
//int len_key=sizeof(k)/sizeof(char);
cout<<"String input:"<<c<<endl;
cout<<"Key input :"<<k<<endl;
f_encrypt(c,50,k,7);
cout<<"encrypt:"<<c<<endl;
}
void f_encrypt (char *c,int string_len,char* offset_list,int offset_list_len) {
for (int ind_string=0;ind_string<string_len;ind_string++) {
int ind_offset_list = ind_string%offset_list_len;
int curr_int_key=*(offset_list+ind_offset_list)-48;
char after=*(c+ind_string)+curr_int_key;
while (after>122) {
after-=122;
}
while (after<32) {
after+=32;
}
if (*(c+ind_string)=='#') {break;}
//printf("ind_string=%d;s=%c;ind_offset_list=%d;key=%d;after=%c\n",ind_string,*(c+ind_string),ind_offset_list,curr_int_key,after);
printf("%3d:(%c)%4d+%d\t=\t(%c)%4d\n",ind_string,*(c+ind_string),*(c+ind_string),curr_int_key,after,after);
*(c+ind_string)=after;
}
}
void f_decrypt(char*c,int offset){
}
<file_sep>/cpp/exe_map/exe_map_sort/s.cpp
#define SIMPLE_LOG 0
#define LNX 1
#if (!SIMPLE_LOG)
#define DLOG(x) cout<<#x<<"="<<x<<" @"<<__LINE__<<endl;
#else
#define DLOG(x)
#endif
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#if (!SIMPLE_LOG)
#define DENTER \
LVCALL++; PRLVCALL; ::std::cout<<"-->"<<__FUNCTION__<<::std::endl;
#define DRETURN \
PRLVCALL; ::std::cout<<"<--"<<__FUNCTION__<<::std::endl; LVCALL--;
#endif
#define DEBUG_MARK PRINT_DEBUG_INFO()
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define DPRINT(x) \
(::std::cout<<x<<::std::endl )
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#if SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define DEBUG_MARK
#define PRINT_DEBUG_INFO_PREFIX(p)
#define DPRINT(x)
#define PRINT_COUT(p)
#define DENTER
#define DRETURN
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <regex>
#include <map>
#include <assert.h>
using namespace std;
int main()
{
vector<pair<int,int>>items;
//items[0]=0;
//items[1]=1;
//items[2]=2;
items.push_back(make_pair(11,1));
items.push_back(make_pair(11,3));
items.push_back(make_pair(12,3));
items.push_back(make_pair(13,2));
items.push_back(make_pair(12,2));
auto cmp = [](std::pair<int,int> const & a, std::pair<int,int> const & b)
{
return a.second != b.second? a.second < b.second : a.first < b.first;
};
std::sort(items.begin(), items.end(), cmp);
for(auto p:items)
{
DPRINT(""<<p.first<<", "<<p.second);
}
}
<file_sep>/python/workspace_python/read_scan_plan_xls/read_scan_plan_xls.py
__author__ = 'jc'
#-*- coding: utf8 -*-
import xlrd
import re
fname = "Alaska_scan_plan.xlsx"
bk = xlrd.open_workbook(fname)
shxrange = range(bk.nsheets)
try:
sh = bk.sheet_by_name("Sheet1")
except:
print "no sheet in %s named Sheet1" % fname
nrows = sh.nrows
ncols = sh.ncols
print "nrows %d, ncols %d" % (nrows,ncols)
cell_value = sh.cell_value(1,1)
#print cell_value
item_list =[]
row_list = []
for i in range(1,nrows):
if i==2:
item_data= sh.row_values(i)
print item_data
if i==8:
row_data = sh.row_values(i)
print row_data
row_list.append(row_data)
for i in range(len(item_data)):
item=item_data[i]
#print "%s\t=\t%s"%(item,row_data[i])
result, number = re.subn(" ", "_", item)
result, number = re.subn("#", "cnt", result)
result, number = re.subn("\.", "", result)
#print "%s\t=\t%s"%(item_data[i],row_data[i])
print "set %s \t%s"%(result,row_data[i])<file_sep>/java/Assignment6/NameSurferGraph.java
/*
* File: NameSurferGraph.java
* ---------------------------
* This class represents the canvas on which the graph of
* names is drawn. This class is responsible for updating
* (redrawing) the graphs whenever the list of entries changes
* or the window is resized.
*/
import acm.graphics.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
public class NameSurferGraph extends GCanvas
implements NameSurferConstants, ComponentListener {
/**
* Creates a new NameSurferGraph object that displays the data.
*/
public NameSurferGraph() {
addComponentListener(this);
// You fill in the rest //
updateListOfDecades();
}
/**
* Clears the list of name surfer entries stored inside this class.
*/
public void clear() {
// You fill this in //
Iterator<GObject> iterator=listOfGObject.iterator();
while (iterator.hasNext()) {
this.remove(iterator.next());
}
}
/* Method: addEntry(entry) */
/**
* Adds a new NameSurferEntry to the list of entries on the display.
* Note that this method does not actually draw the graph, but
* simply stores the entry; the graph is drawn by calling update.
*/
public void addEntry(NameSurferEntry entry) {
// You fill this in //
this.listOfShowingEntry.add(entry);
drawLinesForAnEntry(entry);
// entry.getRank(decade) ;
//TODO
}
/**
* Updates the display image by deleting all the graphical objects
* from the canvas and then reassembling the display according to
* the list of entries. Your application must call update after
* calling either clear or addEntry; update is also called whenever
* the size of the canvas changes.
*/
public void update() {
// You fill this in //
this.clear();
// ADD:
double step_x=getWidth()/NDECADES;
// GLine gl=new GLine(decade_y_grid, 0, decade_y_grid, box.getHeight());
// System.out.println(decade_y_grid+" "+0+" "+decade_y_grid+" "+box.getHeight());
// box.add(gl);
// GLine gl1=new GLine(100 , 100,getWidth() ,getHeight());
// System.out.println(-getWidth()+" "+-getHeight()+" "+getWidth() +" "+getHeight());
// this.add(gl1);
System.out.println("DONE");
// double decade_x_grid=100;
// GLine gl=new GLine(0, decade_x_grid, this.getWidth(),decade_x_grid);
GLabel label =null;
// update x,y loc arrays:
updateLoc_x();
Iterator<NameSurferEntry> iteratorOfShowingEntry=listOfShowingEntry.iterator();
while(iteratorOfShowingEntry.hasNext()) {
NameSurferEntry nse=iteratorOfShowingEntry.next();
updateLoc_y(nse);
drawLinesForAnEntry(nse);
}
// redraw axes
drawAxesWithDecadesLabel();
}
public void drawAxesWithDecadesLabel () {
// draw Y axes and decade labels
GLabel label =null;
Iterator<Integer> iteratorOfDecades=listOfDecades.iterator() ;
while(iteratorOfDecades.hasNext()){
Integer currDecade=iteratorOfDecades.next();
Double curr_x=match_decade2loc_x.get(currDecade);
GLine tmp_gl=new GLine(curr_x , 0,curr_x , getHeight());
listOfGObject.add(tmp_gl);
System.out.println(curr_x+" "+-getHeight()+" "+curr_x+" "+getHeight());
this.add(tmp_gl);
String name=String.valueOf(currDecade);
label = new GLabel(name);
listOfGObject.add(label);
this.add(label, curr_x, getHeight());
}
// draw X axes:
double curr_y=label.getAscent();
GLine tmp_gl1=new GLine( 0,curr_y , getWidth(),curr_y);
this.add(tmp_gl1);
listOfGObject.add(tmp_gl1);
Y_BOTTOM=curr_y;
curr_y=getHeight()-label.getAscent();
GLine tmp_gl2=new GLine( 0,curr_y , getWidth(),curr_y);
this.add(tmp_gl2);
listOfGObject.add(tmp_gl2);
Y_TOP=curr_y;
}
public void drawLinesForAnEntry (NameSurferEntry nse) {
updateLoc_y(nse);
Iterator<Integer> iteratorOfDecades=listOfDecades.iterator() ;
int cntr=0;
Double oldx,oldy,x = null,y = null;
while(iteratorOfDecades.hasNext()){
Integer decade=iteratorOfDecades.next();
oldx=x;
oldy=y;
x=match_decade2loc_x.get(decade);
y=match_decade2loc_y.get(decade);
// draw lines
if(cntr>0) {
GLine tmp_gl1=new GLine( oldx,oldy ,x,y);
this.add(tmp_gl1);
listOfGObject.add(tmp_gl1);
}
// draw labels
Integer rank=nse.getRank(decade);
String labelString;
if (rank==0) {
labelString=nse.getName()+",*";
} else {
labelString=nse.getName()+","+nse.getRank(decade);
}
GLabel temp_glabel1=new GLabel(labelString);
this.add(temp_glabel1, x, y);
listOfGObject.add(temp_glabel1);
cntr++;
}
}
public void updateListOfDecades () {
for (Integer i=0;i<NDECADES;i++) {
listOfDecades.add(START_DECADE+i*10);
}
System.out.println("PROC updateListOfDecades:"+listOfDecades);
}
public void updateLoc_x () {
double step_x=getWidth()/NDECADES;
double curr_x = 0;
Iterator<Integer> iteratorOfDecades=listOfDecades.iterator() ;
while(iteratorOfDecades.hasNext()){
Integer i=iteratorOfDecades.next();
match_decade2loc_x.put(i, curr_x);
curr_x+=step_x;
}
}
public void updateLoc_y (NameSurferEntry entry) {
Iterator<Integer> iteratorOfDecades=listOfDecades.iterator() ;
while(iteratorOfDecades.hasNext()){
Integer decade=iteratorOfDecades.next();
Integer rank=entry.getRank(decade);
if (rank==0) {
rank=MAX_RANK;
}
Double loc_y=Y_BOTTOM+(-(Y_BOTTOM-Y_TOP)/(1000))*rank;
match_decade2loc_y.put(decade,loc_y);
System.out.println("Y_TOP="+Y_TOP+"Y_BOTTOM="+Y_BOTTOM+"rank="+rank+"loc_y="+loc_y+"@DECADE"+decade);
}
}
/* Implementation of the ComponentListener interface */
public void componentHidden(ComponentEvent e) { }
public void componentMoved(ComponentEvent e) { }
public void componentResized(ComponentEvent e) { update(); }
public void componentShown(ComponentEvent e) { }
private ArrayList<GLine> u_Array_GLine=new ArrayList<GLine>();
private ArrayList<GObject> listOfGObject=new ArrayList<GObject>();
private ArrayList<Integer> listOfDecades=new ArrayList<Integer>();
// private ArrayList<Double> listOfXOfDecades=new ArrayList<Double>();
private HashMap<Integer, Double> match_decade2loc_x=new HashMap<Integer, Double>();
private HashMap<Integer, Double> match_decade2loc_y=new HashMap<Integer, Double>();
private ArrayList<NameSurferEntry> listOfShowingEntry=new ArrayList<NameSurferEntry>();
private Double Y_TOP;
private Double Y_BOTTOM;
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.2_directed_graph/dot2svg.sh
#dot -Tsvg t.dot -o t.svg
for i in `ls *dot`
do
echo $i
to=$i.svg
dot -Tsvg $i -o $to
done
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/CC.h
/////////////////////////////////
// P349 Table 4.1.6 CC
/////////////////////////////////
class CC
{
private:
vector<bool> mMarked;// MEMBER
vector<int> mId;// MEMBER
int mCount;// MEMBER
public:
CC(Graph* G)// METHOD
{
mMarked.resize(G->V(),0);
mId.resize(G->V(),-1);
mCount=0;
for(int s=0;s<G->V();s++)
if(!mMarked[s])
{
dfs(G,s) ;
mCount++;
}
}
void dfs(Graph* G,int v)// METHOD
{
//DLOG(v);
mMarked[v]=1;
mId[v]=mCount;
//DPRINT("set mId["<<v<<"]="<<mCount );
for(int w:G->adj(v))
if(!mMarked[w])
dfs(G,w);
}
bool connected(int v,int w) { return mId[v]==mId[w]; }// METHOD
int id(int v){return mId[v];}// METHOD
int count(){return mCount;}// METHOD
};
class TestCC// METHOD
{
public:
TestCC(Graph* G)//METHOD
{
CC* cc=new CC(G);
int M=cc->count();
cout<<M<<" components:"<<endl;
vector<vector<int>> components;
components.resize(M,{});
for(int i=0;i<M;i++)
components[i]={};
for(int v=0;v<G->V();v++)
components[cc->id(v)].push_back(v);
for(int i=0;i<M;i++)
{
for(int v:components[i])
cout<<v<<" ";
cout<<endl;
}
}
};
void testCC()//METHOD
{
Graph* g=new Graph("tinyG.txt");
DLOG(g->toString());
new TestCC(g);
}
<file_sep>/python/workspace_python/basic_algorithm_of_python/analyze_prime.py
__author__ = 'jc'
import math
def is_prime(N):
flag_is_prime=True
up=math.floor(N**0.5)
for i in range(2,up+1):
if N % i == 0:
flag_is_prime=False
break
return flag_is_prime
def find_prime(N):
list_prime=[]
for i in range(2,N):
list_prime.append(i)
for i in list_prime:
if is_prime(i):
for j in range(i+i,N,i):
if j in list_prime:
list_prime.remove(j)
return list_prime
def differential(ll):
old_i=0
r = []
for i in ll:
#print(str(i))
diff=i-old_i
r.append(diff)
old_i=i
return r
total_list=[]
u=find_prime(100000)
total_list.append(u)
u=differential(u)
total_list.append(u)
u=differential(u)
total_list.append(u)
u=differential(u)
total_list.append(u)
u=differential(u)
total_list.append(u)
u=differential(u)
total_list.append(u)
u=differential(u)
total_list.append(u)
u=differential(u)
total_list.append(u)
u=differential(u)
total_list.append(u)
u=differential(u)
total_list.append(u)
#l1=differential(l0)
#l2=differential(l1)
#l3=differential(l2)
#l4=differential(l3)
l0=total_list[0]
for index in range(len(l0)):
for i in total_list:
#print(str(l0[i])+"\t"+str(l1[i])+"\t"+str(l2[i])+"\t"+str(l3[i])+"\t"+str(l4[i]))
print ("%10d"%(i[index]),end="")
print()
'''
list_prime=[]
for i in range(2,10):
list_prime.append(i)
for i in list_prime:
if 6 in list_prime:
list_prime.remove(6)
print('ITER: '+str(i))
'''<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/BreadthFirstPaths.h
/////////////////////////////////
// P342 Table 4.1.5 Paths
/////////////////////////////////
class BreadthFirstPaths
{
protected:
vector<bool> mMarked;// MEMBER
vector<int> mEdgeTo;// MEMBER
int mS;
//int mEccentricity; // the min distance the farest node of node mS
int mFarestNode;
public:
BreadthFirstPaths() {}//METHOD
BreadthFirstPaths(Graph* G,int s)//METHOD
{
mMarked.resize(G->V(),0);
mEdgeTo.resize(G->V(),-2); // -2 is init value
mEdgeTo[s]=-1; // -1 is root value
mS=s;
bfs(G,s);
cout<<"mEdgeTo:";
for(int i=0;i<G->V();i++)
{
cout<<i<<":"<<mEdgeTo[i]<<endl;
}
cout<<endl;
}
private:
void bfs(Graph*G,int s)//METHOD
{
deque<int> queue={};
mMarked[s]=1;
queue.push_back(s);
while(!queue.empty())
{
int v=queue.front();
queue.pop_front();
for(int w:G->adj(v))
if(!mMarked[w])
{
mFarestNode=w;
mEdgeTo[w]=v;
mMarked[w]=1;
DPRINT(" EdgeTo["<<w<<"]="<<s);
queue.push_back(w);
}
}
}
public:
bool hasPathTo(int v) { return mMarked[v]; }//METHOD
vector<int> pathTo(int v)//METHOD
{
if(!hasPathTo(v)) return {};
vector<int> path={};
for(int x=v;x!=mS;x=mEdgeTo[x])
path.push_back(x);
path.push_back(mS);
return path;
}
int getEccentricity()
{
auto path=pathTo(mFarestNode);
int dist=path.size()-1;
DPRINT("mFarestNode from "<<mS<<" is "<<mFarestNode<<", dist="<<dist);
DLOG(path);
return dist;
}
};
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/4.4.cpp
#include <iostream>
#include <math.h>
#include <iomanip>
#include <time.h>
#include <stdio.h>
#include "lib.h"
using namespace std;
int main4_4 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
int up_bound=100000;
cout<<"计算"<<up_bound<<"以内完数:"<<endl;
for(int n=1;n<=up_bound;n++) {
if (is_full_num(n)) {
cout<<setw(4)<<"="<<n<<""<<endl;
}
}
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/20.1.cpp
#include "include.top.h"
template <class T>
T min(T& a,T& b) {
return a>b?b:a;
}
char* min(char* a,char* b) { // override
return (strcmp(a,b)?b:a);
}
void f20_1() {
int c=min<int>(1,2);
cout<<"min="<<c<<""<<endl;
double r=min<double>(1.1,2.2);
cout<<"min="<<r<<""<<endl;
cout<<"min="<<min('3','5')<<""<<endl;
cout<<"min="<<min("aoe","ziga")<<""<<endl;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/5.9.h
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <iomanip>
#include "4.10.h"
#include "lib.h"
using namespace std;
int f5_9 (int year) ;
int sum(int n) ;
int sum_big(int n) ;
int sum_small(int n) ;
int new_born(int n) ;
<file_sep>/python/workspace_python/dive_into_python/src/1/range_group/range.py
# MATH: group, ring, domain
# calc in range
def show_range(ll):
'''gen range by abstract form'''
print "full form of range",ll,"is:"
for i in range(10):
print i,
print ""
out={1:1}
for i in range(10):
out[i]=i
for j in ll:
if j==i:
index=ll.index(j)
#print "index of",j," is",index
length=len(ll)
if index==length-1:
index=-1
ret=ll[index+1]
#print "return ", ret
out[i]=ret
for i in range(10):
print out[i],
print ""
return out
def show_abs():
pass
def mul(full1,full2):
print "full form of mul ",full1," x ",full2," is:"
for i in range(10):
print i,
print ""
out={1:1}
for key1,values1 in full1.items():
for key2,values2 in full2.items():
if key1 == key2:
continue
for i in range(10):
out[i]=full1[full2[i]]
for i in range(10):
print out[i],
print ""
return out
pass
abs1=[1,3,5,7,8]
abs2=[2,5,8]
#show_range(abs1)
f1=show_range(abs1)
f2=show_range(abs2)
mul(f1,f2)<file_sep>/cpp/exe_operator_for_map/s.cpp
#include <vector>
#include <map>
#include <iostream>
#include <assert.h>
using namespace std;
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
// Catalan number
#define N 6
#define LEN 2
using std::vector;
template <class T>
vector<T> operator+(const vector<T>& lhs, const vector<T>& rhs){ // return type is a vector of integers
if(lhs.size() != rhs.size()){ // Vectors must be the same size in order to add them!
throw std::runtime_error("Can't add two vectors of different sizes!");
}
vector<T> result; // Declaring the resulting vector, result
for(T i=0; i < lhs.size(); i++){ // adding each element of the result vector
result.push_back(lhs.at(i) + rhs.at(i)); // by adding each element of the two together
}
return result; // returning the vector "result"
}
std::ostream & operator <<(std::ostream &os,
const std::map<std::string, std::vector<int>> &m)
{
for (const auto &p : m)
{
os << p.first << ": ";
for (int x : p.second) os << x << ' ';
os << std::endl;
}
return os;
}
template <class U, class V>
std::ostream & operator <<(std::ostream &os,
const std::map<U, V> &m)
{
os << "->";
os << std::endl;
for (const auto &p : m)
{
os << p.first << ": " << p.second;
os << std::endl;
}
os << "<-";
return os;
}
int main(int argc, char** argv) {
vector<int> a(3, 3);
vector<int> b(3, 5);
vector<int> c = a + b;
vector<int> check_add;
check_add.push_back(8);
check_add.push_back(8);
check_add.push_back(8);
PRINT_VECTOR_hor(a);
PRINT_VECTOR_hor(b);
PRINT_VECTOR_hor(c);
if (c == check_add) {
std::cout<<"operator works for vector!\n";
}
else {
std::cout<<"operator fails for vector!\n";
}
std::map<std::string, std::vector<int>> m;
m["1"]={1};
m["2"]={2};
PRINTVAR(m);
std::map<int, int> m1={{4,4},{6,6}};
PRINTVAR(m1);
std::map<int, map<int,int>> m2;
m2[1]=m1;
m2[2]=m1;
PRINTVAR(m2);
return 0;
}
<file_sep>/cpp/POJ/src/poj1002.cpp
#include "include.top.h"
#include <math.h>
#include <iomanip>
#include <map>
using namespace std;
#include <fstream>
void poj1002 ()
{
cout<<"-----------------------------------------------"<<endl;
cout<<"poj1002"<<endl;
//----------------------------------------------------------
string filename="input/poj1002.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj1002.out";
std::ofstream outfile(filename_out);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
string line;
string out;
int line_cntr=1;
//int total_number_cnt;
map<string,string> map_char2digit=
{
{"A","2"},
{"B","2"},
{"C","2"},
{"D","3"},
{"E","3"},
{"F","3"},
{"G","4"},
{"H","4"},
{"I","4"},
{"J","5"},
{"K","5"},
{"L","5"},
{"M","6"},
{"N","6"},
{"O","6"},
{"P","7"},
{"Q","-1"},
{"R","7"},
{"S","7"},
{"T","8"},
{"U","8"},
{"V","8"},
{"W","9"},
{"X","9"},
{"Y","9"},
{"Z","-1"}
};
map<string,int> map_num2freq;
map<string,string> map_decode;
while (infile >> line)
{
if(line_cntr==1)
{
//total_number_cnt=stoi(line);
outfile<<"got "<<line<<" tele numbers:"<<endl;
}
else
{
outfile<<"\t"<<line<<"\t"<<"\t";
//-------------------------------------------
cout<<"got\tchar:";
for(auto c:line)
{
if (c=='-' || c=='Q' || c== 'Z')
continue;
string s_tmp=string(1,c);
cout<<s_tmp<<"\t";
//outfile<<map_char2digit[s_tmp];
}
cout<<endl;
//-------------------------------------------
cout<<"trans\tchar:";
string translated_number="";
for(auto c:line)
{
if (c=='-' || c=='Q' || c== 'Z')
continue;
string s_tmp;
if (!isdigit(c))
{
s_tmp=string(1,c);
cout<<map_char2digit[s_tmp]<<"\t";
translated_number=translated_number+map_char2digit[s_tmp];
}
else
{
s_tmp=string(1,c);
cout<<c<<"\t";
translated_number=translated_number+s_tmp;
}
}
PRINTVAR(translated_number);
map_decode[line]=translated_number;
if (!map_num2freq[translated_number])
map_num2freq[translated_number]=1;
else
map_num2freq[translated_number]++;
cout<<endl;
//-------------------------------------------
outfile<<endl;
}
++line_cntr;
}
outfile<<"====================="<<endl;
bool flag_duplicate=false;
for (auto pair:map_num2freq)
{
auto key=pair.first;
auto v=pair.second;
if (v>1)
{
flag_duplicate=true;
cout<<key<<":\t"<<v;
outfile<<key<<":\t"<<v;
cout<<":ORIGIN NUM:";
outfile<<":ORIGIN NUM:";
for (auto pair2:map_decode)
{
auto key2=pair2.first;
auto v2=pair2.second;
//cout<<key<<":\t"<<v<<endl;
if (v2==key)
{
cout<<":"<<key2<<"\t";
outfile<<":"<<key2<<"\t";
}
}
cout<<endl;
outfile<<endl;
}
}
if (!flag_duplicate)
outfile<<"No duplicate"<<endl;
outfile<<"====================="<<endl;
#if 0
for (auto pair:map_num2freq)
{
auto key=pair.first;
auto v=pair.second;
cout<<key<<":\t"<<v<<endl;
}
for (auto pair:map_decode)
{
auto key=pair.first;
auto v=pair.second;
cout<<key<<":\t"<<v<<endl;
}
#endif
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
}
<file_sep>/cpp/codewar/best_travel/others_full_exhaustion/others.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#define SIMPLE_LOG
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#if(SIMPLE_LOG)
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
using namespace std;
class BestTravel
{
public:
static int chooseBestSum(int t, int k, std::vector<int>& ls)
{
unsigned n = ls.size(); // size of set
if( k > n )
return -1;
int best_sum = -1;
int sum, j;
// We represent a subset of ls (of size k) by a
// strictly increasing sequence of indices into ls:
vector<unsigned> indices(k);
// The first subset to consider:
for(int i=0; i<k; i++)
indices[i] = i;
// Iterate over all subsets of ls:
for(;;)
{
PRINT_VECTOR_hor(indices);
// Find the sum for this subset:
sum = 0;
for(j=0; j<k; j++)
sum += ls[indices[j]];
if( sum > best_sum && sum <= t)
best_sum = sum;
// Now move on to the next subset.
if( indices[k-1] < n-1 )
{
++indices[k-1];
continue;
}
// Find an index we can increment:
for(j=k-2; j >=0 && indices[j] == indices[j+1]-1; j--)
;
if( j < 0 )
break;
++indices[j];
//
for(j++; j < k; j++)
indices[j] = indices[j-1]+1;
}
return best_sum;
}
};
std::vector<std::vector<unsigned>> gen_full_exhausive_indices (unsigned n,unsigned k) ;
std::vector<std::vector<unsigned>> gen_full_exhausive_indices (unsigned n,unsigned k)
{
PRINT_DEBUG_INFO();
std::vector<std::vector<unsigned>> r;
PRINT_DEBUG_INFO();
//
PRINT_DEBUG_INFO();
// We represent a subset of ls (of size k) by a
// strictly increasing sequence of indices into ls:
std::vector<unsigned> indices(k);
for(int i=0; i<k; i++)
indices[i] = i;
PRINT_VECTOR_hor(indices);
// Iterate over all subsets of ls:
int j;
for(;;)
{
PRINT_VECTOR_hor(indices);
r.push_back(indices);
// Now move on to the next subset.
if( indices[k-1] < n-1 )
{
++indices[k-1];
continue;
}
// Find an index we can increment:
for(j=k-2; j >=0 && indices[j] == indices[j+1]-1; j--)
;
if( j < 0 )
break;
++indices[j];
for(j++; j < k; j++)
indices[j] = indices[j-1]+1;
}
return r;
};
int main ()
{
//std::vector<int> arr = {17, 0, -4, 3, 15};
//std::vector<int> arr = {3,4,8,9,10};
#if 0
std::vector<int> arr = {91,74,73,73,73,73,73};
std::map<std::vector<int>,int> cache_keep_max;
auto r=BestTravel::chooseBestSum(300,3,arr);
#endif
#if 0
std::vector<int> arr = {1,2,91,74,73,82,71};
std::map<std::vector<int>,int> cache_keep_max;
auto r=BestTravel::chooseBestSum(500,5,arr);
#endif
#if 0
std::vector<int> arr = {100, 76, 56, 44, 89, 73, 68, 56, 64, 123, 2333, 144, 50, 132, 123, 34, 89 };
//std::vector<int> arr = {100, 44, 89, 73, 68, 56, 64, 123, 34, 89 };
auto r=BestTravel::chooseBestSum(500,5,arr);
#endif
#if 0
std::vector<int> arr = { 91,74,73,85,73,81,87};
auto r=BestTravel::chooseBestSum(331,5,arr);
#endif
#if 0
std::vector<int> arr = { 91,74,73,85,73,81,87 };
auto r=BestTravel::chooseBestSum(331,3,arr);
#endif
//PRINTVAR(BestTravel::findLargestOne(std::vector<int>(),100,arr,cache_keep_max));
//PRINT_DEBUG_INFO_PREFIX("================================================");
//std::vector<int> a={1,2,3};
//std::vector<int> b={1,3,2};
//sort(b.begin(),b.end());
//PRINTVAR((a==b));
std::vector<std::vector<unsigned>> vv=gen_full_exhausive_indices(6,2);
PRINT_DEBUG_INFO_PREFIX("================================================");
for(std::vector<unsigned> v:vv)
{
PRINT_VECTOR_hor(v);
}
PRINT_DEBUG_INFO_PREFIX("================================================");
//
//
return 0;
}
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN_good/src/main.cpp
#include "include.top.h"
using namespace std;
int main() {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
//string s="test";
//cout<<"this is "<<s<<endl;
//return 0;
////////////////////////////////////////////////
int u[5]={101,77,303,7,21};
MyList l1(u,5,"l1");
MyList lX(l1);
l1.PrintList(5);
l1.PrintList(5,true);
cout<<"LENGTH="<<l1.ListLength()<<endl;
cout<<"GET ELEMENT="<<l1.GetElem(4)<<endl;
if (0) {
cout<<"ClearList..."<<endl;
l1.ClearList();
cout<<"GET ELEMENT="<<l1.GetElem(4)<<endl; // will cause segment fault
}
cout<<"LocateElem:"<<endl;
cout<<l1.LocateElem(3,compare)<<endl;
cout<<"copy constructor:============"<<endl;
MyList ltemp(l1);
l1.PrintList(-1,true);
ltemp.PrintList(-1,true);
//return 0;
cout<<"PriorElem:============"<<endl;
cout<<l1.PriorElem(7)<<endl;
printf("NextElem:===================\n");
cout<<l1.NextElem(1)<<endl;
printf("ListInsert:===================\n");
l1.PrintList(-1,true);
l1.ListInsert(5,999);
l1.PrintList(-1,true);
//return 0;
printf("ListDelete:===================\n");
l1.PrintList(-1,true);
l1.ListDelete(5);
l1.PrintList(-1,true);
printf("ListTraverse,pre_order:===================\n");
l1.ListTraverse(visit);
printf("ListTraverse,post_order:===================\n");
l1.ListTraverse(visit,false);
printf("ListPush:=========\n");
l1.PrintList(-1);
l1.ListPush(9);
l1.ListPush(8);
l1.ListPush(7);
l1.PrintList(-1);
printf("ListPop:=========\n");
l1.PrintList(-1);
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
l1.PrintList(-1);
printf("ListUnion:=========\n");
l1.PrintList(-1);
int v[5]={33,44,55,66,77};
MyList l2(v,5,"l2");
l2.PrintList(-1);
MyList lunion(v,5,"lunion");
l1.ListUnion(l2,lunion);
lunion.PrintList(-1);
//return 0;
printf("ListSwap:=========\n");
l1.PrintList(-1);
l1.ListSwap(0,1);
l1.PrintList(-1);
printf("ListSort:=========\n");
l1.ListPush(-3);
l1.ListPush(-5);
l1.PrintList(-1);
l1.ListSort();
l1.PrintList(-1);
printf("ListReverse:=========\n");
l1.PrintList(-1);
l1.ListReverse();
l1.PrintList(-1);
l1.ListSort();
l1.PrintList(-1);
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
cout<<"END"<<endl;
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/include.top.h
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <string.h>
#include <cstdlib>
#include "3.4.h"
#include "3.5.h"
#include "3.6.h"
#include "4.1.h"
#include "4.2.h"
#include "4.3.h"
#include "4.4.h"
#include "4.5.h"
#include "4.6.h"
#include "4.7.h"
#include "4.8.h"
#include "4.9.h"
#include "4.10.h"
#include "5.1.h"
#include "5.2.h"
#include "5.6.h"
#include "5.9.h"
#include "ch_7.5.h"
#include "7.5.h"
#include "lib.h"
#include "8.1.h"
#include "8.2.h"
#include "8.4.h"
#include "8.9.h"
#include "9.1.h"
#include "11.2.h"
#include "Cat.h"
#include "Node.h"
#include "Queue.h"
#include "11.5.h"
#include "20.1.h"
#include "20.2.h"
<file_sep>/cpp/POJ/src/poj1860.cpp
#include "include.top.h"
#include "gnuplot_i.h"
#include "poj1860.h"
#include "GRAPH.class.h"
#include "GRAPH.class.cpp"
#include <math.h>
#include <iomanip>
#include <map>
#include <regex>
#include <fstream>
using namespace std;
void f(string* node);
void poj1860 ()
{
#if 1
cout<<"-----------------------------------------------"<<endl;
cout<<"poj1860"<<endl;
//----------------------------------------------------------
string filename="input/poj1860.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj1860.out";
// clean the file "output/poj1860.out"
std::ofstream outfile_init(filename_out);
outfile_init.close();
std::ofstream outfile(filename_out,ios::app);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
string line;
//Edge <double>null_edge(-1,1);
Edge <double>null_edge(-1,1,0,0);
int cnt_line=0;
int num_of_currency,num_of_points,kind_of_Nick_has;
double qty_of_Nick_has;
double rab,cab,rba,cba;
GRAPH<string,double>* graph_currency_ptr;
while(getline(infile,line))
{
if (std::regex_match(line, std::regex("^//.*") )) // lines begin with "//"
continue;
if (std::regex_match(line, std::regex("^\\s*$") )) // blank lines
continue;
cnt_line++;
cout<<"-------------------------------------"<<endl;
cout<<"LINE="<<line<<endl;
if(cnt_line==1)
{
stringstream ssin(line);
ssin>>num_of_currency>>num_of_points>>kind_of_Nick_has>>qty_of_Nick_has;
PRINTVAR(num_of_currency);
PRINTVAR(num_of_points);
PRINTVAR(kind_of_Nick_has);
PRINTVAR(qty_of_Nick_has);
//GRAPH<string,double> graph_currency=new GRAPH<string,double>(num_of_currency,null_edge);
//graph_currency_ptr=&graph_currency;
graph_currency_ptr=new GRAPH<string,double>(num_of_currency,null_edge);
}
if(cnt_line>1 && cnt_line<num_of_points+2)
{
cout<<"Point:"<<endl;
PRINTVAR(line);
// integer A and B - numbers of currencies it exchanges,// real RAB, CAB, RBA and CBA - exchange rates and commissions when exchanging A to B and B to A respectively
//
string* pA=new string;
string* pB=new string;
stringstream ssin(line);
ssin>>*pA>>*pB>>rab>>cab>>rba>>cba;
Edge<double> tmpEdgeAB(1,true,rab,cab);
Edge<double> tmpEdgeBA(1,true,rba,cba);
PRINT_DEBUG_INFO();
graph_currency_ptr->addEdge(pA,pB,tmpEdgeAB);
PRINT_DEBUG_INFO();
graph_currency_ptr->addEdge(pB,pA,tmpEdgeBA);
PRINT_DEBUG_INFO();
}
}
cout<<"-----------------------------------------------"<<endl;
cout<<"SHOW"<<endl;
graph_currency_ptr->show();
cout<<"-----------------------------------------------"<<endl;
//graph_currency_ptr->getParentIdList(1);
//graph_currency_ptr->getChildIdList(1);
//graph_currency_ptr->traverseDFS(graph_currency_ptr->getNodeById(0));
#if 0
//----------------------------------------------------------
// traverseBFS
cout<<"traverseBFS:"<<endl;
graph_currency_ptr->traverseBFS(graph_currency_ptr->getNodeById(3),f);
std::cout << "id2BFSdepth:" << " \n";
graph_currency_ptr->showMAP_id2BFSdepth();
std::cout << "printBFSTree:" << " \n";
graph_currency_ptr->printBFSTree();
//----------------------------------------------------------
cout<<"traverseBFS:"<<endl;
graph_currency_ptr->traverseBFS(graph_currency_ptr->getNodeById(2),f);
std::cout << "id2BFSdepth:" << " \n";
graph_currency_ptr->showMAP_id2BFSdepth();
std::cout << "printBFSTree:" << " \n";
graph_currency_ptr->printBFSTree();
//----------------------------------------------------------
cout<<"traverseBFS:"<<endl;
graph_currency_ptr->traverseBFS(graph_currency_ptr->getNodeById(1),f);
std::cout << "id2BFSdepth:" << " \n";
graph_currency_ptr->showMAP_id2BFSdepth();
std::cout << "id2BFSparent:" << " \n";
graph_currency_ptr->showMAP_id2BFSparent();
std::cout << "printBFSTree:" << " \n";
graph_currency_ptr->printBFSTree();
std::cout << "------------------" << " \n";
std::cout << "printShortestPath:" << " \n";
std::cout << "------------------" << " \n";
graph_currency_ptr->printShortestPath(1,5);
std::cout << "------------------" << " \n";
graph_currency_ptr->printShortestPath(5,1);
std::cout << "------------------" << " \n";
//----------------------------------------------------------
#endif
#if 1
//----------------------------------------------------------
// traverseDFS
cout<<"traverseDFS:"<<endl;
graph_currency_ptr->traverseDFS(graph_currency_ptr->getNodeById(3),f);
//----------------------------------------------------------
cout<<"-----------------------------------------------"<<endl;
cout<<"print DFS time:"<<endl;
cout<<"TIME"<<"\t:\t"<<"NODE COLOR"<<endl;
for(int i=0;i<100;i++)
{
for(int id=0;id<100;id++)
{
auto MAP_grey=graph_currency_ptr->MAP_id2DFSdepth_grey;
auto MAP_black=graph_currency_ptr->MAP_id2DFSdepth_black;
if(MAP_grey.count(id) && MAP_grey[id]==i)
cout<<i<<"\t:\t"<<id<<"\tgrey \t"<<endl;
if(MAP_black.count(id) &&MAP_black[id]==i)
cout<<i<<"\t:\t"<<id<<"\tblack\t"<<endl;
}
}
cout<<"-----------------------------------------------"<<endl;
//----------------------------------------------------------
//----------------------------------------------------------
#endif
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
//----------------------------------------------------------
//Edge <double>null_edge;
/////////////////////////////////
// PRINT_DEBUG_INFO();
// auto m=graph_currency.getMat();
// PRINTVAR(m.size());
// PRINT_DEBUG_INFO();
// graph_currency.show();
// PRINT_DEBUG_INFO();
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
outfile.close();
#endif
}
void f(string* node)
{
cout<<"do for node:"<<*node<<"\t@"<<node<<endl;
}
<file_sep>/cpp/case/include/lib.h
#include <math.h>
#include <stdio.h>
#include "include.top.h"
double myfac (int n) ;
double calc_sum_of_power (int n,int power=3) ;
bool is_tulip (int n, int power=3) ;
bool is_prime (int n, int print=0) ;
bool is_full_num (int n, int print=0) ;
double calc_use_do (double x, double stop=1e-8) ;
bool is_int (double v) ;
//double integral(double from,double to);
bool item_is_in_array (int i,int a[] ,int a_length) ;
void show_array(double a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void show_array(int a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void show_array(bool a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void sort_bubble(double a [],int size,int return_list[]) ;
void sort_bubble(double a [],int size,int return_list[]) ;
string dec2bin(int n);
<file_sep>/python/workspace_python/dive_into_python/src/1/1/1p5_hash.py
# HASH:
score={'a':100,'b':99,'c':98}
print score
print score['c']
score['new']=60
print score['new']
print score
print 'somebody' in score
score['somebody']=99
print 'somebody' in score
print '======================'
print score.get('b')
print score.get('nobody')
print score
score.pop('somebody')
print score
# SET
print '======================'
ll=[1, 1, 2, 2, 3, 3]
print ll
s = set(ll)
print s<file_sep>/cpp/codewar/k_primes/s.handout.cpp
#include <vector>
#include <string>
#include <iostream>
#include <deque>
class Solution
{
public:
static TreeNode* arrayToTree(std::vector<int> arr)
{
if(arr.empty())
return NULL;
TreeNode* rootNode;
std::deque<TreeNode*> queueOfNode;
int cntr=0;
for(auto i:arr)
{
auto node=new TreeNode(i);
if(cntr==0)
rootNode=node;
// father point to children
if(!queueOfNode.empty())
{
auto fr=queueOfNode.front();
if(fr->m_left==NULL)
fr->m_left=node;
else if(fr->m_right==NULL)
fr->m_right=node;
}
// push to queue
queueOfNode.push_back(node);
// pop front of queue
if(!queueOfNode.empty())
{
auto fr=queueOfNode.front();
if(fr->m_left!=NULL&&fr->m_right!=NULL)
queueOfNode.pop_front();
}
cntr++;
}
return rootNode; // TODO: implementation
}
};
<file_sep>/cpp/stl_test/run.sh
#g++ -v s.cpp ; ./a.out
g++ -v s.cpp
<file_sep>/cpp/5_BOOK_CPP_PRIMER/include/exe_3.2.h
void exe_3_2();
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN/src/2.1_func.cpp
#include "include.top.h"
using namespace std;
int f_test_linear_list() { // FUNC
int u[5]={101,77,303,7,21};
MyList l0(u,15,"l0");
//MyList l0(u,23);
l0.PrintList(l0.ListLength(),true);
return 0;
cout<<l0.ListLength()<<endl;
MyList l1(u,5,"l1");
MyList lX(l1);
l1.PrintList(5);
l1.PrintList(5,true);
cout<<"LENGTH="<<l1.ListLength()<<endl;
cout<<"GET ELEMENT="<<l1.GetElem(4)<<endl;
if (0) {
cout<<"ClearList..."<<endl;
l1.ClearList();
cout<<"GET ELEMENT="<<l1.GetElem(4)<<endl; // will cause segment fault
}
cout<<"LocateElem:"<<endl;
cout<<l1.LocateElem(3,compare)<<endl;
cout<<"copy constructor:============"<<endl;
MyList ltemp(l1);
l1.PrintList(-1,true);
ltemp.PrintList(-1,true);
//return 0;
cout<<"PriorElem:============"<<endl;
cout<<l1.PriorElem(7)<<endl;
printf("NextElem:===================\n");
cout<<l1.NextElem(1)<<endl;
printf("ListInsert:===================\n");
l1.PrintList(-1,true);
l1.ListInsert(5,999);
l1.PrintList(-1,true);
//return 0;
printf("ListDelete:===================\n");
l1.PrintList(-1,true);
l1.ListDelete(5);
l1.PrintList(-1,true);
printf("ListTraverse,pre_order:===================\n");
l1.ListTraverse(visit);
printf("ListTraverse,post_order:===================\n");
l1.ListTraverse(visit,false);
printf("ListPush:=========\n");
l1.PrintList(-1);
l1.ListPush(9);
l1.ListPush(8);
l1.ListPush(7);
l1.PrintList(-1);
printf("ListPop:=========\n");
l1.PrintList(-1);
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
l1.PrintList(-1);
printf("ListUnion:=========\n");
return 0;
l1.PrintList(-1);
int v[5]={33,44,55,66,77};
MyList l2(v,5,"l2");
l2.PrintList(-1);
MyList lunion(v,5,"lunion");
l1.ListUnion(l2,lunion);
lunion.PrintList(-1);
return 0;
printf("ListSwap:=========\n");
l1.PrintList(-1);
l1.ListSwap(0,1);
l1.PrintList(-1);
printf("ListSort:=========\n");
l1.ListPush(-3);
l1.ListPush(-5);
l1.PrintList(-1);
l1.ListSort();
l1.PrintList(-1);
printf("ListReverse:=========\n");
l1.PrintList(-1);
l1.ListReverse();
l1.PrintList(-1);
l1.ListSort();
l1.PrintList(-1);
printf("HeapRealloc:==========\n");
MyList l3(v,15,"l3");
l1.PrintList(-1);
l1.ListPush(1);
l1.ListPush(1);
l1.ListPush(1);
l1.ListPush(1);
return 0;
}
int f_test_LinkList() { // FUNC
cout<<"================================"<<endl;
cout<<"TEST LINK LIST"<<endl;
MyLinkList l01("l01");
l01.ListUnshift(9);
l01.ListUnshift(8);
l01.ListUnshift(7);
l01.PrintList(-1,1);
return 0;
int u[5]={101,77,303,7,21};
MyLinkList l0(u,15,"l0");
//MyList l0(u,23);
l0.PrintList(l0.ListLength(),true);
return 0;
cout<<l0.ListLength()<<endl;
MyList l1(u,5,"l1");
MyList lX(l1);
l1.PrintList(5);
l1.PrintList(5,true);
cout<<"LENGTH="<<l1.ListLength()<<endl;
cout<<"GET ELEMENT="<<l1.GetElem(4)<<endl;
if (0) {
cout<<"ClearList..."<<endl;
l1.ClearList();
cout<<"GET ELEMENT="<<l1.GetElem(4)<<endl; // will cause segment fault
}
cout<<"LocateElem:"<<endl;
cout<<l1.LocateElem(3,compare)<<endl;
cout<<"copy constructor:============"<<endl;
MyList ltemp(l1);
l1.PrintList(-1,true);
ltemp.PrintList(-1,true);
//return 0;
cout<<"PriorElem:============"<<endl;
cout<<l1.PriorElem(7)<<endl;
printf("NextElem:===================\n");
cout<<l1.NextElem(1)<<endl;
printf("ListInsert:===================\n");
l1.PrintList(-1,true);
l1.ListInsert(5,999);
l1.PrintList(-1,true);
//return 0;
printf("ListDelete:===================\n");
l1.PrintList(-1,true);
l1.ListDelete(5);
l1.PrintList(-1,true);
printf("ListTraverse,pre_order:===================\n");
l1.ListTraverse(visit);
printf("ListTraverse,post_order:===================\n");
l1.ListTraverse(visit,false);
printf("ListPush:=========\n");
l1.PrintList(-1);
l1.ListPush(9);
l1.ListPush(8);
l1.ListPush(7);
l1.PrintList(-1);
printf("ListPop:=========\n");
l1.PrintList(-1);
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
cout<<l1.ListPop()<<endl;
l1.PrintList(-1);
printf("ListUnion:=========\n");
return 0;
l1.PrintList(-1);
int v[5]={33,44,55,66,77};
MyList l2(v,5,"l2");
l2.PrintList(-1);
MyList lunion(v,5,"lunion");
l1.ListUnion(l2,lunion);
lunion.PrintList(-1);
return 0;
printf("ListSwap:=========\n");
l1.PrintList(-1);
l1.ListSwap(0,1);
l1.PrintList(-1);
printf("ListSort:=========\n");
l1.ListPush(-3);
l1.ListPush(-5);
l1.PrintList(-1);
l1.ListSort();
l1.PrintList(-1);
printf("ListReverse:=========\n");
l1.PrintList(-1);
l1.ListReverse();
l1.PrintList(-1);
l1.ListSort();
l1.PrintList(-1);
printf("HeapRealloc:==========\n");
MyList l3(v,15,"l3");
l1.PrintList(-1);
l1.ListPush(1);
l1.ListPush(1);
l1.ListPush(1);
l1.ListPush(1);
cout<<"================================"<<endl;
return 0;
}
int f_test_Stack() { // FUNC
cout<<"================================"<<endl;
cout<<"TEST STACK"<<endl;
MyStack l0;
//MyList l0(u,23);
l0.Push(1);
l0.Push(2);
l0.Push(3);
l0.PrintList(l0.ListLength(),true);
cout<<"POP!"<<endl;
cout<<l0.Pop()<<endl;
cout<<"POP!"<<endl;
cout<<l0.Pop()<<endl;
cout<<"================================"<<endl;
l0.Unshift(9);
l0.Unshift(8);
l0.Unshift(7);
l0.Unshift(6);
l0.Unshift(9);
l0.Unshift(8);
l0.Unshift(7);
l0.PrintList(l0.ListLength(),true);
cout<<"SHIFT!"<<endl;
cout<<l0.Shift()<<endl;
cout<<"SHIFT!"<<endl;
cout<<l0.Shift()<<endl;
cout<<"SHIFT!"<<endl;
cout<<l0.Shift()<<endl;
l0.PrintList(l0.ListLength(),true);
cout<<"================================"<<endl;
return 0;
}
bool compare(int a,int b) // FUNC
{
//if (a==b){return true;}
//return false;
return (a==b);
}
bool visit(int *a) // FUNC
{
printf("visit (%x)%d\n",a,*a);
return true;
}
<file_sep>/cpp/exe_TSP/pr_data/run.sh
cp ../out.nearest.dat ./out_data.dat
#/usr/bin/tclsh gen_tsp.tcl > data.dat
gnuplot r.scr
evince out_data.ps
<file_sep>/tcl/tcl_call_cpp/2_swig/fract.c
#include <stdio.h>
double myfract(int n)
{
double res=1.0;
printf("CPP:n=%d\n",n);
int j;
for (j=1;j<=n;j++)
{
printf("CPP:j=%d\n",j);
res *= j;
}
printf("CPP:res=%f\n",res);
return res;
//return 9.9;
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/SymbolGraph.h
class SymbolGraph
{
/////////////////////////////////
// P353 Table 4.1.8 SymbolGraph API
/////////////////////////////////
private:
map<string,int> mSt;
vector<string> mKeys;
Graph* mG;
public:
SymbolGraph(string filename,string delim)
{
DENTER;
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
string a, b;
int cntLine=0;
while (infile >> a >> b)
{
cntLine++;
if(mSt.find(a)==mSt.end())
mSt[a]=mSt.size()-1;
if(mSt.find(b)==mSt.end())
mSt[b]=mSt.size()-1;
}
mKeys.resize(mSt.size());
//for(string name:mSt.keys())
//mKeys[st.get(name)]=name;
for(auto pair:mSt)
{
mKeys[pair.second]=pair.first;
}
mG=new Graph(mSt.size());
std::ifstream infile1(filename);
if (!infile1)
std::cerr << "Couldn't open " << filename << " for reading\n";
cntLine=0;
while (infile1 >> a >> b)
{
if(cntLine>mSt.size())
break;
cntLine++;
int u=mSt[a];
int v=mSt[b];
mG->addEdge(u,v);
//DPRINT("addEdge");
}
DLOG(mG->toString());
DRETURN;
}
Graph* G() {
return mG;}
bool contains(string key) { return mSt.find(key)!=mSt.end(); }
int index(string key)
{
DENTER;
auto r= mSt[key];
DRETURN;
return r;
}
string name(int v)
{
return mKeys[v];
}
};
class TestSymbolGraph
{
public:
TestSymbolGraph(string filename,string delim)
{
DENTER;
SymbolGraph* sg=new SymbolGraph(filename,delim);
Graph* G=sg->G();
auto source="shanghai";
DLOG(source);
for(auto w:G->adj(sg->index(source)))
DLOG(sg->name(w));
source="guangzhou";
DLOG(source);
for(auto w:G->adj(sg->index(source)))
{
DLOG(sg->name(w));
}
DRETURN;
}
};
void testSymbolGraph ()
{
DENTER;
new TestSymbolGraph("routes.txt"," ");
DRETURN;
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.2_directed_graph/SymbolDigraph.h
class SymbolDigraph
{
/////////////////////////////////
// P353 Table 4.1.8 SymbolDigraph API
/////////////////////////////////
private:
map<string,int> mSt;
vector<string> mKeys;
Digraph* mG;
public:
SymbolDigraph(string filename,string delim)//METHOD
{
DENTER;
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
cout<<"READING file: "<<filename<<" ..."<<endl;
string a, b;
int cntLine=0;
while (infile >> a >> b)
{
cntLine++;
if(mSt.find(a)==mSt.end())
mSt[a]=mSt.size()-1;
if(mSt.find(b)==mSt.end())
mSt[b]=mSt.size()-1;
}
mKeys.resize(mSt.size());
//for(string name:mSt.keys())
//mKeys[st.get(name)]=name;
for(auto pair:mSt)
{
mKeys[pair.second]=pair.first;
}
mG=new Digraph(mSt.size());
std::ifstream infile1(filename);
if (!infile1)
std::cerr << "Couldn't open " << filename << " for reading\n";
cout<<"READING file: "<<filename<<" ..."<<endl;
cntLine=0;
while (infile1 >> a >> b)
{
cntLine++;
int u=mSt[a];
int v=mSt[b];
DPRINT("addEdge:"<<a<<"("<<u<<"),"<<b<<"("<<v<<")");
mG->addEdge(u,v);
//DPRINT("addEdge");
}
DLOG(mG->toString());
DRETURN;
}
Digraph* G() {//METHOD
return mG;}
bool contains(string key) { return mSt.find(key)!=mSt.end(); }//METHOD
int index(string key)//METHOD
{
DENTER;
auto r= mSt[key];
DRETURN;
return r;
}
string name(int v)//METHOD
{ return mKeys[v]; }
string toString()
{
DENTER;
string s= "";
s+="\n-----------------------------\n";
s+=to_string(mG->V())+" vertices, "+
to_string(mG->E())+"edges\n";
for(int v=0;v<mG->V();v++)
{
s+=name(v)+"("+to_string(v)+")\t->\t";
auto vv=mG->adj(v);
auto sz= vv.size();
if(sz!=0)
{
for(int w:mG->adj(v))
{
s+=name(w)+"("+to_string(w)+") ";
}
}
s+="\n";
}
s+="-----------------------------\n";
DRETURN;
return s;
}
void dumpDOT(string fname)
{
//----------------------------------------------------------
string filename_out=fname;
std::ofstream outfile(filename_out);
if (!outfile)
{
std::cerr << "Couldn't open " << filename_out << " for writing\n";
return;
}
cout<<"DUMPING FILE: "<<fname<<" ..."<<endl;
outfile<<"digraph \""<<this<<"\" {"<<endl;
for(int ii=0;ii<mG->V();ii++)
{
outfile<<ii<<"[label =\""<<ii<<","<<name(ii)<<"\"];"<<endl;
}
for(int v=0;v<mG->V();v++)
{
for(auto to:mG->adj(v))
outfile<<v<<"->"<<to<<";"<<endl;
}
outfile<<"}"<<endl;
//----------------------------------------------------------
}
};
class TestSymbolDigraph
{
public:
TestSymbolDigraph(string filename,string delim)
{
DENTER;
SymbolDigraph* sdg=new SymbolDigraph(filename,delim);
Digraph* G=sdg->G();
auto source="shanghai";
DLOG(source);
for(auto w:G->adj(sdg->index(source)))
DLOG(sdg->name(w));
source="guangzhou";
DLOG(source);
for(auto w:G->adj(sdg->index(source)))
{
DLOG(sdg->name(w));
}
DRETURN;
}
};
void testSymbolDigraph ()
{
DENTER;
new TestSymbolDigraph("routes.txt"," ");
DRETURN;
}
<file_sep>/python/workspace_python/dive_into_python/src/1/1/1p2.py
# LIST
classmates=['a','b','c']
print len(classmates)
print classmates[1]
print classmates[-1]
print classmates
classmates.append('d')
print classmates
classmates.extend(['e','f','g'])
print classmates
classmates.append(['e','f','g'])
print classmates
classmates.insert(1,'insert1');# insert in front of list[1]
classmates.insert(-2,'insert-2');# insert in front of list[-2]
print classmates
classmates.pop()
print classmates
classmates.sort()
print classmates
classmates.pop(3)
print classmates
L=[]
print L.__len__()<file_sep>/python/workspace_python/design_pattern/src/factory_method/CalcAbstract.py
class CalcAbstract:
def calc(self):
print 'calc'
pass
class CalcAdd (CalcAbstract):
def __init__(self):
pass
def calc(self,a,b):
return a+b
class CalcSub (CalcAbstract):
def __init__(self):
pass
def calc(self,a,b):
return a-b
class CalcMul (CalcAbstract):
def __init__(self):
pass
def calc(self,a,b):
return a*b
class CalcDiv (CalcAbstract):
def __init__(self):
pass
def calc(self,a,b):
return a/b
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/4.5.cpp
#include <stdio.h>
#include <iostream>
#include "4.5.h"
#include "lib.h"
using namespace std;
int f4_5 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
int start_point=100;
int up_bound=20;
double h=start_point,sum=0;
int cnt_hit_gnd=0;
cout<<"计算"<<up_bound<<"次自由落体反弹:"<<endl;
for(int n=0;n<=up_bound;n++) {
cnt_hit_gnd=n+1;
double incr;
if(n==0) {
incr=h;
} else {
incr=h*2;
}
sum+=incr;
printf("hit gnd:%d times, incr:%f, total:%f\n",cnt_hit_gnd,incr,sum);
h=h/2;
}
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/cpp/POJ/include/poj1001.h
void poj1001 () ;
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/Graph.cpp
#include "../../include/include.h"
#include "Graph.h"
#include <queue>
#include <utility>
//struct CmpByKeyLength { bool operator()(const int& k1, const int& k2) { return k1.length() < k2.length(); } };
typedef std::pair<int,int> PAIR;
class combyValue
{
public:
bool operator()(pair<int,int> &lhs,pair<int,int> &rhs)
{return lhs.second<rhs.second;}
};
void print_sorted_hash_by_value(map<int,int> & mm ) {
//DENTER;
vector<pair<int,int>> vv(mm.begin(),mm.end());
//DLOG(vv.size());
//sort(vv.begin(), vv.end(), CmpByValue());
//sort(mm.begin(),mm.end(),combyValue());
sort(vv.begin(), vv.end(), combyValue());
#if 1
cout<<"-----------------------------"<<endl;
cout<<"node, parent"<<endl;
for (int i = 0; i != vv.size(); ++i) {
cout << vv[i].first<<"\t,\t"<<vv[i].second << endl;
}
cout<<"-----------------------------"<<endl;
#endif
//DRETURN;
return ;
}
Graph::Graph(int ve){
DENTER;
//DLOG(ve);
mV=ve;
mE=0;
mAdj={};
//for(int i=0;i<ve;i++)
mAdj.resize(ve,{});
DRETURN;
}
Graph::Graph(string fname){
string filename=fname;
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
int a, b;
int sum;
int cntLine=0;
while (infile >> a >> b)
{
cntLine++;
//DLOG(cntLine);
//DLOG(a);
//DLOG(b);
if(cntLine==1)
{
mV=a;
mE=0;
mAdj={};
//for(int i=0;i<a;i++)
mAdj.resize(a,{});
}
else
{
addEdge(a,b);
}
}
}
int Graph::V(){
return mV;
}
int Graph::E(){
DENTER;
DRETURN;
return mE;
}
void Graph::addEdge(int v,int w){
DENTER;
DLOG(v);
DLOG(w);
DLOG(mAdj.size());
mAdj[v].push_back(w);
mAdj[w].push_back(v);
DLOG(mAdj.size());
DLOG(mAdj[v].size());
mE++;
DRETURN;
}
vector<int> Graph::adj(int v){
DENTER;
DLOG(v);
DLOG(mAdj.size());
DLOG(mAdj[v].size());
DRETURN;
return mAdj[v];
}
void testGraph()
{
DENTER;
Graph* g=new Graph ("tinyG.txt");
//g->addEdge(1,2);
DLOG(g->toString());
DRETURN;
}
#if 0
/////////////////////////////////
// P342 Table 4.1.5 Paths
/////////////////////////////////
vector<PATHTYPE> Graph::paths(int s)// all paths from node s
{
}
bool Graph::has_path_to(int from,int through,int to)// path exists from through to
{
assert(through==-1);
return connected(from,to);
}
PATHTYPE Graph::get_one_path_to(int from,int through,int to)
{
if(!has_path_to(from,through,to))
{
DPRINT("no path");
return {};
}
PATHTYPE p;
for(int x=to;x!=from;x=edge_dfs_to[x])
p.push_back(x);
p.push_back(from);
reverse(p.begin(),p.end());
return p;
}
vector<PATHTYPE> Graph::get_all_path(int from,int through, int to)// like report_timing
{
assert(through==-1);
vector<PATHTYPE> r;
return r;
}
void Graph::report_path(int s,int v)// like report_timing
{
}
/////////////////////////////////
// P349 Table 4.1.6 CC (connected component)
/////////////////////////////////
void Graph::CC() // pre constr
{
CC_marked={};
CC_id={};
for(int s=0;s<V();s++)
if(!CC_marked[s]) // s is not connected yet
{
dfs_rec(s,CC_marked);
CC_count++;
}
}
int Graph::CC_getCount() // # of CC
{ return CC_count; }
int Graph::CC_getId(int v) // id of CC of node v
{
return CC_id[v];
}
#endif
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph/GraphBase.cpp
#include "../../include/include.h"
#include "GraphBase.h"
GraphBase::GraphBase(){
DENTER;
DRETURN;
}
GraphBase::GraphBase(int ve){
DENTER;
DRETURN;
}
int GraphBase::V(){
}
int GraphBase::E(){
}
void GraphBase::addEdge(int v,int w){
}
vector<int> GraphBase::adj(int v){
}
string GraphBase::toString(){
DENTER;
string s= ""+
to_string(V())+" vertices, "+
to_string(E())+"edges\n";
for(int v=0;v<V();v++)
{
s+=to_string(v)+":";
for(int w:adj(v))
s+=to_string(w)+" ";
s+="\n";
}
DRETURN;
return s;
}
// freq used methods:
int GraphBase::degree(int v){
int r=0;
for(int w:adj(v)) r++;
}
int GraphBase::maxDegree(){
int max=0;
for(int v=0;v<V();v++)
if(degree(v)>max)
max=degree(v);
return max;
}
int GraphBase::avgDegree(){
return 2*E() /V();
}
int GraphBase::numberOfSelfLoops(){
int count=0;
for(int v=0;v<V();v++)
for(int w:adj(v))
if(v==w) count++;
return count /2;
}
<file_sep>/java/Assignment6/small_exe/UseRegExp.java
package small_exe;
public class UseRegExp {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "[lol]你好,帮我把这些markup清掉,[smile]。谢谢!";
System.out.println(regSub(s));
}
public static String regSub (String s) {
// String r=s.replaceAll("l[^l]*l", "");
String r=s.replaceAll("\\[[^\\[|\\]]*\\]", "");
return r;
}
}
<file_sep>/cpp/tree_structure/tree.class.h
#include <vector>
#include <iostream>
#include <string>
#include <deque>
#include <type_traits> // for is_same
#include <typeinfo>
#include <assert.h>
#include "../POJ/include/lib.h"
using namespace std;
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
template <typename DATA_TYPE>
class Node
{
public:
Node();
Node(DATA_TYPE v);
Node(DATA_TYPE v,Node* ns,Node* fc);
void setmData(DATA_TYPE v){mData=v;};
DATA_TYPE getmData(){return mData;};
void setmNextSibling(Node* v){mNextSibling=v;};
Node<DATA_TYPE>* getmNextSibling(){return mNextSibling;};
Node<DATA_TYPE>* getmNextNSibling(int n=1);
void setmFirstChild(Node* v){mFirstChild=v;};
Node* getmFirstChild(){return mFirstChild;};
void setmIdInATree(string v){mIdInATree=v;};
string getmIdInATree(){ return mIdInATree; };
void show();
private:
DATA_TYPE mData;
Node* mNextSibling;
Node* mFirstChild;
string mIdInATree;
};
#define NODE_T Node<NODE_DATA_TYPE>
template <typename NODE_DATA_TYPE>
class Tree
{
public:
Tree();
~Tree();
void insertNode(NODE_T* brother, NODE_T* newNode) ;
void insertNode(NODE_T* parent, unsigned nth, NODE_DATA_TYPE newNodeData);
void insertNode(NODE_T* parent, unsigned nth, NODE_T* newNode);
//void insertNode(NODE_T* parent,NODE_T* newNode);
void deleteNode(string id);
void deleteNode(NODE_T* targetNode);
NODE_T* getRoot();
NODE_T* getNodeById(string id);
public:
void show();
void traverseDFS(void (*func)(NODE_T*)=0){traverseDFS(Root,"0",func);};
void traverseBFS(void (*func)(NODE_T*)=0){traverseBFS(Root,"0",func);};
void traverseDFS(NODE_T* fromNode,string fromNodeId="",void (*func)(NODE_T*)=0);
void traverseBFS(NODE_T* fromNode,string fromNodeId="",void (*func)(NODE_T*)=0);
private:
std::vector<NODE_T*> list;
NODE_T* Root;
private:
static void _print_used_in_show(Node<int>* node);
};
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/8.1.cpp
#include "8.1.h"
#include <iostream>
using namespace std;
void f8_1() {
int a[10] ={1,2,3,6,4,3,2,1,8,-2};
int * maxaddr;
int idx;
show_array_with_addr(a,sizeof(a)/sizeof(*a));
maxaddr=findmax(a,sizeof(a)/sizeof(*a),&idx);
cout<<"index="<<idx<<endl
<<"max address="<<maxaddr<<endl
<<"value of it="<<a[idx]<<endl;
}
void show_array_with_addr(int* array,int size) {
for(int i=0;i<size;i++) {
int v=*(array+i);
int *addr=array+i;
cout<<"index:"<<i<<" addr:"<<addr<<" value:"<<v<<endl;
}
}
int* findmax(int* array,int size,int* index) {
int max_v=-99999;
for(int i=0;i<size;i++) {
if(*(array+i)>max_v) {
*index=i;
max_v=*(array+i);
}
}
return (array+*index);
}
<file_sep>/python/workspace_python/pendulum_phase/src/gl.py
'''
Created on 2015-8-9
@author: admin
'''
pendulum_list=[]
INIT_SPEED=0
COLOR=(0,255,0)<file_sep>/tcl/tcl_call_cpp/2_swig/Makefile
t = fract_wrap.c libfract.so
all: $t
clean:
rm -f $t core *.doc *.o
fract_wrap.c: fract.i
swig -tcl8 fract.i
libfract.so:fract_wrap.c
gcc -c fract.c fract_wrap.c -fPIC -I/home/zz/Downloads/tcl8.6.10/generic
gcc -shared -fPIC -o libfract.so fract_wrap.o fract.o
<file_sep>/cpp/6_EXEs/src/exe_operator.cpp
#include "include.top.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
void exe_operator ()
{
cout<<"----------------------"<<endl;
std::vector<Employee_class> v = {
Employee_class(108, "Z"),
Employee_class(32, "A"),
Employee_class(18, "F"),
Employee_class(108, "F"),
Employee_class(33, "F"),
Employee_class(208, "F"),
Employee_class(108, "A"),
Employee_class(108, "C"),
Employee_class(108, "B"),
};
cout<<"-----------------------------"<<endl;
for (const Employee_class &e : v) {
std::cout << e.getAge() << ",\t " << e.getName() << "\n";
}
cout<<"-----------------------------"<<endl;
v[0]+=1;
v[1]+=v[2];
cout<<"v[3]<v[4]="<<(v[3]<v[4])<<endl;
cout<<"v[3]<=v[4]="<<(v[3]<=v[4])<<endl;
cout<<"v[3]>v[4]="<<(v[3]>v[4])<<endl;
cout<<"v[3]>=v[4]="<<(v[3]>=v[4])<<endl;
cout<<"-----------------------------"<<endl;
cout<<"v[6]< v[7]="<<(v[6]< v[7])<<endl;
cout<<"v[6]<=v[7]="<<(v[6]<=v[7])<<endl;
cout<<"v[6]> v[7]="<<(v[6]> v[7])<<endl;
cout<<"v[6]>=v[7]="<<(v[6]>=v[7])<<endl;
cout<<"-----------------------------"<<endl;
for (const Employee_class &e : v) {
std::cout << e.getAge() << ",\t " << e.getName() << "\n";
}
cout<<"-----------------------------"<<endl;
cout<<"Operator for pointer"<<endl;
Employee_class* p1;
Employee_class* p2;
Employee_class c1(1,"a"),c2(2,"b");
cout<<"c1<c2="<<(c1<c2)<<endl;
p1=&c1;
p2=&c2;
cout<<"*p1<*p2="<<(*p1<*p2)<<endl;
cout<<"-----------------------------"<<endl;
}
<file_sep>/python/workspace_python/PKU Online Judge/poj_C15I.py
# -*- coding:gb2312 -*-
__author__ = 'jc'
'''
C15I:The New MindSwitcher
查看 提交 统计 提问
总时间限制: 1000ms 内存限制: 65536kB
描述
<NAME> and <NAME> create The New MindSwitcher!
A The New MindSwitcher allows two users to switch minds with each other without any limits.
There are N people have already tried it,
and each of them may have other's mind now.
Obviously, it is a great invention, but it also leads to trouble.
People who do evil can use it to escape from punishment, or even set others up.
When this realization hit, <NAME> decides to return every mind back to its original body.
There are a lot of The New MindSwitchers, which means in each turn,
any number of pairs of people can switch minds.
However, no one can switch minds with himself/herself or with more than one people at the same time.
To avoid getting into bigger trouble, it is forbidden to introduce new people who did not have used
The New MindSwitcher.
And most importantly, to finish this work as soon as possible,
Professor Farnsworth wants to arrange this process to minimize the number of turns.
输入
The first line contains an integer N. 2 ≤ N ≤ 1000.
Then follows N lines, each line contains two strings: B, M,
separated by a single space, describe that the person B’s body has the person M’s mind at this time.
Both B and M only contain alphabetic characters. 1 ≤ |B|, |M| ≤ 15.
Note that different people have different names.
输出
The first line contains an integer T -- the minimum possible number of turns in order to
return every mind back to its original body.
Then follows T turns. For each turn:
The first line contains an integer S, describes the number of The New MindSwitchers needed in this turn.
Then follows S lines, each line contains two strings: B1, B2,
describe that one of The New Mindswitchers is serving for body of B1 and body of B2 to switch their minds.
You should also make sure that nobody is appeared multiple times in one turn,
and there is no additional person. If there are several solutions, output any one of them.
样例输入
5
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
样例输出
2
1
<NAME>
2
<NAME>
<NAME>
'''
import math
import random
def printvar(varname):
if varname in globals():
print("Info: {} = {}".format(varname, globals()[varname]))
def is_permutation(ll):
lnew=ll[:]
lnew.sort()
for i in range(len(lnew)):
if i != lnew[i]:
print("list is not permutation: {}".format(lnew))
return False
return True
print(is_permutation([1, 2, 6]))
def gen_a_shuffle(N):
ll = []
for i in range(N):
ll.append(i)
random.shuffle(ll)
return ll
def find_a_ring(ll):
print("Info: calling proc find_a_ring: {}".format(ll))
loc=[]
for i in range(len(ll)):
loc.append(i)
print(" marker: {}".format(loc))
if not is_permutation(ll):
return False
ans_list = []
ind = 0
while not ind in ans_list:
print("push {} into {}".format(ind,ans_list))
ans_list.append(ind)
ind = ll[ind]
'''
# the last one iteration
print("push {} into {}".format(ind,ans_list))
ans_list.append(ind)
ind = ll[ind]
'''
print("proc find_a_ring: return {}".format(ans_list))
return ans_list
'''
u = find_a_ring([1, 2, 3, 4, 6,5, 7, 8, 0])
print(u)
'''
def divide_into_rings(ll):
ans_list = []
pass
def divide_by_index_list(ll,index_list):
print("call divide_by_index_list: {} {}".format(ll,index_list))
out_list=[]
left_list=[]
for u in ll:
print("ITER:"+str(u))
if u in index_list:
out_list.append(u)
left_list.append(-1)
else:
out_list.append(-1 )
left_list.append(u)
return [out_list,left_list]
N = 10
name_list = []
for i in range(N):
name = "body{}".format(i)
name_list.append(name)
print(name_list)
init_perm = gen_a_shuffle(N)
printvar('init_perm')
for i in range(len(name_list)):
for j in range(len(init_perm)):
if i == j:
print("{}->HEAD{}".format(name_list[i], init_perm[j]))
ll=[1, 2, 3, 4, 6,5, 7, 8, 0]
u = find_a_ring(ll)
#find_a_ring(init_perm)
r=divide_by_index_list(ll,u)
a,b=r
printvar('a')
printvar('b')<file_sep>/cpp/leetcode/combinational_sum/s.cpp
#define SIMPLE_LOG 0
#define LNX 1
#if (!SIMPLE_LOG)
#define DLOG(x) cout<<#x<<"="<<x<<" @"<<__LINE__<<endl;
#define DLOG1(x) cout<<#x<<"="<<x<<"\t";
#else
#define DLOG(x)
#define DLOG1(x)
#endif
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#if (!SIMPLE_LOG)
#define DENTER \
LVCALL++; PRLVCALL; ::std::cout<<"-->"<<__FUNCTION__<<::std::endl;
#define DRETURN \
PRLVCALL; ::std::cout<<"<--"<<__FUNCTION__<<"@" <<__LINE__<<::std::endl; LVCALL--;
#endif
#define DEBUG_MARK PRINT_DEBUG_INFO()
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define DPRINT(x) \
(::std::cout<<x<<::std::endl )
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#if SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define DEBUG_MARK
#define PRINT_DEBUG_INFO_PREFIX(p)
#define DPRINT(x)
#define PRINT_COUT(p)
#define DENTER
#define DRETURN
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <regex>
#include <map>
#include <assert.h>
using namespace std;
#if !SIMPLE_LOG
static int LV=0;
static int LVCALL=-1;
//#define PRLV std::cout<<LV<<"\t"; for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLV for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLVCALL std::cout<<"L"<<LVCALL<<"\t"; for(int u12=LVCALL;u12>0;u12--) {std::cout<<" .. ";}
template <class U>
std::ostream & operator <<(std::ostream &os, const std::vector<U> &m)
{
if(m.size()==0)
return os;
os << std::endl;
PRLV(LV);
os << "->";
os << std::endl;
LV++;
PRLV(LV);
for (const auto &p : m)
{
os << p << ", " ;
}
os << std::endl;
LV--;
PRLV(LV);
os << "<-";
return os;
}
template <class U, class V>
std::ostream & operator <<(std::ostream &os, const std::map<U, V> &m)
{
os << "->";
os << std::endl;
for (const auto &p : m)
{
os << p.first << ": " << p.second;
os << std::endl;
}
os << "<-";
return os;
}
#endif
//=========================================================================================
int cntSort=0;
int cntPushPop=0;
class Solution {
public:
vector<vector<int>> genPermRep(int numbers) {
vector<vector<int>> r;
int temp;
int a[numbers], upto = numbers+1, temp2;
for( temp2 = 1 ; temp2 <= numbers; temp2++){
a[temp2]=1;
}
a[numbers]=0;
temp=numbers;
while(1){
if(a[temp]==upto-1){
temp--;
if(temp==0)
break;
}
else{
a[temp]++;
while(temp<numbers){
temp++;
a[temp]=1;
}
vector<int> r1;
printf("(");
for( temp2 = 1 ; temp2 <= numbers; temp2++){
printf("%d", a[temp2]-1);
r1.push_back(a[temp2]-1);
cntPushPop++;
}
printf(")\n");
r.push_back(r1);
cntPushPop++;
}
}
return r;
}
vector<vector<int>> genPermRep(vector<int> cand,int target) {
DENTER;
vector<vector<int>> r;
int temp;
int numbers=cand.size();
DLOG(numbers);
//int a[numbers],
vector<int> a;
for(int i=0;i<numbers;i++)
{
a.push_back(0);
cntPushPop++;
}
int upto = numbers+1, ind2;
for( ind2 = 1 ; ind2 < numbers; ind2++){
//DEBUG_MARK;
//DLOG(ind2);
a[ind2]=1;
}
DEBUG_MARK;
a[numbers]=0;
temp=numbers;
while(1){
DEBUG_MARK;
int localSum=0;
if(a[temp]==upto-1){
DEBUG_MARK;
temp--;
if(temp==0)
break;
}
else{
DEBUG_MARK;
a[temp]++;
while(temp<numbers){
temp++;
a[temp]=1;
}
vector<int> r1;
printf("(");
for( ind2 = 1 ; ind2 <= numbers; ind2++){
printf("%d", a[ind2]-1);
auto v=cand[a[ind2]-1];
if(localSum<target)
{
DPRINT("PUSH"<<v);
r1.push_back(v);
cntPushPop++;
localSum+= v;
}
if(localSum==target)
{
DPRINT("PUSH!");
break;
}
if(localSum>target)
break;
}
printf(")\n");
sort(r1.begin(),r1.end());
cntSort++;
if(localSum==target &&
find(r.begin(),r.end(),r1)==r.end()
)
r.push_back(r1);
cntPushPop++;
}
}
DEBUG_MARK;
DRETURN;
return r;
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
DENTER;
vector<vector<int>> ans;
sort(candidates.begin(),candidates.end());
cntSort++;
vector<int> combination;
searchInRange(candidates,target,ans,combination,0);
DRETURN;
return ans;
}
vector<vector<int>> search(vector<int>& cand, int target){
DENTER;
if(cand.size()==0)
return {{}};
if(cand[0]>target)
return {{}};
vector<vector<int>> r;
vector<int> oneAns;
int combination=target;
int ind=0;
int endInd=cand.size()-1;
DRETURN;
return {{0},{1,2,3}};
}
void searchInRange(vector<int>& cand,int target,vector<vector<int>>& res,vector<int>& combination,int from) {
DENTER;
DLOG(from);
DLOG(target);
if(target==0)
{
res.push_back(combination);
DRETURN;
return ;
}
if(target<cand[from])
{
DRETURN;
return ;
}
vector<vector<int>> r;
for(int i=from;i<cand.size();i++)
{
// use cand[i]
DPRINT("use cand["<<i<<"]");
int newTarget=target-cand[i];
combination.push_back(cand[i]);
searchInRange(cand,newTarget,res,combination,i);
combination.pop_back();
DLOG(r.size());
DLOG(r);
} //for(set i=from;i<cand.size;i++)
DLOG(r.size());
DLOG(r);
DLOG(from);
DLOG(target);
DLOG(r);
DRETURN;
return ;
}
int binSearch(vector<int>& cand, int target,int from,int to){
DENTER;
if(cand[from]>target)
return -1;
if(cand[to]<target)
return -1;
if(from>to)
return -1;
while(1)
{
DLOG(from);
DLOG(to);
if(to-from<5)
{
for(int i=0;i<cand.size();i++)
if(cand[i]==target)
return i;
return -1;
}
int mid=(from+to)/2;
if(cand[mid]==target)
return mid;
else if(cand[mid]>target)
{
to=mid;
}
else //cand[mid]<target
{
from=mid;
}
}
return -1;
}
};
#if LNX
int main()
{
clock_t start, end;
start = clock();
////////////////////////////////////////////////
Solution sol;
//vector<int> cand={1,2,3,6,7};
//vector<int> cand={6,1,2,4};
//vector<int> cand={1,2,4};
vector<int> cand={48,22,49,24,26,47,33,40,37,39,31,46,36,43,45,34,28,20,29,25,41,32,23};
//vector<int> cand={48,22,49,24,26,47,33,40,37,39,31};
//auto ans=sol.combinationSum(cand,6);
auto ans=sol.combinationSum(cand,69);
DLOG(ans);
//DLOG(sol.genPermRep(2));
//DLOG(sol.genPermRep(cand));
DLOG(cntSort);
DLOG(cntPushPop);
////////////////////////////////////////////////
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
}
#endif
#if 0
#endif
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/src/f13_6.cpp
#include "include.top.h"
#define MINNUM2(a,b) (a<b?a:b)
#define MINNUM3(a,b,c) (MINNUM2(a,MINNUM2(b,c)))
#define PRINT(a) (a)
//#ifdef DEBUG
// #define PIRNT_DEBUG(cond,msg,) if (cond) cout<<""<<<<""<<endl;
//#else
// #define PIRNT_DEBUG(cond,msg,)
//#endif
#define SUM_ARRAY(a,len,return_value) int sum=0;for(int u=0;u<len;u++) {sum+=*a+u;};return_value=sum;
//#define SHOW_VAR(a,b) cout<<a<<"="<<b<<endl;
//#define PRINTVAR(a) SHOW_VAR(#a,a)
void f13_6() {
cout<<"==============="<<endl;
cout<<"EXE 13_6:"<<endl;
int x,y,z;
cout<<"please enter a num x:"<<endl;
cin>>x;
cout<<"please enter a num y:"<<endl;
cin>>y;
cout<<"please enter a num z:"<<endl;
cin>>z;
cout<<"MINNUM2(x,y)="<<MINNUM2(x,y)<<endl;
cout<<"==============="<<endl;
cout<<"EXE 13_7:"<<endl;
cout<<"MINNUM3(x,y,z)="<<MINNUM3(x,y,z)<<endl;
cout<<"==============="<<endl;
cout<<"EXE 13_8:"<<endl;
cout<<"PRINT(x)="<<PRINT("this is a string")<<endl;
cout<<"PRINT(x)="<<PRINT(1)<<endl;
cout<<"PRINT(x)="<<PRINT(PI)<<endl;
cout<<"Info: so, the macro PRINT() can be used for all kinds of variables"<<endl;
cout<<"==============="<<endl;
cout<<"EXE 13_9:"<<endl;
int x1[3]={1,2,3};
cout<<"debug:"<<x1[0]<<endl;
cout<<"PRINT_ARRAY:"<<endl;
PRINT_ARRAY(x1,3);
cout<<"Info: you can use 'g++ -E' instead of 'g++' to debug macro"<<endl;
cout<<"==============="<<endl;
cout<<"EXE 13_10:"<<endl;
cout<<"SUM_ARRAY:"<<endl;
int r=0;
SUM_ARRAY(x1,3,r);
cout<<r<<endl;
cout<<"==============="<<endl;
cout<<"EXE 13_more # and ##:"<<endl;
#define HELLO0(x) printf ("Hello,x\n")
#define HELLO(x) printf ("Hello,"#x"\n")
#define CALC0(x) (x+2)
#define CALC(x) (#x+2)
HELLO0(John);
HELLO(John);
CALC0(3);
CALC(3);
#define AND(x,y) printf (#x""#y" \n")
AND(Albert,Bob);
int intVar=3555;
#define AND2(x,y) cout<<x##y<<endl
AND2(intV,ar);
cout<<"==============="<<endl;
cout<<"SHOW_VAR:"<<endl;
//SHOW_VAR("r",r);
int a1=1;
int a2=2;
double d1=2.13;
string s1="this is a string";
PRINTVAR(r);
PRINTVAR(a1);
PRINTVAR(a2);
PRINTVAR(d1);
PRINTVAR(s1);
PRINTVAR(x1);
}
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN_good/include/include.top.h
#ifndef INCLUDE_TOP_H
#define INCLUDE_TOP_H
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <string.h>
#include <string>
#include <cstdlib>
#include <time.h>
#include <assert.h>
#include "2.1_linear_list.h"
#include "2.1_func.h"
//#include "3.4.h"
//#include "3.5.h"
//#include "3.6.h"
//#include "4.1.h"
//#include "4.2.h"
//#include "4.3.h"
//#include "4.4.h"
//#include "4.5.h"
//#include "4.6.h"
//#include "4.7.h"
//#include "4.8.h"
//#include "4.9.h"
//#include "4.10.h"
//#include "5.1.h"
//#include "5.2.h"
//#include "5.6.h"
//#include "5.9.h"
//#include "ch_7.5.h"
//#include "7.5.h"
//#include "lib.h"
//#include "8.1.h"
//#include "8.2.h"
//#include "8.4.h"
//#include "8.9.h"
//#include "9.1.h"
//#include "11.2.h"
//#include "Cat.h"
//#include "Node.h"
//#include "Queue.h"
//#include "11.5.h"
//
using namespace std;
#endif INCLUDE_TOP_H
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/4.10.h
int f4_10 (int year) ;
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN_good/include/2.1_linear_list.h
#include "include.top.h"
using namespace std;
//int instanceCounterMyList=-1;
class MyList
{
public:
MyList(); // a blank list, name is NA
MyList(int[],int);
MyList(int[],int,string);
MyList(MyList& other);//copying construct func
MyList & operator=(MyList& other);//copying construct func
~MyList();
void SetName(string);
void PrintItem(int);
void PrintList(int printLength=-1,bool b=false); // default value setting is only allowed in declaration(h files)
void ClearList();
bool ListEmpty();
int ListLength();
int GetElem(int ind);
void SetElem(int ind,int value);
int LocateElem(int e,bool (*compare)(int,int)); // notice: the format of function-pointer
int PriorElem(int cur_e);
int NextElem (int cur_e);
void ListInsert(int ind , int e);
void ListPush(int e);
int ListPop();
void ListDelete(int ind );
void ListTraverse(bool (*visit)(int*),bool pre_order=true);
void ListUnion(MyList&,MyList& Lunion); // how to use the reference of a class
void ListSwap(int ind1,int ind2);
void ListSort(); // bubble sort
void ListReverse();
//void ListSort(int start=0,int end=-1); // quick sort
private:
string m_name;
int *m_list_element;
int *m_list_relation;
int m_list_length;
int m_heap_length;
};
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/5.2.h
int f5_2 () ;
double target_func (double x) ;
double integral (double from,double to) ;
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/Cat.cpp
#include "include.top.h"
using namespace std;
int Cat::GetAge() {
return itsAge;
}
void Cat::SetAge(int age) {
itsAge=age;
}
void Cat::Meow() {
cout <<"Meow\n";
}
<file_sep>/cpp/6_EXEs/src/main.cpp
#include "include.top.h"
//using namespace std;
string reverse_str(string str) {
reverse(str.begin(),str.end());
# if 0
string sss;
for(auto c:str) {
PRINTVAR(c);
sss.push_back(c);
}
#endif
return str;
}
string exe1 (string str) {
PRINTVAR(str)
string newstr=reverse_str(str);
PRINTVAR(newstr)
return newstr;
}
int main() {
#if 0
exe1("Hello!");
cout<<"=============="<<""<<endl;
cout<<"pointer of pointer"<<endl;
int d=1;
int* j=&d;
//int* j;
//j=(int *)&j1;
int cnt=0;
while(cnt<10)
{
cout<<"--------------"<<""<<endl;
cout<<"ITER= "<<cnt<<""<<endl;
cout<<"j= "<<j<<""<<endl;
cout<<"sizeof(j)= "<<sizeof(j)<<""<<endl;
j=(int*)&j;
cnt++;
}
#endif
//map_with_sort_wrp();
//use_std_sort();
//stable_sort();
exe_operator();
return 0;
}
<file_sep>/cpp/simple_exe/overflow.cpp
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
typedef int INT;
int main () {
INT cnt=0;
char n;
while (cnt<1000) {
cnt++;
cout <<"n="<<(int)n<<" ("<<n<<")\n";
n++;
}
cout
<<setfill('*')
<<setw(50)
<<"Hi there!\n";
return 0;
}
<file_sep>/tcl/tcl_call_cpp/4_swig_manual/run.sh
gcc -c -fPIC example.cpp -I/home/zz/Downloads/tcl8.6.10/generic
gcc -shared -fPIC -o example.so example.o -I/home/zz/Downloads/tcl8.6.10/gener
<file_sep>/cpp/exe_game/tetris/ShapeExist.class.cpp
#include "ShapeExist.class.h"
void ShapeExist::merge(Shape * shape) // merge the new added shape, after the shape doesn't move
{
}
void ShapeExist::checkDeleteRow() // then check whether to delete a row or not
{
}
void ShapeExist::update() // update all location after deleting
{
}
vector<string> ShapeExist::touch(Shape* shape)
{// zjc need unit test!
// "NOT": not touch
// "COINCIDE": coincide
// S:
// E:
// N:
// W:
vector<string> r;
for(Point* p1:dots)
{
for(Point* p2:shape->getDots())
{
if(p1->touch(p2)=="COINCIDE")
{
r.push_back("HIT");
return r;
}
if(p1->touch(p2)=="S") // p2 is in S
r.push_back("S");
if(p1->touch(p2)=="N") // p2 is in S
r.push_back("N");
if(p1->touch(p2)=="E") // p2 is in S
r.push_back("E");
if(p1->touch(p2)=="W") // p2 is in S
r.push_back("W");
}
}
if(r.size()==0)
{
r.push_back("NOT");
return r;
}
else
return r;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/4.8.cpp
#include <stdio.h>
#include <math.h>
#include <iostream>
#include "4.8.h"
#include "lib.h"
using namespace std;
int f4_8 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
int width=40;
for (int i=0;i<=width/2;i+=2) {
print_font_in_the_mid(width,i+1,'#');
}
cout<<endl;
cout<<endl;
width=40;
for (int i=15;i>=8;i-=1) {
print_font_in_the_mid(width,i+1,'x');
}
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
void print_font_in_the_mid(int line_width, int c_cnt, char c) {
int mid=line_width/2;
int begin=mid-1*c_cnt+1;
for (int i=0;i<=begin;i++) {
cout<<" ";
}
for (int i=0;i<c_cnt;i++) {
cout<<c<<" ";
}
cout<<endl;
}
<file_sep>/cpp/leetcode/Longest_Increasing_Subsequence/s.cpp
//#define SIMPLE_LOG
#ifdef SIMPLE_LOG
#define DBG 0
#else
#define DBG 1
#endif
#if (DBG)
#define DLOG(x) cout<<#x<<"="<<x<<" @"<<__LINE__<<endl;
#else
#define DLOG(x)
#endif
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#define PRINT_COUT(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
using namespace std;
class Solution {
public:
int callLevel;
void initCallLevel() {callLevel=0;}
int isIncremental(vector<int>& nums,int from,int to)
{
for(int i=from;i<=to-1;i++)
{
if(nums[i]>nums[i+1])
return false;
}
return true;
}
void printIndentByCallLevel( int callLevel ) {
if(!DBG) {return;}
int i=callLevel;
while(i>0)
{
cout<<" .";
i--;
}
}
void getMaxIncr(vector<int>&nums,int from,int to,int lowBound,vector<int>&vInd)
{
callLevel++;
printIndentByCallLevel(callLevel );
if(DBG)
cout<<"->"<<from<<","<<to<<",lb="<<lowBound<<endl;
//vIndIn={};
//vIndHead={};
if(from>to)
{
printIndentByCallLevel(callLevel--);
if(DBG)
cout<<"<-"<<from<<","<<to<<"lb="<<lowBound<<",size="<<vInd.size()<<endl;
return;
}
if(from==to && nums[from]>lowBound)
{
vInd.push_back(from);
printIndentByCallLevel(callLevel--);
if(DBG)
cout<<"<-"<<from<<","<<to<<"lb="<<lowBound<<",size="<<vInd.size()<<endl;
return;
}
// from < to:
// with from:
vector<int> vIndSub1,vIndSub2;
if(nums[from]>lowBound)
{
vIndSub1.push_back(from);
getMaxIncr(nums,from+1,to,nums[from],vIndSub1);
}
if(DBG)
{
cout<<"sub1=";for(auto i:vIndSub1) cout<<"\t("<<i<<")"<<nums[i];cout<<endl;
}
// without from:
getMaxIncr(nums,from+1,to,lowBound,vIndSub2);
auto added=(vIndSub1.size()>vIndSub2.size())?vIndSub1:vIndSub2;
for(auto i:added)
{
vInd.push_back(i);
}
if(DBG)
{
cout<<"sub2=";for(auto i:vIndSub2) cout<<"\t("<<i<<")"<<nums[i];cout<<endl;
cout<<"resu=";for(auto i:vInd) cout<<"\t("<<i<<")"<<nums[i];cout<<endl;
}
printIndentByCallLevel(callLevel--);
if(DBG)
{
cout<<"<-"<<from<<","<<to<<"lb="<<lowBound<<",size="<<vInd.size()<<endl;
}
}
int lengthOfLIS(vector<int>& nums) {
if(nums.size()==0)
return 0;
////////////////
bool ordered=true;
for(int i=0;i<nums.size()-1;i++)
{
DLOG(i);
if(nums[i]>=nums[i+1])
{
ordered=false;
break;
}
}
if(ordered)
{
return nums.size();
}
////////////////
vector<int> vInd;
cout<<"nums=";
int ind=0;
for(auto i:nums) {cout<<"\t("<<ind++<<")"<<i;}cout<<endl;
getMaxIncr(nums,0,nums.size()-1,-9999,vInd);
return vInd.size();
}
};
int main()
{
DLOG(DBG);
vector<int> v={3,2,5,4,1,7};
//vector<int> v={1,2,3,4};
//vector<int> v={2,2};
Solution s;
s.initCallLevel();
int R=s.lengthOfLIS(v);
DLOG(R);
}
<file_sep>/cpp/POJ/include/poj2965.h
#include "include.top.h"
class GateOfRefrigerator: public Board
{
public:
GateOfRefrigerator(string s):Board(s) {
//cout<<"calling GateOfRefrigerator::GateOfRefrigerator(string)"<<endl;
};
void flip(int,int);
};
void poj2965 ();
<file_sep>/python/workspace_python/design_pattern/src/SimpleFactory/SimpleFactory.py
__author__ = 'jc'
'''
client
|
SimpleFactory abstract_product
|
concrete_product1 concrete_product2
'''
class SimpleFactory:
def getProduct(self,item):
print 'in proc getProduct, retult='+item
if item=='A':
return ProductA()
else:
return ProductB()
class AbstractProduct:
def say(self):
print 'I\'m AbstractProduct!'
class ProductA(AbstractProduct):
def say(self):
print 'I\'m productA'
class ProductB(AbstractProduct):
def say(self):
print 'I\'m productB'
if __name__ == "__main__":
sf = SimpleFactory()
calcA=sf.getProduct('A')
calcA.say()
calcB=sf.getProduct('B')
calcB.say()
<file_sep>/cpp/codewar/John_and_Ann_sign_up_for_Codewars/s.handout.cpp
#include <vector>
#include <string>
#include <iostream>
#include <assert.h>
class Johnann
{
public:
static std::vector<long long> john(long long n);
static std::vector<long long> ann(long long n);
static long long sumJohn(long long n);
static long long sumAnn(long long n);
static void compose(long long n);
private:
static std::vector<long long> v_john;
static std::vector<long long> v_ann;
};
std::vector<long long> Johnann::v_john;
std::vector<long long> Johnann::v_ann;
std::vector<long long> Johnann::john(long long n)
{
compose(n);
n--;
//return john(n,0);
std::vector<long long>::const_iterator first=v_john.begin();
std::vector<long long>::const_iterator last =v_john.begin()+n+1;
std::vector<long long> r(first,last);
return r;
}
//-------------------------------------------------------------------------
std::vector<long long> Johnann::ann(long long n)
{
compose(n);
n--;
//return ann(n,0);
std::vector<long long>::const_iterator first=v_ann.begin();
std::vector<long long>::const_iterator last =v_ann.begin()+n+1;
std::vector<long long> r(first,last);
return r;
}
//-------------------------------------------------------------------------
long long Johnann::sumJohn(long long n)
{
long long r=0;
for(auto v:john(n))
r+=v;
return r;
}
long long Johnann::sumAnn(long long n)
{
long long r=0;
for(auto v:ann(n))
r+=v;
return r;
}
void Johnann::compose(long long n)
{
for(long long i=0;i<n;i++)
{
v_john.push_back(-1);
v_ann.push_back(-1);
}
v_john[0]=0;
v_ann[0]=1;
for(long long i=1;i<n;i++)
{
v_john[i]=i-v_ann [v_john[i-1]];
v_ann[i] =i-v_john[ v_ann[i-1]];
}
}
int main ()
{
//Johnann::ann(6);
//{1, 1, 2, 2, 3, 3};
//Johnann::john(11);
//{0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6};
//Johnann::compose(11);
Johnann::ann(6);
Johnann::john(11);
//Johnann::john(1);
//Johnann::john(4);
//Johnann::john(3,0);
//Johnann::ann(6,0);
//Johnann::ann(4,0);
//Johnann::ann(2,0);
//Johnann::ann(10000);
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/3.6.h
int main3_6 () ;
<file_sep>/cpp/stl_test/s.cpp
#include <string>
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int PrintIt (string& StringToPrint) {
cout <<StringToPrint <<endl;
}
int main (void) {
list <string> ms;
ms.push_back("v0");
ms.push_back("v1");
for_each(ms.begin(),ms.end(),PrintIt);
}
<file_sep>/cpp/POJ/src/poj1753.cpp
#include "include.top.h"
#include <math.h>
#include <iomanip>
#include <map>
#include <string>
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include "poj1753.h"
using namespace std;
#include <fstream>
#define SHOW_DETAILS 0
#define CH0_ENABLE 1
#define CH1_ENABLE 1
#define CH2_ENABLE 1
#define CH3_ENABLE 1
void poj1753 ()
{
cout<<"-----------------------------------------------"<<endl;
cout<<"poj1753"<<endl;
//----------------------------------------------------------
string filename="input/poj1753.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj1753.out";
std::ofstream outfile(filename_out);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
#if CH0_ENABLE
std::cout << "----------------------------------------\n";
std::cout << "ch0. solve the problem\n";
std::cout << "----------------------------------------\n";
Board board_read_file("input/poj1753.in");
cout<<"board_read_file.show()"<<endl;
board_read_file.show();
Board board_read_file_bk=board_read_file;
vector<Board> solution_tranformations;
for(int seed0=0;seed0<pow(2,16);seed0++)
{
Board t;
t.deserialize(seed0);
board_read_file.transformed_by(t);
if (board_read_file.isPure())
solution_tranformations.push_back(t);
}
sort(solution_tranformations.begin(),solution_tranformations.end());
std::cout << "----------------------------------------\n";
cout<<"solution_tranformations"<<endl;
for (auto t:solution_tranformations)
{
t.show();
}
std::cout << "----------------------------------------\n";
//----------------------------------------------------------
// dump output file
outfile<<solution_tranformations[0].sumOfTrue();
#endif
#if CH1_ENABLE
Board board_all_zeros,n,t;
board_all_zeros.show();
std::cout << "----------------------------------------\n";
std::cout << "ch1. find all unit transformation s\n";
std::cout << "----------------------------------------\n";
vector<Board> unit_transforms;
for(int seed0=0;seed0<pow(2,16);seed0++)
{
n=board_all_zeros;
t.deserialize(seed0);
n.transformed_by(t);
if(n.isAllBlack())
{
cout<<"GOT UNIT seed:"<<seed0<<endl;
//t.show();
unit_transforms.push_back(t);
}
}
sort(unit_transforms.begin(),unit_transforms.end());
std::cout << "================================"<< " \n";
cout<<"show unit_transforms:"<<endl;
for ( auto u:unit_transforms)
{
u.show();
}
std::cout << "================================"<< " \n";
#endif
#if 0
for (auto t:unit_transforms)
{
PRINTVAR(t.sumOfTrue());
t.show();
}
#endif
std::cout << "----------------------------------------\n";
#if CH2_ENABLE
std::cout << "----------------------------------------\n";
std::cout << "ch2. find the shortest clean T for a random board \n";
std::cout << "----------------------------------------\n";
Board before,before_bk,after,transformation,t_init;
//before.show();
t_init.random(time(NULL));
//t_init.deserialize(1+4+64+256);
//t_init.deserialize(1);
before.transformed_by(t_init);
//before.random(time(NULL));
//before.deserialize(3+16);
after=before;
before_bk=before;
after.show();
//#if 1
int seed=0;
int min_transformation_cnt=99;
Board min_transformation,min_after;
vector<Board> restore_transformations;
while (true)
{
after=before_bk;
before=before_bk;
//PRINTVAR(seed);
transformation.deserialize(seed);
//transformation.show();
after.transformed_by(transformation);
//after.show();
if (after.isPure())
{
cout<<"--------------->"<<endl;
cout<<"\tV"<<endl;
cout<<"before:"<<endl;
before.show();
cout<<"transformation:"<<endl;
transformation.show();
cout<<"after:"<<endl;
after.show();
#if SHOW_DETAILS
cout<<"DETAILS:"<<endl;
before.transformed_by(transformation,true);
#endif
restore_transformations.push_back(transformation);
if (transformation.sumOfTrue()<min_transformation_cnt)
{
min_transformation_cnt=transformation.sumOfTrue();
min_transformation=transformation;
min_after=after;
}
cout<<"<---------------"<<endl;
}
if (seed==pow(2,16)) // find all possible transformation(s)
{
break;
}
seed++;
}
if (min_transformation_cnt!=99)
{
PRINTVAR(min_transformation_cnt);
//PRINTVAR(seed);
cout<<"before:"<<endl;
before.show();
cout<<"transformation:"<<endl;
min_transformation.show();
cout<<"after:"<<endl;
min_after.show();
#if SHOW_DETAILS
cout<<"DETAILS:"<<endl;
before=before_bk;
before.transformed_by(min_transformation,true);
#endif
}
else
{
cout<<"find all possible transformation(s) but no answer"<<endl;
before.show();
}
sort(restore_transformations.begin(),restore_transformations.end());
#endif // end of CH2_ENABLE
#if CH3_ENABLE
std::cout << "----------------------------------------\n";
std::cout << "ch3. find combined T in restore_transformations \n";
std::cout << "----------------------------------------\n";
vector<Board> unit_transforms_wo_zeros;
for (auto t:unit_transforms) // gen unit_transforms_wo_zeros, because the Board fill 0s will be contained by all transforms
{
if(t.sumOfTrue()!=0)
unit_transforms_wo_zeros.push_back(t);
}
int size=restore_transformations.size();
PRINTVAR(size);
int cntr=0;
for (auto iter=restore_transformations.begin();iter!=restore_transformations.end();)
{
auto t=*iter;
PRINTVAR(cntr);
int ind=t.transformIsCombined(unit_transforms_wo_zeros);
if (ind!=-1)
{
cout<<"reduced:"<<endl;
Board reduced=t-unit_transforms_wo_zeros[ind];
reduced.show();
auto find_it=find(restore_transformations.begin(),restore_transformations.end(),reduced);
if(find_it==restore_transformations.end()) // restore_transformations doesnot contain reduced
{
cout<<"push_back:"<<endl;
restore_transformations.push_back(reduced);
}
cout<<"erase:"<<endl;
restore_transformations.erase(iter); // delete the combined transform
size=restore_transformations.size();
PRINTVAR(size);
}
else
{
iter++;
}
//if(iter!=restore_transformations.end())
//iter++;
cntr++;
}
size=restore_transformations.size();
PRINTVAR(size);
sort(restore_transformations.begin(),restore_transformations.end());
std::cout << "================================"<< " \n";
cout<<"show restore_transformations:"<<endl;
for ( auto r:restore_transformations)
{
r.show();
}
std::cout << "================================"<< " \n";
#endif // end of CH3_ENABLE
//after.transformed_by(before);
#if 0
for (int cnt=0;cnt<=10;cnt++)
{
std::cout << "================================"<< " \n";
before.random(time(NULL)+cnt);
before.show();
before.serialize();
Board a1=before;
a1.flip(0,1);
a1.flip(1,1);
Board a2=before;
a2.flip(1,1);
a2.flip(0,1);
if(a1!=a2)
{
cout<<"a1!=a2"<<endl;
a1.show();
a2.show();
}
}
#endif
//show_board(board);
//----------------------------------------------------------
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
#if 0
Board t1,t2,t3;
t1.deserialize(2);
t2.deserialize(3);
t1.show();
t2.show();
//t3=t1-t2;
//t3.show();
bool contain=t1%t2;
PRINTVAR(contain);
#endif
}
//---------------------------------------------------------------------
// OPERATORS:
//---------------------------------------------------------------------
void Board::operator= (const Board & rhs)
{
vector<vector<bool>> b=rhs.getBoard();
for(int row=0;row<getHeight();row++)
{
for(int col=0;col<getWidth();col++)
{
//board[row][col]=b[row][col];
setBoard(row,col,b[row][col]);
}
}
};
bool Board::operator== (const Board & rhs) const
{
for(int row=0;row<getHeight();row++)
{
for(int col=0;col<getWidth();col++)
{
if (board[row][col]!=rhs.getBoard()[row][col])
return false;
}
}
return true;
};
bool Board::operator!= (const Board & rhs) const {return !(*this==rhs);};
bool Board::operator< (const Board & rhs) const
{
return sumOfTrue()<rhs.sumOfTrue();
};
bool Board::operator> (const Board & rhs) const
{
return sumOfTrue()>rhs.sumOfTrue();
};
Board Board::operator+ (Board & rhs)
{
Board r;
//int n=this->serialize()| rhs.serialize();
int n1=serialize();
int n2=rhs.serialize();
int n=n1|n2;
//PRINTVAR(n1);
//PRINTVAR(n2);
//PRINTVAR(n);
r.deserialize(n);
return r;
};
Board Board::operator- (Board & rhs) // set sub
{
Board r;
int n1=serialize();
int n2=rhs.serialize();
int n=n1&(~n2);
//PRINTVAR(n1);
//PRINTVAR(n2);
//PRINTVAR(n);
r.deserialize(n);
return r;
};
bool Board::operator% (Board & rhs) // set contain
{
if (*this == rhs)
return true;
else if ((*this-rhs).sumOfTrue()>0 && (rhs-*this).sumOfTrue()==0)
{
return true;
}
else
{
return false;
}
};
//---------------------------------------------------------------------
// DEFINITIONS:
//---------------------------------------------------------------------
void show_board(vector<vector<bool>> board)
{
cout<<"-----------------------------------"<<endl;
for(auto line:board)
{
for (auto c:line)
{
string s=c?".":"@";
cout<<s<<"\t";
}
cout<<endl;
}
cout<<"-----------------------------------"<<endl;
}
Board::Board()
{
for(int row=0;row<4;row++)
{
vector<bool> line_vec;
for(int col=0;col<4;col++)
{
line_vec.push_back(0);
}
board.push_back(line_vec);
}
}
Board::Board(string in_file_name)
{
//cout<<"calling Board::Board(string)"<<endl;
std::ifstream infile(in_file_name);
if (!infile)
std::cerr << "Couldn't open " << in_file_name << " for reading\n";
string line;
while (infile >> line)
{
vector<bool> line_vec;
for(auto c:line)
{
//cout<<"GOT:"<<c<<endl;
if(c=='b' || c=='-')
line_vec.push_back(0);
else
line_vec.push_back(1);
}
board.push_back(line_vec);
}
}
void Board::show()
{
show_board(board);
}
void Board::flip(int row,int col)
{
//cout<<"calling Board::flip("<<row<<","<<col<<")"<<endl;
int r,c;
r=row;
c=col;
if(r>=0&&r<=3&&c>=0&&c<=3)
board[r][c]=!board[r][c];
r=row+1;
c=col;
if(r>=0&&r<=3&&c>=0&&c<=3)
board[r][c]=!board[r][c];
r=row-1;
c=col;
if(r>=0&&r<=3&&c>=0&&c<=3)
board[r][c]=!board[r][c];
r=row;
c=col+1;
if(r>=0&&r<=3&&c>=0&&c<=3)
board[r][c]=!board[r][c];
r=row;
c=col-1;
if(r>=0&&r<=3&&c>=0&&c<=3)
board[r][c]=!board[r][c];
}
void Board::random(int seed)
{
//int seed=col+row+time(NULL);
srand (seed);
for (int row=0;row<=3;row++ )
{
for (int col=0;col<=3;col++ )
{
//srand (time(NULL));
/* generate secret number between 1 and 10: */
int randi=rand();
int i = randi % 2;
board[row][col]=i;
}
}
}
int Board::serialize()
{
string s="";
for(auto line:board)
for(auto b:line)
s+=b?"1":"0";
//PRINTVAR(s);
int r=std::stoi(s,nullptr,2);
//PRINTVAR(r);
return r;
}
void Board::deserialize(long i,bool as_binary)
{
//PRINTVAR(i);
string s;
if (as_binary)// treat as binary
{
s=to_string(i);
//PRINTVAR(s);
}
else // treat as decimal
{
s=DecimalToBinaryString(i);
}
//PRINTVAR(s);
int ptr=0;
for (int row=0;row<=3;row++ )
{
for (int col=0;col<=3;col++ )
{
auto c=s[ptr++];
board[row][col]=(c=='1')?true:false;
}
}
}
string DecimalToBinaryString(int a)
{
string binary = "";
int mask = 1;
for(int i = 0; i < 16; i++)
{
if((mask&a) >= 1)
binary = "1"+binary;
else
binary = "0"+binary;
mask<<=1;
}
//cout<<binary<<endl;
return binary;
}
void Board::transformed_by(Board t,bool details)
{
for (int row=0;row<=3;row++ )
{
for (int col=0;col<=3;col++ )
{
if(t.getBoard()[row][col])
{
if (details)
{
show();
cout<<"flip ("<<row<<","<<col<<")"<<endl;
flip(row,col);
show();
}
else
{
flip(row,col);
}
}
}
}
}
void Board::transformed_by(Board t)
{
transformed_by(t,false);
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/DegreeOfSeparation.h
/////////////////////////////////
// P358 Table DegreeOfSeparation
/////////////////////////////////
class DegreeOfSeparation
{
public:
DegreeOfSeparation(string fname,string delim=" ")// METHOD
{
SymbolGraph* sg=new SymbolGraph(fname,delim);
Graph* G=sg->G();
string source="beijing";
if(!sg->contains(source))
{ cout<<source<<" is not in database!"; return; }
int s=sg->index(source);
BreadthFirstPaths* bfs=new BreadthFirstPaths(G,s);
string sink="taiwan";
if(!sg->contains(sink))
{ cout<<sink<<" is not in database!"; return; }
DPRINT("CHECKING from "<<source<<" to "<<sink<<" ...");
int t=sg->index(sink);
if(bfs->hasPathTo(t))
for(int v:bfs->pathTo(t))
cout<<" "<<sg->name(v)<<endl;
int degrees=bfs->pathTo(t).size()-1;
DLOG(degrees);
}
};
class TestDegreeOfSeparation// METHOD
{
public:
TestDegreeOfSeparation(string fname)//METHOD
{
new DegreeOfSeparation(fname);
}
};
void testDegreeOfSeparation()//METHOD
{
new TestDegreeOfSeparation("routes.txt");
}
<file_sep>/cpp/POJ/include/MATRIX.class.h
#ifndef MATRIX_CLASS_H
#define MATRIX_CLASS_H
template<class T>
class Point
{
public:
Point() {loc={0,0};};
Point(T x,T y)
{
loc={x,y};
};
void setLoc(T x,T y){
//loc=make_pair(x,y);
loc={x,y};
};
void setX(T x) {loc.first=x;};
void setY(T y) {loc.second=y;};
pair<T,T> getLoc(){
return loc;
}
T getX () const { return loc.first; };
T getY () const { return loc.second; };
void incrX(){
int u=getX();
u++;
setX(u);
}
void decrX(){
int u=getX();
u--;
setX(u);
}
void incrY(){
int u=getY();
u++;
setY(u);
}
void decrY(){
int u=getY();
u--;
setY(u);
}
void show() {
cout<<"Point\t("<<getX()<<",\t"<<getY()<<")"<<endl;
}
friend ostream& operator<< (ostream& os, Point rhs) {
os<<"Point\t("<<rhs.getX()<<",\t"<<rhs.getY()<<")"<<endl;
return os;
};
private:
pair<T,T> loc;
};
template<class T>
class MATRIX
{
public:
MATRIX(unsigned height,unsigned width,T v=0)
{
mWidth=width;
mHeight=height;
for(T row=0;row<height;row++)
{
vector<T> tmp;
for(T col=0;col<width;col++)
{
tmp.push_back(v);
}
board.push_back(tmp);
}
};
MATRIX(vector<vector<T>> m)
{
for(auto row:m)
{
vector<T> tmp;
for(auto cell:row)
{
tmp.push_back(cell);
}
board.push_back(tmp);
}
}
T getWidth() {return mWidth;};
T getHeight() {return mHeight;};
void setWidth(T w) {mWidth=w;};
void setHeight(T h) {mHeight=h;};
void fill(T v)
{
board.clear();
T width=mWidth;
T height=mHeight;
for(T row=0;row<height;row++)
{
vector<T> tmp;
for(T col=0;col<width;col++)
{
tmp.push_back(v);
}
board.push_back(tmp);
}
};
void show()
{
for(auto row:board)
{
for(auto cell:row)
{
cout<<cell
<<"\t";
}
cout<<endl;
}
};
void show(int markRow,int markCol, string marker="X")
{
int cntRow=0;
for(auto row:board)
{
int cntCol=0;
for(auto cell:row)
{
if(cntRow==markRow && cntCol==markCol)
cout<<marker <<"\t";
else
cout<<cell <<"\t";
cntCol++;
}
cout<<endl;
cntRow++;
}
}
bool isOnEdge(unsigned row,unsigned col)
{
//if(row>=board.size())
//if( col>=board[0].size())
//if( col<0)
//if( row<0)
if( row>=board.size()
|| col>=board[0].size()
|| col<0
|| row<0)
{
cout<<"Error: illegal:("<<row<<","<<col<<")"<<endl;
cout<<"Board:"<<endl;
show();
return false;
}
if(row==0 || row==board.size()-1)
return true;
if(col==0 || col==board[0].size()-1)
return true;
}
bool isOnEdge(Point<int>p)
{
return isOnEdge(p.getX(),p.getY());
}
private:
T mWidth;
T mHeight;
vector<vector<T>> board;
};
# endif
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN_good/include/2.3_link_list.h
#ifndef M_2_3_LINK_LIST_H
#define M_2_3_LINK_LIST_H
struct LNode {
int data;
LNode * next;
};
//LNode * head;
#endif //M_2_3_LINK_LIST_H
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch1_life_game/src/main.cpp
#include <math.h>
#include <stdio.h>
#include <iostream>
#include "life_game.h"
#include "utility.h"
//#include "life_game.h"
using namespace std;
int main() {
cout<<"Life world!"<<endl;
main_life_game();
//while(true){
// cout<<user_say_yes()<<endl;
//}
return 0;
}
<file_sep>/tcl/tcl_call_cpp/3/Makefile
t = main
# TCL_LIBS = -L/usr/lib -ltcl8.6
TCL_LIBS = -L/home/zz/Downloads/tcl8.6.10/library -ltcl8.6
all: $t
clean:
rm -f $t core
main:main.c fract.c
gcc -I. -I/home/zz/Downloads/tcl8.6.10/generic ${TCL_LIBS} -o $@ main.c fract.c
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.2_directed_graph/main.cpp
#include "../../include/include.h"
#include "Digraph.h"
#include "SymbolDigraph.h"
#include "DirectedDFS.h"
#include "DirectedCycle.h"
#include "DepthFirstOrder.h"
#include "Topological.h"
//////////////////////////////
// MAIN
//////////////////////////////
int main()
{
//new TestDigraph();
//testSymbolDigraph();
//new TestDirectedDFS();
//new TestDirectedCycle();
new TestTopological();
return 0;
}
//////////////////////////////
//////////////////////////////
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph/GraphAdjList.h
#include "GraphBase.h"
#include <set>
class GraphAdjList:public GraphBase {
public:
GraphAdjList(int ve);
GraphAdjList(string fname);
int V();
int E();
void addEdge(int v,int w);
vector<int> adj(int v);
private:
int mV;
int mE;
vector<vector<int>> mAdj;
// P337 Table4.1.4
public:
vector <int> search(int s); // find all nodes connected s
bool marked(int s,int v); // does v connected to s
int count(int s); // # of nodes connected s
};
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN/src/main.cpp
#include "include.top.h"
using namespace std;
//void printvar (int& var) ;
int main() // FUNC
{
float f=3.121;
printf("========= %f \n",f);
printf("========= %d \n",f);
printf("========= %x \n",f);
printf("========= %s \n",f);
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
//string s="test";
//cout<<"this is "<<s<<endl;
//return 0;
////////////////////////////////////////////////
//f_test_linear_list();
//f_test_Stack() ;
f_test_LinkList() ;
int a = 1010;
string b="test";
PRINTVAR(a);
PRINTVAR(b);
//printvar (a);
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
cout<<"END"<<endl;
return 0;
}
//void printvar (int& var) {
////int v=*var;
//cout<<VNAME(var)<<" = "<<var<<endl;
//}
<file_sep>/python/workspace_python/libs/msoffice2ps.py
import win32com.client, time, pythoncom
"""
MSOffice2PS - Microsoft Office to Postscript Converter 1.1
Makes a Postscript file from Word-, Excel- or Powerpoint.
Now with mutex support for Powerpoint. Because Powerpoint can
only run as a single instance.
usage:
first: import msoffice2ps in the script, where it should be used
then call the convert-function.
import msoffice2ps
msoffice2ps.word('wordfilename', 'psfilename', 'ps_printername')
msoffice2ps.excel('excelfilename', 'psfilename', 'ps_printername')
msoffice2ps.powerpoint('powerpointfilename', 'psfilename', 'ps_printername')
Dipl.-Ing. <NAME> -> http://www.goermezer.de
"""
def word(wordfile, psfile, printer):
pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
myWord = win32com.client.DispatchEx('Word.Application')
myWord.Application.ActivePrinter = printer
myDoc = myWord.Documents.Open(wordfile, False, False, False)
myDoc.Saved=1
myWord.Application.NormalTemplate.Saved = 1
myWord.PrintOut(True, False, 0, psfile)
while myWord.BackgroundPrintingStatus > 0:
time.sleep(0.1)
myDoc.Close()
myWord.Quit()
del myDoc
del myWord
pythoncom.CoUninitialize()
def excel(excelfile, psfile, printer):
pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
myExcel = win32com.client.DispatchEx('Excel.Application')
myExcel.Application.AskToUpdateLinks = 0
Excel = myExcel.Workbooks.Open(excelfile, 0, False, 2)
Excel.Saved = 1
Excel.PrintOut(1, 5000, 1, False, printer, True, False, psfile)
Excel.Close()
myExcel.Quit()
del myExcel
del Excel
pythoncom.CoUninitialize()
def powerpoint(powerpointfile, psfile, printer):
from win32event import CreateMutex
from win32api import GetLastError
from winerror import ERROR_ALREADY_EXISTS
from sys import exit
#the guid in the next line must be unique !!!
handle = CreateMutex ( None, 1, '{D0E858DF-985E-4907-B7FB-8D732C3FC3B9}' )
if GetLastError ( ) == ERROR_ALREADY_EXISTS:
print 'Powerpoint conversion already working'
exit ( 1 )
pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
myPowerpoint = win32com.client.DispatchEx('Powerpoint.Application')
myPpt = myPowerpoint.Presentations.Open(powerpointfile, False, False, False)
myPpt.PrintOptions.PrintInBackground = 0
myPpt.PrintOptions.ActivePrinter = printer
myPpt.Saved = 1
myPpt.PrintOut(1, 5000, psfile, 0, False)
myPpt.Close()
#myPowerpoint.Quit()
del myPpt
#del myPowerpoint
pythoncom.CoUninitialize()
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN_good/include/2.1_MyStack.h
#ifndef M_2_1_MYSTACK_H
#define M_2_1_MYSTACK_H
#include "include.top.h"
using namespace std;
//int instanceCounterMyList=-1;
class MyStack:public MyList
{
public:
void Push(int e);
int Pop();
void Unshift(int e);
int Shift();
private:
string m_name;
int *m_list_element;
int *m_list_relation;
int m_list_length;
int m_heap_length;
};
#endif //M_2_1_MYSTACK_H
<file_sep>/cpp/exe_game/tetris/Display.class.cpp
#include "global.h"
#include "Display.class.h"
void Display::show(bool compacted)
{
auto board=m->getBoard();
for(vector<string> row:board)
{
for(string cell:row)
{
cout<<cell;
if(!compacted)
cout<<"\t";
}
cout<<endl;
}
};
void Display::show(int markRow,int markCol, string marker)
{
PRINT_DEBUG_INFO();
auto board=m->getBoard();
PRINT_DEBUG_INFO();
int cntRow=0;
PRINT_DEBUG_INFO();
for(auto row:board)
{
PRINT_DEBUG_INFO();
int cntCol=0;
for(auto cell:row)
{
PRINT_DEBUG_INFO();
if(cntRow==markRow && cntCol==markCol)
cout<<marker <<"\t";
else
cout<<cell <<"\t";
PRINT_DEBUG_INFO();
cntCol++;
}
PRINT_DEBUG_INFO();
cout<<endl;
cntRow++;
PRINT_DEBUG_INFO();
}
}
<file_sep>/cpp/6_EXEs/src/use_std_sort.cpp
#include "include.top.h"
#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
int use_std_sort()
{
cout<<"----------------------------------------"<<endl;
std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
cout<<"BEFORE:"<<endl;
PRINT_VECTOR_hor(s);
cout<<"----------------------------------------"<<endl;
// sort using the default operator<
cout<<"default sort:"<<endl;
std::sort(s.begin(), s.end());
PRINT_VECTOR_hor(s);
cout<<"----------------------------------------"<<endl;
cout<<"use std::greater:"<<endl;
// sort using a standard library compare function object
std::sort(s.begin(), s.end(), std::greater<int>());
PRINT_VECTOR_hor(s);
cout<<"----------------------------------------"<<endl;
// sort using a custom function object
cout<<"use customLess:"<<endl;
struct {
bool operator()(int a, int b)
{
return a < b;
}
} customLess;
std::sort(s.begin(), s.end(), customLess);
PRINT_VECTOR_hor(s);
cout<<"----------------------------------------"<<endl;
cout<<"use lambda:"<<endl;
// sort using a lambda expression
std::sort(s.begin(), s.end(),
[](int a, int b) {
return b < a;
});
PRINT_VECTOR_hor(s);
cout<<"----------------------------------------"<<endl;
}
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN/include/2.1_func.h
#ifndef M_2_1_func_H
#define M_2_1_func_H
bool compare(int a,int b);
bool visit(int* a);
int f_test_linear_list() ;
int f_test_Stack();
int f_test_LinkList();
bool compare(int a,int b);
bool visit(int *a);
#endif //M_2_1_func_H
<file_sep>/cpp/POJ/include/ROBOT.class.h
#include "lib.h"
#include "MATRIX.class.h"
class ROBOT
{
public:
ROBOT(Point<int> l,string h){loc=l;head=h;};
void setLoc(Point<int> l) {loc=l;};
Point<int> getLoc() {return loc;};
void setHead(string h) {head=h;};
string getHead() {return head;};
void setBoard(MATRIX<int>* p){board=p;};
MATRIX<int>* getBoard() {return board;};
void run(){
for(auto i:instTable)
{
PRINTVAR(i);
}
};
void exe(string cmd) {
string towards=split(cmd," ")[0];
int multiply =stoi(split(cmd," ")[1]);
PRINTVAR(towards);
PRINTVAR(multiply);
if(towards=="F")
moveFoward(multiply);
else
turn(towards,multiply);
};
void turn(string to) {
if(head == "N")
{
if(to == "L" ) head="W";
if(to == "R" ) head="E";
}
if(head == "E")
{
if(to == "L" ) head="N";
if(to == "R" ) head="S";
}
if(head == "W")
{
if(to == "L" ) head="S";
if(to == "R" ) head="N";
}
if(head == "S")
{
if(to == "L" ) head="E";
if(to == "R" ) head="W";
}
};
void turn(string to,int mult) {
for(int i=0;i<mult;i++)
turn(to);
};
bool moveFoward() {
if(head == "N") loc.incrY();
if(head == "E") loc.incrX();
if(head == "W") loc.decrX();
if(head == "S") loc.decrY();
PRINT_DEBUG_INFO();
if(!getBoard()->isOnEdge(getLoc().getX(),getLoc().getY()))
{
PRINT_DEBUG_INFO();
return false;
}
else
{
return true;
}
};
bool moveFoward(int mult) {
for(int i=0;i<mult;i++)
if(!moveFoward())
return false;
return true;
};
void addInst(string inst) {
instTable.push_back(inst);
};
void show() {
cout<<"ROBOT is in:\t";
loc.show();
board->show(getLoc().getY(),getLoc().getX(),"R");
cout<<"\thead to\t"
<<head
<<"\nInstructions:\t"
<<endl;
for(auto i:instTable)
{
cout<<i<<endl;
}
};
private:
vector<string> instTable;
Point<int> loc;
string head;
MATRIX<int>* board;
};
<file_sep>/cpp/POJ/src/poj3295.cpp
#include "include.top.h"
#include "gnuplot_i.h"
#include "poj3295.h"
#include "WFF.class.h"
#include <math.h>
#include <iomanip>
#include <map>
#include <fstream>
using namespace std;
void poj3295 ()
{
#if 1
cout<<"-----------------------------------------------"<<endl;
cout<<"poj3295"<<endl;
//----------------------------------------------------------
string filename="input/poj3295.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj3295.out";
// clean the file "output/poj3295.out"
std::ofstream outfile_init(filename_out);
outfile_init.close();
std::ofstream outfile(filename_out,ios::app);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
string line;
while(getline(infile,line))
{
cout<<"-------------------------------------"<<endl;
//cout<<"LINE:"<<endl;
//PRINTVAR(flag_end_of_one_case);
if (line == "0") // end of one case
{
break;
}
else
{
PRINTVAR(line);
WFF w(line);
w.show();
assert(w.isLegal());
//cout<<"w_breakIntoUnitWFFs"<<endl;
//w.breakIntoUnitWFFs();
cout<<"w_showMUnitWFFs---------------------------"<<endl;
//PRINT_DEBUG_INFO();
w.showMUnitWFFs();
auto patterns=w.genTestPatterns();
vector<bool> values;
cout<<"----------------"<<endl;
cout<<"TRUTH TABLE:"<<endl;
for(auto p:patterns)
{
bool v=w.calcValue(p);
cout<<v<<":\t"<<p<<endl;;
values.push_back(v);
}
cout<<"----------------"<<endl;
bool flag_all1=true,flag_all0=true;
for(auto v:values)
{
if(v==true)
flag_all0=false;
if(v==false)
flag_all1=false;
}
if(flag_all1)
cout<<"Tautology:\t"<<w.getMForm()<<endl;
else if(flag_all0)
cout<<"Inv-Tautology:\t"<<w.getMForm()<<endl;
else
cout<<"Non-Tautology:\t"<<w.getMForm()<<endl;
}
}
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
//----------------------------------------------------------
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
outfile.close();
//for(int cnt=0;cnt<=100;cnt++)
//{
//float rx=((float)(random()%100))/100;
//float ry=((float)(random()%100))/100;
//cout<<rx<<" "<<ry<<endl;
//}
#endif
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/4.5.h
# include "lib.h"
int f4_5 () ;
<file_sep>/cpp/POJ/src/poj1000.cpp
#include "include.top.h"
using namespace std;
#include <fstream>
void poj1000 ()
{
cout<<"-----------------------------------------------"<<endl;
cout<<"poj1000"<<endl;
//----------------------------------------------------------
string filename="input/poj1000.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj1000.out";
std::ofstream outfile(filename_out);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
int a, b;
int sum;
while (infile >> a >> b)
{
sum=a+b;
//cout<<"sum="<<sum<<endl;
outfile<<a<<"\t+\t"<<b<<"\t=\t"<<sum<<endl;
}
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
}
<file_sep>/cpp/exe_game/tetris/Matrix.class.cpp
#include "global.h"
#include "Matrix.class.h"
using namespace std;
Matrix::Matrix(unsigned height,unsigned width,string v)
{
mWidth=width;
mHeight=height;
for(unsigned row=0;row<height;row++)
{
vector<string> tmp;
for(unsigned col=0;col<width;col++)
{
tmp.push_back(v);
}
board.push_back(tmp);
}
};
Matrix::Matrix(vector<vector<string> > m)
{
for(vector<string> row:m)
{
vector<string> tmp;
for(string cell:row)
{
tmp.push_back(cell);
}
board.push_back(tmp);
}
};
bool Matrix::isOnEdge(unsigned row,unsigned col)
{
//if(row>=board.size())
//if( col>=board[0].size())
//if( col<0)
//if( row<0)
if( row>=board.size()
|| col>=board[0].size()
|| col<0
|| row<0)
{
cout<<"Error: illegal:("<<row<<","<<col<<")"<<endl;
cout<<"Board:"<<endl;
//show();
return false;
}
if(row==0 || row==board.size()-1)
return true;
if(col==0 || col==board[0].size()-1)
return true;
return false; // bug?
}
bool Matrix::isOnEdge(int row,int col)
{
return isOnEdge(row,col);
}
//void Matrix::addShape(Shape* shape,int ul_row, int ul_col,string anchor)
//{
// shape->ul_row=ul_row;
// shape->ul_col=ul_col;
// shapeList.push_back(shape);
//};
void Matrix::addShape(Shape* shape)
{
shapeList.push_back(shape);
};
void Matrix::deleteShape(Shape* shape)
{
deleteFromVectorShape(&shapeList,shape);
//shapeList.push_back(shape);
};
Shape* Matrix::getShape()
{
//PRINTVAR(shapeList.size());
if(shapeList.size()==0)
return 0;
else
return shapeList.back();
}
void Matrix::applyShape(Shape* shape){// mark shape into board
};
bool Matrix::tick()
{
bool dropSucceed=false;
bool dropSucceed_bk=dropSucceed;
allShapesAreSteady=true;
for (auto shapePtr:shapeList)
{
if(shapePtr->steady)
continue;
// if not hit bottom or other shapes
dropSucceed_bk=dropSucceed;
dropSucceed=shapePtr->drop();
PRINTVAR(dropSucceed);
PRINTVAR(dropSucceed_bk);
if(!dropSucceed && !dropSucceed_bk) // steady
{
shapePtr->steady=true;
}
if(shapePtr->steady==false)
allShapesAreSteady=false;
shapePtr->update(); // apply data to board
}
if(allShapesAreSteady)
{
// check clean rows
// foreach shapes to form list[row] if full clean row
// clean row: foreach shapes { shape->clean(row)}
PRINT_DEBUG_INFO_PREFIX("ALL STEADY!!!");
for(int r=mHeight-1;r>=0;r--)
if(rowIsFull(r))
{
cout<<"ROW IS FULL("<<r<<")"<<endl;
cleanRow(r);
}
//
// shape->clean(row) means:
// dots under row: not change
// dots in row: delete
// dots above row: drop one row
if(rowIsEmpty(mHeight-1))
{
for (auto shapePtr:shapeList)
{
// zjc here: bug in it:
shapePtr->drop();
}
}
// check if dead
if(!rowIsEmpty(0))
{
cout<<"DEAD!!!!!!!!!!!!!!!!!"<<""<<endl;
return false;
}
}
return true;
}
void Matrix::clear()
{
int width=mWidth;
int height=mHeight;
for(unsigned row=0;row<height;row++)
{
for(unsigned col=0;col<width;col++)
{
board[row][col]="X";
}
}
};
void Matrix::update()
{
clear();
//PRINTVAR(shapeList.size());
for (auto shapePtr:shapeList)
{
vector<Point*> vector_dots_in_shape=shapePtr->getDots();
//PRINTVAR(vector_dots_in_shape.size());
//PRINT_DEBUG_INFO_PREFIX("core dump");
for(Point* dot:vector_dots_in_shape)
{
//PRINT_DEBUG_INFO_PREFIX("core dump");
//PRINTVAR(dot->x);
//PRINTVAR(dot->y);
//PRINTVAR(mHeight);
//PRINTVAR(mWidth);
PRINTVAR(shapePtr->steady);
assert(dot->x>=0);
assert(dot->y>=0);
assert(dot->x<=mHeight-1);
assert(dot->y<= mWidth-1);
if(shapePtr->steady)
board[dot->x][dot->y]="s";
else
board[dot->x][dot->y]="0";
}
//PRINT_DEBUG_INFO_PREFIX("core dump");
}
//PRINT_DEBUG_INFO_PREFIX("core dump");
};
bool Matrix::rowIsFull(int row)
{
PRINT_DEBUG_INFO_PREFIX(row);
vector<int> rowVec;
for(Shape* one_shape:shapeList)
{
//PRINT_DEBUG_INFO();
//PRINTVAR(one_shape);
auto dots=one_shape->getDots();
for(Point* one_dot:dots)
{
//PRINTVAR(one_dot);
if(one_dot->x==row)
rowVec.push_back(one_dot->y);
}
}
PRINTVAR(rowVec.size());
// check:
if(rowVec.size()==0)
return false;
if(rowVec.size()<mWidth)
return false;
PRINT_VECTOR_hor(rowVec);
//PRINT_DEBUG_INFO();
sort(rowVec.begin(),rowVec.end());
PRINT_VECTOR_hor(rowVec);
for(int i=0;i<getWidth();i++)
{
if(rowVec[i]!=i)
return false;
}
return true;
}
bool Matrix::rowIsEmpty(int row)
{
PRINT_DEBUG_INFO();
print();
for(Shape* one_shape:shapeList)
{
auto dots=one_shape->getDots();
for(Point* one_dot:dots)
{
if(one_dot->x==row)
return false;
}
}
return true;
}
void Matrix::cleanRow(int row)
{
PRINT_DEBUG_INFO();
//print();
PRINTVAR(shapeList.size());
//for(Shape* one_shape:shapeList)
for (auto iter=shapeList.begin();iter!=shapeList.end();)
{
Shape* one_shape=*iter;
PRINTVAR(*one_shape);
one_shape->cleanRow(row);
vector<Point*> dots=one_shape->getDots();
auto size1=shapeList.size();
if(dots.size()==0)
{
deleteFromVectorShape(&shapeList,one_shape);
PRINTVAR(size1);
PRINTVAR(shapeList.size());
assert(size1==shapeList.size()+1);
}
else
{
iter++;
}
}
PRINTVAR(shapeList.size());
PRINT_DEBUG_INFO();
}
void Matrix::print()
{
PRINT_DEBUG_INFO_PREFIX("---------------------------------");
for(Shape* one_shape:shapeList)
{
for(Point* one_dot:one_shape->getDots())
{
PRINTVAR_hor(*one_dot);
}
cout<<""<<""<<endl;
}
PRINT_DEBUG_INFO_PREFIX("---------------------------------");
}
<file_sep>/cpp/5_BOOK_CPP_PRIMER/include/exe_2.3.1.h
void exe_2_3_1() ;
<file_sep>/cpp/exe_reference_to_pointer/main.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_POINTER1(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER2(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<"\t->\t"<<**a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER(a) PRINT_POINTER1(a)
#include <iostream>
#include <map>
using namespace std;
void f(int** pptr);
void print_ptr(int* j);
int main()
{
std::cout<<"------------------------------"<<std::endl;
std::cout<<"SHOW:"<<std::endl;
int i=1;
int* ptr=&i;
int ** pptr=&ptr;
PRINT_POINTER2(pptr);
f(pptr);
PRINT_POINTER2(pptr);
std::cout<<"------------------------------"<<std::endl;
PRINT_POINTER1(*pptr);
std::cout<<"------------------------------"<<std::endl;
}
void f(int** pptr)
{
int* u=new int(2);
//int* ptr=*pptr;
PRINT_POINTER(pptr);
*pptr=u;
PRINT_POINTER(pptr);
}
//void print_ptr(int*j)
//{
// cout<<"=============="<<""<<endl;
// cout<<"pointer of pointer"<<endl;
// //int* j;
// //j=(int *)&j1;
// cout<<"j\t=\t"<<j;
// cout<<"\t->\t"<<*j;
// int cnt=0;
// void* jbk;
// //while(cnt<10)
// //{
// // //cout<<"--------------"<<""<<endl;
// // //cout<<"ITER= "<<cnt<<""<<endl;
// // //cout<<"j= "<<j<<""<<endl;
// // //cout<<"sizeof(j)= "<<sizeof(j)<<""<<endl;
// // jbk=j;
// // j=(int*)&j;
// // if(j==jbk)
// // break;
// // cout<<"\t->\t"<<j;
// // cnt++;
// //}
//}
<file_sep>/cpp/6_EXEs/include/map_with_sort.h
#include<map>
using namespace std;
using std::map;
int map_with_sort_wrp() ;
//template <class T> struct is_less : binary_function <T,T,bool> {
// bool operator() (const T& x, const T& y) const
// {return x>y;}
//};
template <class T> struct is_less : std::binary_function <T,T,bool> {
bool operator() (const T& x, const T& y) const
{return x>y;}
};
//void foo(map<string, int, is_less<string> > m);
void foo(map<string, int, is_less<string> > );
<file_sep>/cpp/POJ_separated/1001/run.sh
rm a.out; g++ -v -g -Wall -std=c++11 poj.cpp ; ./a.out
#rm a.out; g++ -v -g -Wall -std=c++11 s.handout.cpp ; ./a.out
<file_sep>/cpp/POJ/include/poj1328.h
#ifndef POJ1328_H
#define POJ1328_H
#include "include.top.h"
#include "gnuplot_i.h"
//#include "gnuplot_i.new.hpp"
class Point
{
public:
Point() {loc={0,0};D=0;};
Point(float x,float y)
{
loc={x,y};
D=0;
};
Point(float x,float y,float d)
{
loc={x,y};
D=d;
};
void setLoc(float x,float y){
//loc=make_pair(x,y);
loc={x,y};
};
void setD(float d) {D=d;};
float getD() {return D;};
pair<float,float> getLoc(){
return loc;
}
float getX () const { return loc.first; };
float getY () const { return loc.second; };
void show() {
cout<<"Point\t("<<getX()<<",\t"<<getY()<<"), D="<<D<<endl;
}
pair<float,float> getXCover(float) ;
bool coverPointOnXAxis(Point targetP) { // this point covers the targetP(type=coverPointOnXAxis) on x-axis
pair<float,float> cover=getXCover(D) ;
if(targetP.getX()>=cover.first && targetP.getX()<=cover.second)
{
return true;
}
return false;
};
friend ostream& operator<< (ostream& os, Point rhs) {
os<<"Point\t("<<rhs.getX()<<",\t"<<rhs.getY()<<"), D="<<rhs.getD()<<endl;
return os;
};
private:
pair<float,float> loc;
float D;
};
class PointOnXAxis:public Point
{
public:
PointOnXAxis():Point(){};
PointOnXAxis(float x,float y):Point(x,(float)0){};
PointOnXAxis(float x):Point(x,(float)0){};
bool isLeftBoardOfCoverage;
bool operator< (const PointOnXAxis rhs) const {return getX()<rhs.getX();};
//void coverIslandsPushBack(Point p){coverIslands.push_back(p);};
vector<Point> coverIslands;
private:
};
class Case
{
public:
int N;
float D;
//pair<float,float> coord;
vector<Point> islands;
vector<PointOnXAxis> radars;
vector<pair<float,float>> covers;
void show();
void solve();
bool checkLegality();
};
void poj1328();
void show(vector<pair<float,float>>) ;
void wait_for_key(); // Programm halts until keypress
class GUI
{
public :
GUI(){
GUI_DRAW_NPOINTS=100;
//Gnuplot g("GUI");
//string s="";
Gnuplot g;
g.reset_all();
g.reset_plot();
g.set_grid();
try {
}
catch (GnuplotException ge)
{
cout << ge.what() << endl;
}
};
// void drawCircle(double xc,double yc,double r,string style,string info);
void drawCircle(double xc,double yc,double r,string style,string info="")
{
std::vector<double> x, y ;
//const double PI=3.1415926;
double theta=0;
double theta_step=2*PI/GUI_DRAW_NPOINTS;
for (int i = 0; i < GUI_DRAW_NPOINTS; i++) // fill double arrays x, y, z
{
x.push_back(xc+r*(double)cos(theta)); // x[i] = i
y.push_back(yc+r*(double)sin(theta)); // y[i] = i^2
theta+=theta_step;
}
//cout << endl << endl << "*** user-defined lists of points (x,y)" << endl;
//string style="points";
g.set_style(style);
g.plot_xy(x,y,info);
}
//void drawPoint(Point p);
void drawPoint(Point p,string mode="lines")
{
drawCircle(p.getX(),p.getY(),0.01,mode);
drawCircle(p.getX(),p.getY(),p.getD(),mode);
}
int GUI_DRAW_NPOINTS;
private:
Gnuplot g;
};
#endif
<file_sep>/tcl/tcl_call_cpp/4_swig_manual/Makefile
t = example.cpp example.so
all: $t
clean:
rm -f $t core *.doc *.o
example.so:example.cpp
gcc -c example.cpp -I/home/zz/Downloads/tcl8.6.10/generic
<file_sep>/cpp/ch12_6.cpp/run.sh
g++ date.cpp
<file_sep>/python/workspace_python/extend_snake/src/AI.py
import pygame
import random
import player
import gl
# ->x
# |
# V
# y
class AI (player.Snake):
def __init__(self, x, y,name):
print 'init AI'
player.Snake.__init__(self, x, y,name)
def update_position(self, dt):
print str(self.x) + ',' + str(self.y)
self.time += dt
# disturb_ratio=0.999
disturb_ratio=2
if self.check_dangerous_down() == 0 and self.h_y != 1:
if random.random() > disturb_ratio:
self.turn_down()
if self.check_dangerous_up() == 0 and self.h_y != -1:
if random.random() > disturb_ratio:
self.turn_up()
if self.check_dangerous_left() == 0 and self.h_x != -1:
if random.random() > disturb_ratio:
self.turn_left()
if self.check_dangerous_right() == 0 and self.h_x != 1:
if random.random() > disturb_ratio:
self.turn_right()
self.check_loop()
if self.h_x == 1 and self.check_dangerous_right():
if self.check_dangerous_up():
self.turn_down()
elif self.check_dangerous_down():
self.turn_up()
else:
self.turn_up_down()
if self.h_x == -1 and self.check_dangerous_left():
if self.check_dangerous_up():
self.turn_down()
elif self.check_dangerous_down():
self.turn_up()
else:
self.turn_up_down()
if self.h_y == 1 and self.check_dangerous_down():
if self.check_dangerous_left():
self.turn_right()
elif self.check_dangerous_right():
self.turn_left()
else:
self.turn_left_right()
if self.h_y == -1 and self.check_dangerous_up():
if self.check_dangerous_left():
self.turn_right()
elif self.check_dangerous_right():
self.turn_left()
else:
self.turn_left_right()
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_UP] and self.h_y != +1 :
self.h_x = 0
self.h_y = -1
elif key_pressed[pygame.K_DOWN] and self.h_y != -1 :
self.h_x = 0
self.h_y = +1
elif key_pressed[pygame.K_LEFT] and self.h_x != +1:
self.h_x = -1
self.h_y = 0
elif key_pressed[pygame.K_RIGHT] and self.h_x != -1:
self.h_x = +1
self.h_y = 0
if self.time >= self.time_tick :
self.tail.insert(0, player.Snake_part((self.x, self.y)))
self.x += self.h_x
self.y += self.h_y
self.head.x, self.head.y = self.x * 10, self.y * 10
if len(self.tail) > self.length :
self.tail.pop(len(self.tail) - 1)
self.time = 0
def update(self, dt, screen):
self.update_position(dt)
self.blit(screen)
self.check_dead()
print 'x:'+str(self.x)+'y:'+str(self.y)
def check_dead(self):
for t in self.tail :
if t.m_x == self.x and t.m_y == self.y :
self.is_dead = True
print 'DEAD REASON: hit my self'
if self.x < 0 or self.x > 40 or self.y < 0 or self.y > 40 :
self.is_dead = True
print 'DEAD REASON: run out of field'
# print gl.snake_list
for snake in gl.snake_list:
if self is snake:
continue
if snake.x == self.x and snake.y==self.y:
self.is_dead= True
print 'DEAD REASON:'+self.name+'head hit '+snake.name+' head!'
for t in snake.tail:
if t.m_x == self.x and t.m_y == self.y:
self.is_dead = True
print 'DEAD REASON:'+self.name+'head hit'+snake.name+'tail!'
def turn_up_down(self):
if random.randint(0, 1):
self.turn_down()
else:
self.turn_up()
def turn_left_right(self):
if random.randint(0, 1):
self.turn_left()
else:
self.turn_right()
def turn_up(self):
self.h_x = 0
self.h_y = -1
def turn_down(self):
self.h_x = 0
self.h_y = +1
def turn_left(self):
self.h_x = -1
self.h_y = 0
def turn_right(self):
self.h_x = +1
self.h_y = 0
def check_dangerous_down(self):
if self.y == 39:
return 1
for t in self.tail :
if t.m_x == self.x:
if t.m_y == self.y + 1:
print 'dangerous down'+self.name
return 1
for snake in gl.snake_list:
if self is snake:
continue
if snake.x == self.x and snake.y==self.y+1:
print 'dangerous down'+self.name
return 1
for t in snake.tail:
if t.m_x == self.x:
if t.m_y == self.y + 1:
print 'dangerous down'+self.name
return 1
return 0
def check_dangerous_up(self):
if self.y == 0:
return 1
for t in self.tail :
if t.m_x == self.x:
if t.m_y == self.y - 1:
print 'dangerous up'+self.name
return 1
for snake in gl.snake_list:
if self is snake:
continue
if snake.x == self.x and snake.y==self.y-1:
print 'dangerous up'+self.name
return 1
for t in snake.tail:
if t.m_x == self.x:
if t.m_y == self.y - 1:
print 'dangerous up'+self.name
return 1
return 0
def check_dangerous_right(self):
if self.x == 39:
return 1
for t in self.tail :
if t.m_y == self.y:
if t.m_x == self.x + 1:
print 'dangerous right'+self.name
return 1
for snake in gl.snake_list:
if self is snake:
continue
if snake.x == self.x+1 and snake.y==self.y:
print 'dangerous right'+self.name
return 1
for t in snake.tail:
if t.m_y == self.y:
if t.m_x == self.x + 1:
print 'dangerous right'+self.name
return 1
return 0
def check_dangerous_left(self):
if self.x == 0:
return 1
for t in self.tail :
if t.m_y == self.y:
if t.m_x == self.x - 1:
print 'dangerous left'+self.name
return 1
for snake in gl.snake_list:
if self is snake:
continue
if snake.x == self.x-1 and snake.y==self.y:
print 'dangerous left'+self.name
return 1
for t in snake.tail:
if t.m_y == self.y:
if t.m_x == self.x - 1:
print 'dangerous left'+self.name
return 1
return 0
def check_loop (self): # check if self loop in a close area
print 'Info:'+self.name+' check loop!'
largest_cnt=-1
cnt =2
for t in self.tail[2:-1]:
if abs(t.m_x-self.x)<=1 and abs(t.m_y-self.y)<=1:
print self.name+'hit his tail:'+str(cnt)
largest_cnt=cnt
cnt+=1
#zjc
if largest_cnt!=-1:
inp=largest_cnt
outp=largest_cnt+1
print 'judge'+str(inp)+'and'+str(outp)+'!'
self.h_x=self.tail[outp].m_x-self.tail[inp].m_x
self.h_y=self.tail[outp].m_y-self.tail[inp].m_y
print 'set direction to:'+str(self.h_x)+' '+str(self.h_y)
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.2_directed_graph/Digraph.h
#ifndef _DIGRAPH_H_
#define _DIGRAPH_H_
#include "../../include/include.h"
class Digraph {
public:
Digraph();
Digraph(int v);
Digraph(string fname);
virtual int V();
virtual int E();
//////////////////////////////
// Table 4.2.2
//////////////////////////////
virtual void addEdge(int v,int w);
virtual vector<int> adj(int v);
Digraph *reverse();
string toString();
void dumpDOT(string fname)
{
//----------------------------------------------------------
string filename_out=fname;
std::ofstream outfile(filename_out);
if (!outfile)
{
std::cerr << "Couldn't open " << filename_out << " for writing\n";
return;
}
cout<<"DUMPING FILE: "<<fname<<" ..."<<endl;
outfile<<"digraph \""<<this<<"\" {"<<endl;
for(int ii=0;ii<V();ii++)
{
outfile<<ii<<";"<<endl;
}
for(int v=0;v<V();v++)
{
for(auto to:adj(v))
outfile<<v<<"->"<<to<<";"<<endl;
}
outfile<<"}"<<endl;
//----------------------------------------------------------
}
//
private:
int mV;
int mE;
vector<vector<int>> mAdj;
};
class TestDigraph {
public:
TestDigraph()
{
Digraph * g=new Digraph ("tinyG.txt");
DLOG(g->toString());
auto gr=g->reverse();
DLOG(gr->toString());
}
};
#endif
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/chapter4.6_calc_PI.cpp
#include <iostream>
#include <math.h>
#include <iomanip>
#include <time.h>
using namespace std;
typedef int INT;
int f_ch4_6 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
INT cnt=0;
const int width=20;
int i,sig;
long double pi=0;
long double incr;
sig=-1;
while (true) {
//if (cnt>=1e6) {break;}
//if (cnt%2==0) { sig=1;
//} else {sig=-1;}
sig=-sig;
incr=(long double)sig*1/(2*cnt+1);
//cout<<"plus 1/"<<sig*(2*cnt+1)<<" = "<<incr<<endl;
pi+=incr;
cnt++;
if (fabs(incr)<1e-10) {break;}
}
pi*=4;
cout<<setprecision(100)<<"PI = "<<pi<<endl;
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/Queue.cpp
//#include <include.top.h>
//Queue::Queue() {
// //topPtr=NULL;
// //topPtr=(Node*)NULL;
// //Node pNode;
// //pNode.next=NULL;
//}
//void Queue::put(int item) {
//// Node temp(item,pNode.getNext);
//// cout <<"put======="<<endl;
//// cout<<"put:topPtr="<<pNode.next()<<endl;
//// pNode.next=&temp;
//// cout<<"put:topPtr="<<pNode.next()<<endl;
//}
//int Queue::get() {
//// cout <<"get======="<<endl;
//// int v=pNode.next->a;
//// cout<<"put:topPtr="<<pNode.next<<endl;
//// pNode.next=pNode.next->next;
//// cout<<"put:topPtr="<<pNode.Next<<endl;
//// return v;
// return 0;
//}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph/run.sh
rm a.out; g++ -g -Wall -std=c++11 GraphBase.cpp GraphAdjList.cpp main.cpp; ./a.out
#rm a.out; g++ -E -v -g -Wall -std=c++11 GraphBase.cpp main.cpp; ./a.out
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/Queue.h
//class Queue{
// public:
// Queue();
// void put(int );
// int get();
// //private:
// //Node pNode;
//};
//
//
<file_sep>/python/workspace_python/use_baidu/gl.py
#! /usr/bin/env python
#coding=utf-8
def printGB(s):
#s="中文"
if isinstance(s, unicode):
#s=u"中文"
print s.encode('gb2312')
else:
#s="中文"
print s.decode('utf-8').encode('gb2312')
<file_sep>/cpp/POJ_separated/1019/poj.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#define SIMPLE_LOG
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#define PRINT_COUT(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
#include <math.h>
#include <iomanip>
#include <map>
#include <fstream>
using namespace std;
static map<int ,string > cache_series_lv1;
static map<int ,string > cache_series_lv2;
template <typename T>
std::string to_string(T value)
{
std::ostringstream os ;
os << value ;
return os.str() ;
}
string genSeriesLv1 (int n)
{
string r="";
if(cache_series_lv1.count(n))
{
PRINTVAR_hor(n);
PRINT_DEBUG_INFO_PREFIX("USE CACHE genSeriesLv1");
r=cache_series_lv1[n];
}
else if(n==1)
r="1";
else
r=genSeriesLv1(n-1)+to_string(n);
PRINTVAR(r);
if(!cache_series_lv1.count(n))
cache_series_lv1[n]=r;
return r;
}
string genSeriesLv2 (int n)
{
string r="";
if(cache_series_lv2.count(n))
{
PRINTVAR_hor(n);
PRINT_DEBUG_INFO_PREFIX("USE CACHE genSeriesLv2");
r=cache_series_lv2[n];
}
else if(n==1)
r=genSeriesLv1(1);
else
r=genSeriesLv2(n-1)+genSeriesLv1(n);
PRINTVAR(r);
if(!cache_series_lv2.count(n))
cache_series_lv2[n]=r;
return r;
}
int main ()
{
//----------------------------------------------------------
//cout<<"-----------------------------------------------"<<endl;
//string filename="input.txt";
//std::ifstream infile(filename);
//if (!infile)
// std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
//for(int i=3;i<1000;i++)
//{
// string s=genSeriesLv2(i);
// cout<<i
// <<"\t:\t"<<s.size()
// <<"\t:\t"<<(sqrt(s.size())-i)
// <<endl;
// if (s.size()>1000000000)
// break;
//}
int t;
int cntr=0;
while(cin >> t)
{
PRINTVAR(t);
if(cntr!=0)
{
int i=sqrt((float)t)+5;
PRINTVAR(i);
string s=genSeriesLv2(i);
PRINTVAR(s);
assert(s.size()>t);
cout<<s[t-1];
}
PRINTVAR(cache_series_lv1.size());
PRINTVAR(cache_series_lv2.size());
cntr++;
}
cout<<"-----------------------------------------------"<<endl;
return 0;
}
<file_sep>/python/workspace_python/pendulum_phase/src/pendulum_phase_main.py
# _*_ coding:utf-8 _*_
"""
Created on 2015年8月9日
@author: admin
"""
import pygame
import SinglePendulumClass
import gl
import math
class GameWindow(object):
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((800, 800), 0, 32)
self.clock = pygame.time.Clock()
# self.player = player.Snake(400,400)
gl.pendulum_list = []
self.COUNT = 80
for i in range(self.COUNT):
name = 's' + str(i)
#objname = 'player' + str(i)
# self.player=AI.AI(i,i,name)
#gl.pendulum_list.append(self.player)
if i < self.COUNT / 2:
a = 100
loc = [a, i * 1]
pos = loc
freq = 0.0000 * i + 0.001
phi = i * 1.0 / self.COUNT * 2 * math.pi
name = name
time_tick = 100000
direction = 'x'
color = gl.COLOR
gl.pendulum_list.append(
SinglePendulumClass.SinglePendulumClass(pos, freq, a, phi, name, time_tick, direction, color))
# def __init__(self, pos,freq,a,phi,name,time_tick,direction, color=(0, 255, 0)):
else:
a = 100
loc = [i - self.COUNT / 2, a]
pos = loc
freq = 0.0000 * i + 0.001
phi = i * 1.0 / self.COUNT * 2 * math.pi
name = name
time_tick = 100000
direction = 'y'
color = gl.COLOR
gl.pendulum_list.append(
SinglePendulumClass.SinglePendulumClass(pos, freq, a, phi, name, time_tick, direction, color))
self.font = pygame.font.SysFont('Comic Sans MS', 40)
def blit_grid(self):
for x in range(40):
pygame.draw.aaline(self.screen, (255, 255, 255), (x * 10, 0), (x * 10, 400))
for y in range(40):
pygame.draw.aaline(self.screen, (255, 255, 255), (0, y * 10), (400, y * 10))
def game_over(self):
running = True
time = 0
while running:
time += self.clock.tick()
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN and time > 1500:
running = False
self.screen.fill((255, 255, 255))
text = self.font.render('GAME OVER ', True, (255, 0, 0))
self.screen.blit(text, (200 - text.get_width() / 2, 200 - text.get_height()))
for i in gl.pendulum_list:
t2 = 'POINT : ' + str(i.point)
# t2 = 'POINT : ' + str(self.player.point)
text2 = self.font.render(t2, True, (255, 0, 0))
self.screen.blit(text2, (200 - text2.get_width() / 2, 200 + text2.get_height()))
pygame.display.update()
for snake in gl.pendulum_list:
snake.is_dead = False
# self.player.is_dead = False
# self.player2.is_dead = False
self.clock.tick()
for snake in gl.pendulum_list:
snake.restart()
# self.player.restart()
# self.player2.restart()
self.Food.restart()
def run(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
self.screen.fill((255, 255, 255))
dt = self.clock.tick()
# print("DEBUG:dt="+str(dt))
for snake in gl.pendulum_list[0:self.COUNT / 2 - 1]:
a_loc = snake.get_loc()
ax = a_loc[0]
ay = a_loc[1]
for node in gl.pendulum_list[self.COUNT / 2:]:
#print ('iteration:%s'%node.name)
b_loc = node.get_loc()
bx = b_loc[0]
by = b_loc[1]
#print('a_loc=%s;b_loc=%s'%(a_loc,b_loc))
#if a_loc==b_loc:
if abs(ax - bx) + abs(ay - by) < 10:
#print('a_loc=%s;b_loc=%s'%(a_loc,b_loc))
node.color = (255, 0, 0)
for snake in gl.pendulum_list:
snake.update(dt, self.screen)
for snake in gl.pendulum_list:
snake.color = gl.COLOR
#self.Food.update(dt, self.screen, snake)
# self.player.update(dt,self.screen)
# self.Food.update(dt,self.screen,self.player)
# self.player2.update(dt,self.screen)
# self.Food.update(dt,self.screen,self.player2)
self.blit_grid()
for snake in gl.pendulum_list:
if snake.is_dead:
print 'DEAD:' + snake.name + 'IN:' + str(snake.x) + ' ' + str(snake.y)
self.game_over()
for snake in gl.pendulum_list:
point = self.font.render(str(snake.point), True, (0, 0, 0))
self.screen.blit(point, (0, 0))
pygame.display.update()
if __name__ == '__main__':
app = GameWindow()
app.run()
<file_sep>/python/workspace_python/dive_into_python/src/1/1/1p6_func_arg.py
# FUNC:
def power(x):
return x*x
def power_m(x,n=2):
return x**n
print power(3)
print power_m(4)
print power_m(2,3)
def enroll(name, gender, age=6, city='Beijing'):
print '---------'
print 'name:', name
print 'gender:', gender
print 'age:', age
print 'city:', city
enroll('john','M',3,'Kaifeng')
enroll('Jenny','F',city='Wuhan',age=11);# not ordered args
enroll('Jenny','F',city='Wuhan' );# single special args
# a grammar that can cause bug:
def add_end (L=[]):
L.append('END')
return L
print add_end()
print add_end()
print add_end();# END END END...
def add_end_right (L=None):
if L is None:
L=[]
L.append('END')
return L
print add_end_right()
print add_end_right()
print add_end_right();# END END END...
# args# can be changed
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print calc([1,2,3])
def calc2(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print calc2(1,2)
print calc2()
# a good using
nums=[1,2,3,4]
print calc2(*nums)
# keyword arg:
def person(name, age, **kw):
print 'name:', name, 'age:', age, 'other:', kw
print person('John','M')
print person('John','M',u1=1,u2=2,u3=3,addr='a street')
# 4 types of args
def func(a, b, c=0, *args, **kw):
print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw
print func('avalue','bvalue',)
func(1, 2)
func(1, 2, c=3)
func(1, 2, 3, 'a', 'b')
func(1, 2, 3, 'a', 'b', x=99)
# a magic way
print 'magic way:'
args = (1, 2, 3, 4)
kw = {'x': 99}
func(*args, **kw)
<file_sep>/cpp/6_EXEs/src/sort_bubble.cpp
#include "include.top.h"
# if 0
void sort_bubble_wrp ()
{
cout<<"=============="<<endl;
PRINT_DEBUG_INFO();
vector <int> a={6,5,1,2,3,10,2,3,4,5};
//vector <int> a={6,2,15,3};
//vector <int> a={6,2};
PRINT_VECTOR(a);
cout<<"=============="<<endl;
vector <int> a_bk=a;
sort_bubble(a);
cout<<"=============="<<endl;
PRINT_VECTOR(a);
cout<<"=============="<<endl;
sanity_check(a,a_bk);
}
bool sanity_check(vector<int> &a,vector<int> &a_bk)
{
cout<<"=============="<<endl;
cout<<"SANITY CHECK:"<<endl;
PRINT_VECTOR_hor(a);
PRINT_VECTOR_hor(a_bk);
cout<<"=============="<<endl;
assert(a.size()==a_bk.size());
for(auto it=a.begin();it!=a.end()-1;it++)
{
cout<<"checking-1:"<<(*it)<<""<<endl;
assert(*it<=*(it+1));
}
for(auto it=a.begin();it!=a.end();it++)
{
auto t=*it;
cout<<"checking-2:"<<t<<""<<endl;
int cnt1=std::count(a.begin(),a.end(),t);
int cnt2=std::count(a_bk.begin(),a_bk.end(),t);
PRINTVAR(cnt1);
PRINTVAR(cnt2);
assert(cnt1==cnt2);
}
cout<<"=============="<<endl;
cout<<"SANITY CHECK DONE!"<<endl;
return true;
}
void sort_bubble (vector<int> &arr)
{
for(auto it=arr.begin()+1;it!=arr.end();it++) // n-1+1=n
{
cout<<"============================"<<""<<endl;
PRINT_VECTOR_hor(arr);
auto get=*it; // n
PRINTVAR(get);
for(auto it_sorted=it-1;it_sorted!=arr.begin()-1;it_sorted--) // sum(k[i]), where k[i]=i+1 ,i=1~n
{
cout<<"-----"<<""<<endl;
auto item_sorted=*it_sorted;
PRINTVAR(item_sorted);
if(*it_sorted>get )
{
*(it_sorted+1)=*it_sorted;
}
else
{
*(it_sorted+1)=get;
break;
}
if(it_sorted==arr.begin())
*(it_sorted)=get;
PRINT_VECTOR_hor(arr);
}
PRINT_VECTOR_hor(arr);
cout<<"============================"<<""<<endl;
}
}
#endif
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.2_directed_graph/SCC.h
class SCC
{
}
class TestSCC
{
}
<file_sep>/cpp/tree_structure/run.sh
rm a.out; g++ main.cpp ../POJ/src/lib.cpp -I../POJ/include ; ./a.out
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.2_directed_graph/DepthFirstOrder.h
class DepthFirstOrder
{
private:
vector<bool> mMarked;
deque<int> mPre;
deque<int> mPost;
vector<int> mReversePost;
public:
DepthFirstOrder(Digraph*G)
{
mMarked.resize(G->V(),0);
for(int v=0;v<G->V();v++)
{
if(!mMarked[v])
dfs(G,v);
}
}
private:
void dfs(Digraph* G,int v)
{
mPre.push_back(v);
mMarked[v]=1;
for(int w:G->adj(v))
{
if(!mMarked[w])
dfs(G,w);
}
mPost.push_back(v);
mReversePost.push_back(v);
}
public:
deque<int> pre()
{
return mPre;
}
deque<int> post()
{
return mPost;
}
vector<int> reversePost()
{
return mReversePost;
}
};
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/run.sh
/usr/bin/ctags -R --sort=yes --c++-kinds=+pl --fields=+iaSKz .
rm a.out;
rm compile.log;
rm out.log
g++ -g -Wall -std=c++11 GraphBase.cpp Graph.cpp main.cpp > compile.log 2>&1 && ./a.out > out.log 2>&1
#g++ -g -Wall -std=c++11 main.cpp > compile.log 2>&1 && ./a.out > out.log 2>&1
grep --color error compile.log
#rm a.out; g++ -E -v -g -Wall -std=c++11 GraphBase.cpp main.cpp; ./a.out
<file_sep>/cpp/exe_game/tetris/Shape.class.h
#ifndef SHAPE_CLASS_H
#define SHAPE_CLASS_H
using namespace std;
class Point
{
/*
* x : row
* y : col
*
* o-------------------->
* | y
* |
* |
* v
* x
*
*/
public:
Point(int u,int v){
x=u; y=v;
}
Point shift(Point vector) {
Point p2(x+vector.x,y+vector.y);
return p2;
}
void setLoc(int u, int v) { x=u; y=v; }
void setLoc(Point p) { x=p.x; y=p.y; }
int getX(){return x;};
int getY(){return y;};
friend ostream& operator<< (ostream& os, Point rhs) {
//os<<"Point\t("<<rhs.getX()<<",\t"<<rhs.getY()<<")"<<endl;
os<<"Point\t("<<rhs.getX()<<",\t"<<rhs.getY()<<")";
return os;
};
string touch(Point* p)
{
// "NOT": not touch
// "COINCIDE": coincide
// S: p is at the S of this
// E: p is at the E of this
// N: p is at the N of this
// W: p is at the W of this
if(x==p->x)
if(y==p->y)
return "COINCIDE";
if(x==p->x)
if(y-p->y==1)
return "W";
if(y-p->y==-1)
return "E";
if(y==p->y)
if(x-p->x==1)
return "N";
if(x-p->x==-1)
return "S";
return "NOT";
}
public:
int x;
int y;
};
class Shape
{
public:
int width_board;
int height_board;
//Shape(unsigned height,unsigned width,string v="0"){};
//Shape(unsigned height=4,unsigned width=4,string v="#");
Shape(vector<vector<string> > m);
Shape(int w_board,int h_board,int type=0,string ori="N");
//bool touchToShape(Shape* another);
int getWidthN() ;
int getHeightN() ;
int getWidth() ;
int getHeight() ;
bool legalType() ;
void setDots();
vector<Point*> getDots(); // return {P1,P2,...Pn};
vector<Point> getBorder(); // return {{ul_row,ul_col}, {drx,dry}};
int ul_row;
int ul_col;
void init(); // apply type
void update(); // apply orientation,ul_row,ul_col to dots
void update_ul();
void move(string orientation);
void move(string orientation,unsigned times);
bool drop();
void turn(string left_or_right);
private:
vector<Point*> findTheMost(string orientation) ; // orientation={N,E,W,S};
void showVector(vector<Point*>* vecPtr);
void deleteFromVector(vector<Point*>* vecPtr, Point* item);
void initShapeFaceToN(int type);
public:
bool hit(string orientation);
int hit_depth(string orientation);
// depth <0 means not hit
// depth =0 means touch the border
// depth >0 means out of border
bool hit_bottom();
bool contain(Point* p);
bool contain(Shape* s);
bool contain();
bool hit(Point* p,string to="S");
bool hit(Shape* s,string to="S");
bool hitInMatrix(string to="S");
void setMatrixPtr(void* m){mat=m;};
bool steady;
void cleanRow(int row);
friend ostream& operator<< (ostream& os, Shape rhs) {
os<<"Shape\t:";
for(Point* d:rhs.getDots())
os<<*d;
return os;
};
// LV1 MEMBERS:
// written by outside
private:
string orientation;// N,E,W,S (no flip)
int type; //
/* types:
* 0 ####
*
* 1 ##
* ##
*
* 2 ##
* ##
*
* 3 ##
* ##
*
* 4 #
* ###
*
* 5 #
* ###
*
* 6 #
* ###
*
*/
// LV2 MEMBERS:
// written by update()
vector<Point*> dots; // store dots, to save time
vector<Point*> dotsMostN;
vector<Point*> dotsMostE;
vector<Point*> dotsMostW;
vector<Point*> dotsMostS;
void* mat; // because Matrix.h include Shape.h, so Shape.h can't have Matrix variable, void* can be used to declear a Matrix* in the future, and using casting.
};
# endif
<file_sep>/cpp/POJ/include/lib.h
#include <math.h>
#include <stdio.h>
#include "include.top.h"
#ifndef LIB_H
#define LIB_H
double myfac (int n) ;
double calc_sum_of_power (int n,int power=3) ;
bool is_tulip (int n, int power=3) ;
bool is_prime (int n, int print=0) ;
bool is_full_num (int n, int print=0) ;
double calc_use_do (double x, double stop=1e-8) ;
bool is_int (double v) ;
//double integral(double from,double to);
bool item_is_in_array (int i,int a[] ,int a_length) ;
void show_array(double a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void show_array(int a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void show_array(bool a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void sort_bubble(double a [],int size,int return_list[]) ;
void sort_bubble(double a [],int size,int return_list[]) ;
string dec2bin(int n);
std::vector<std::string> split(std::string str,std::string pattern) ;
std::string join(std::vector<std::string> v,string spliter=" ");
string itos(int a) ;
vector<string> itos(vector<int> a) ;
vector<int> stoi(vector<string> sv) ;
#endif
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/7.5.cpp
#include "7.5.h"
#include <iostream>
using namespace std;
void f7_5() {
double u[10][10]={{1,2,3},{3,4,1},{9,4,2}};
cout<<calc_diag_sum(u,3)<<endl;
}
double calc_diag_sum(double a[][10],int n) {
double sum=0;
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
cout<<a[i][j]<<"\t";
}
cout<<endl;
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
double v=a[i][j];
if (i==j) {
cout<<"ADD:"<<v<<endl;
sum+=v;
}
if(i+j==n-1) {
cout<<"ADD:"<<v<<endl;
sum+=v;
}
}
}
if(n%2==1) {
int ind=n/2;
double repeated_value=a[ind][ind];
cout<<"MINUS:"<<repeated_value<<endl;
sum-=repeated_value;
}
return sum;
}
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/src/f13_5.cpp
#include "include.top.h"
#define SUM(a,b) (a+b)
void f13_5() {
double x=3.1;
double y=5.12;
cout<<"SUM="<<SUM(x,y)<<endl;
}
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/src/f13_4.cpp
#include "include.top.h"
void f13_4() {
PRINT_DEBUG_INFO();
for (int a=1;a<=10;a++) {
cout<<"SPHERE_VOLUME("<<a<<")\t="<<SPHERE_VOLUME(a)
<<"\t|\t"<<dec2bin(SPHERE_VOLUME(a))<<endl;
if(SPHERE_VOLUME(a)<0) {break;}
}
cout<<dec2bin(1)<<endl;
cout<<dec2bin(2)<<endl;
cout<<dec2bin(4)<<endl;
cout<<dec2bin(8)<<endl;
cout<<dec2bin(7)<<endl;
cout<<dec2bin(9)<<endl;
}
<file_sep>/cpp/5_BOOK_CPP_PRIMER/src/exe_3.16.cpp
#include <vector>
#include "include.top.h"
using namespace std;
using std::string;
using std::vector;
void f_3_20_redo () {
cout<<"---------"<<""<<endl;
cout<<"redo exe3.20:"<<""<<endl;
cout<<"---------"<<""<<endl;
vector<int> vec_int_3_21;
#if 0
int buf_num;
while(cin>>buf_num)
{
PRINTVAR(buf_num);
vec_int_3_21.push_back(buf_num);
}
#else
vec_int_3_21.push_back(1);
vec_int_3_21.push_back(4);
vec_int_3_21.push_back(2);
vec_int_3_21.push_back(33);
vec_int_3_21.push_back(6);
vec_int_3_21.push_back(7);
vec_int_3_21.push_back(17);
#endif
int sum=0;
cout<<"print_vector(vec_int_3_21): "<<""<<endl;
print_vector(vec_int_3_21);
cout<<"1. calc sum of neighbour:"<<""<<endl;
for(auto it =vec_int_3_21.cbegin();it!=vec_int_3_21.cend();it++)
{
auto i=*it;
auto i_bk=*(it-1);
if(it!=vec_int_3_21.cbegin())
{
sum=i+i_bk;
cout<<"sum="<<sum<<""<<endl;
}
}
cout<<"2. calc sum of [0]+[end],[1]+[end-1], etc. :"<<""<<endl;
decltype(vec_int_3_21.size()) cntr_i=0,cntr_j=0,size;
size=vec_int_3_21.size();
PRINTVAR(size);
auto it1=vec_int_3_21.cbegin();
auto it2=vec_int_3_21.cend()-1;
//while(it1!=it2 && it1!=it2+1)
while(it1<it2 )
{
sum=(*it1)+(*it2);
cout<<"sum="<<sum<<"="<<(*it1)<<"+"<<*it2<<endl;
it1++;
it2--;
}
return;
}
void exe_3_16() {
cout<<"==============="<<endl;
cout<<"exe_3_13 & exe_3_16:"<<""<<endl;
cout<<"==============="<<endl;
vector<int> v0(5,3);
vector<int> v1;
vector<int> v2(10);
vector<int> v3(10,42);
vector<int> v4{10};
vector<int> v5{10,42};
vector<string> v6{10};
vector<string> v7{10,"hi"};
cout<<"v0"<<""<<endl;
print_vector(v0);
cout<<"v1"<<""<<endl;
print_vector(v1);
cout<<"v2"<<""<<endl;
print_vector(v2);
cout<<"v3"<<""<<endl;
print_vector(v3);
cout<<"v4"<<""<<endl;
print_vector(v4);
cout<<"v5"<<""<<endl;
print_vector(v5);
cout<<"v6"<<""<<endl;
print_vector(v6);
cout<<"v7"<<""<<endl;
print_vector(v7);
//PRINTVAR(v7);
//
cout<<"==============="<<endl;
cout<<"exe_3_17:"<<""<<endl;
cout<<"==============="<<endl;
vector<string> vec_word;
#if 0
string buf;
while(cin>>buf)
{
PRINTVAR(buf);
vec_word.push_back(buf);
}
#else
vec_word.push_back("a");
vec_word.push_back("b?");
vec_word.push_back("d1");
vec_word.push_back("sdsaf!!");
#endif
cout<<"print_vector(vec_word):"<<""<<endl;
print_vector(vec_word);
for(auto &w:vec_word)
{
w=stringToUpper(w);
cout<<"w="<<w<<""<<endl;
}
cout<<"print_vector(vec_word):"<<""<<endl;
print_vector(vec_word);
cout<<"==============="<<endl;
cout<<"exe_3_19:"<<""<<endl;
cout<<"==============="<<endl;
vector<int> v3_19_0(10,42);
vector<int> v3_19_1{42,42,42,42,42,42,42,42,42,42};
vector<int> v3_19_2={42,42,42,42,42,42,42,42,42,42};
vector<int> v3_19_3;
for(auto i:string(10,'x'))
{
PRINTVAR(i);
v3_19_3.push_back(42);
}
print_vector(v3_19_0);
print_vector(v3_19_1);
print_vector(v3_19_2);
print_vector(v3_19_3);
cout<<"==============="<<endl;
cout<<"exe_3_20:"<<""<<endl;
cout<<"==============="<<endl;
vector<int> vec_int;
#if 0
int buf_num;
while(cin>>buf_num)
{
PRINTVAR(buf_num);
vec_int.push_back(buf_num);
}
#else
vec_int.push_back(1);
vec_int.push_back(4);
vec_int.push_back(2);
vec_int.push_back(33);
vec_int.push_back(6);
vec_int.push_back(7);
#endif
int sum=0;
int cntr=0;
int i_bk;
cout<<"print_vector(vec_int): "<<""<<endl;
print_vector(vec_int);
cout<<"1. calc sum of neighbour:"<<""<<endl;
for(auto i : vec_int)
{
if(cntr!=0)
{
sum=i+i_bk;
cout<<"sum="<<sum<<""<<endl;
}
cntr++;
i_bk=i;
}
cout<<"2. calc sum of [0]+[end],[1]+[end-1], etc. :"<<""<<endl;
decltype(vec_int.size()) cntr_i=0,cntr_j=0,size;
size=vec_int.size();
PRINTVAR(size);
for(auto i : vec_int)
{
if(cntr_i>=size/2){break;}
cntr_j=0;
for(auto j : vec_int)
{
//PRINTVAR(cntr_i);
//PRINTVAR(cntr_j);
if((cntr_j+cntr_i)==vec_int.size()-1) {
sum=i+j;
cout<<"sum("<<cntr_i<<"+"<<cntr_j<<") ="<<sum<<endl;
}
cntr_j++;
}
cntr_i++;
}
cout<<"==============="<<endl;
cout<<"exe_3_21, redo exe:"<<""<<endl;
cout<<"==============="<<endl;
cout<<"---------"<<""<<endl;
cout<<"redo exe3.17:"<<""<<endl;
cout<<"---------"<<""<<endl;
vector<string> vec_word_3_21;
#if 0
string buf;
while(cin>>buf)
{
PRINTVAR(buf);
vec_word_3_21.push_back(buf);
}
#else
vec_word_3_21.push_back("a");
vec_word_3_21.push_back("b?");
vec_word_3_21.push_back("d1");
vec_word_3_21.push_back("sdsaf!!");
#endif
cout<<"print_vector(vec_word_3_21):"<<""<<endl;
print_vector(vec_word_3_21);
for(auto it=vec_word_3_21.begin();it!=vec_word_3_21.end();it++)
{
(*it)=stringToUpper(*it);
//cout<<"*it="<<*it<<""<<endl;
}
cout<<"print_vector(vec_word_3_21):"<<""<<endl;
print_vector(vec_word_3_21);
f_3_20_redo();
}
<file_sep>/cpp/7_EXEs_separated/exe_ieee754/s.cpp
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <glob.h>
using namespace std;
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_MAP(a) std::cout<<#a<<":"<<std::endl;for(auto u:a) {std::cout<<u.first<<"\t->\t"<<u.second<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_POINTER1(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER2(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<"\t->\t"<<**a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER3(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<"\t->\t"<<**a; \
std::cout<<"\t->\t"<<***a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER(a) PRINT_POINTER1(a)
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//inline std::vector<std::string> glob(const std::string& pat);
#include <stdint.h>
#include <stdio.h>
void convert_hex(char* myString)
{
uint32_t num;
float f;
sscanf(myString, "%x", &num); // assuming you checked input
f = *((float*)&num);
//printf("the hexadecimal 0x%08x becomes %.3f as a float\n", num, f);
printf("hex=0x%08x\n",num);
printf("flo=%.3f\n",f);
printf("dec=%d\n",num);
string bin="";
string bin_with_delim="";
printf("bin=");
int n=num;
int cntr=0;
while (n) {
if(cntr%8==0)
bin_with_delim+=" ";
if (n & 1)
{
bin+="1";
bin_with_delim+="1";
}
else
{
bin+="0";
bin_with_delim+="0";
}
n >>= 1;
cntr--;
}
int diff=32-bin.size();
while (diff!=0)
{
bin+="0";
bin_with_delim+="0";
diff--;
}
std::reverse(bin.begin(),bin.end());
std::reverse(bin_with_delim.begin(),bin_with_delim.end());
std::cout<<bin_with_delim;
printf("\n");
return;
}
int main()
{
PRINT_DEBUG_INFO();
//int a=0x4435e984;
//float f=(float)a;
//PRINTVAR(a);
//PRINTVAR(f);
//char myString[]="0x4435e984";
char myString[]="0x43000000";
//myString=scanf();
std::cout<<"input :\t";
scanf("%s",myString);
convert_hex(myString);
//printf("bin=%b\n",num);
}
<file_sep>/python/workspace_python/Beauty_of_programming/1.2.py
__author__ = 'jc'
<file_sep>/cpp/5_BOOK_CPP_PRIMER/include/lib.h
#include <math.h>
#include <stdio.h>
#include <vector>
#include "include.top.h"
#define PRINT_DEBUG_INFO() \
(std::cout<<"DEBUG: FILE=" <<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<" compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<std::endl)
double myfac (int n) ;
double calc_sum_of_power (int n,int power=3) ;
bool is_tulip (int n, int power=3) ;
bool is_prime (int n, int print=0) ;
bool is_full_num (int n, int print=0) ;
double calc_use_do (double x, double stop=1e-8) ;
bool is_int (double v) ;
//double integral(double from,double to);
bool item_is_in_array (int i,int a[] ,int a_length) ;
void show_array(double a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void show_array(int a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void show_array(bool a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void sort_bubble(double a [],int size,int return_list[]) ;
void sort_bubble(double a [],int size,int return_list[]) ;
std::string dec2bin(int n);
std::string stringToUpper(std::string s);
template <class T>
void print_vector(std::vector<T> v) {
std::cout<<"get vector "<<""<<std::endl;
std::cout<<"size="<<v.size()<<""<<std::endl;
for(auto& c:v)
{
std::cout<<"\t"<<c<<""<<std::endl;
}
}
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch1_life_game/src/life_game.cpp
#include <utility.h>
#include <life.h>
void main_life_game() {//FUNC
Life a_board(10,10);
a_board.init();
//a_board.make_live(2,3);
//a_board.make_live(1,3);
a_board.make_live(2,4);
a_board.make_live(1,4);
a_board.make_live(0,4);
//a_board.make_live(5,5);
//a_board.make_dead(7,7);
while (true) {
a_board.show();
a_board.update_neighbour_cnt();
a_board.show_neighbour_cnt();
if (!user_say_yes()) {break;}
a_board.update();
}
}
<file_sep>/cpp/POJ/src/poj1003.cpp
#include "include.top.h"
#include <math.h>
#include <iomanip>
#include <map>
#include "poj1003.h"
using namespace std;
#include <fstream>
void poj1003 ()
{
cout<<"-----------------------------------------------"<<endl;
cout<<"poj1003"<<endl;
//----------------------------------------------------------
string filename="input/poj1003.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj1003.out";
std::ofstream outfile(filename_out);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
//----------------------------------------------------------
// GET UPBOUND FOR GENERATING map_card2length
float upbound=-1;
string line;
while (infile >> line)
{
float l=stof(line);
if (l>upbound)
upbound=l;
}
cout<<"get upbound="<<upbound<<" from file:"<<filename<<endl;
cout<<"generating map_card2length ..."<<endl;
//----------------------------------------------------------
// gen map_card2length and map_length2card
map<int,float> map_card2length;
gen_map_card2length(map_card2length,upbound);
map<float,int> map_length2card;
for(auto it:map_card2length)
{
auto f=it.first;
auto s=it.second;
map_length2card[s]=f;
//cout<<s<<":\t"<<f<<endl;
}
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
double result;
// read filename for the second time, a new file_handle infile1 is needed,
//std::ifstream infile1(filename);
// or use clear() and seekg(0) to init the file_handle again
infile.clear();
infile.seekg(0);
while (infile >> line)
{
//cout<<"GOT LINE"<<line<<endl;
float l=stof(line);
outfile<<line;
outfile<<":\t";
if (l<=0)
{
cout<<0<<endl;
outfile<<0<<endl;
}
else if (map_length2card.count(l))
{
cout<<map_length2card[l]<<endl;
}
else
{
for (auto it:map_length2card)
{
auto f=it.first;
if (f>l)
{
cout<<it.second<<endl;
outfile<<it.second<<endl;
break;
}
}
}
}
outfile<<"====================="<<endl;
//----------------------------------------------------------
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
}
map<int,float> gen_map_card2length(map<int,float> & map_card2length,float upbound=5.2)
{
map<int,float> r;
for(int n=1;n<=1000000;n++)
{
float m=calc_center(n,map_card2length);
if (n%10000==0)
cout<<n<<":\t"<<m<<endl;
r[n]=m;
if (m>upbound)
break;
}
return r;
}
float calc_center(float n,map<int,float> &map_card2length)
{
if (n==1)
{
map_card2length[1]=0.5;
return 0.5;
}
else
{
//return 0.5*(1/n)+calc_center(n-1);
float m= 0.5*(1/n)+map_card2length[n-1];
map_card2length[n]=m;
return m;
}
}
<file_sep>/cpp/7_EXEs_separated/exe_remove_some_lines/copy.cpp
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
int main() {
clock_t start, end;
start = clock();
ifstream source("from.ogv", ios::binary);
ofstream dest("to.ogv", ios::binary);
std::string line;
//dest << source.rdbuf();
//while(source>>line)
std::string head= "<annotationInfo>";
std::string tail= "</annotationInfo>";
dest<<head<<std::endl;
while(getline(source,line))
{
std::cout<<"LINE=\t"<<line<<std::endl;
if(
line== head
|| line== tail
)
continue;
dest<<line<<std::endl;
}
dest<<tail<<std::endl;
source.close();
dest.close();
//end = clock();
//cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
//cout << "CPU-TIME START " << start << "\n";
//cout << "CPU-TIME END " << end << "\n";
//cout << "CPU-TIME END - START " << end - start << "\n";
//cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
<file_sep>/cpp/codewar/John_and_Ann_sign_up_for_Codewars/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
//#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#include <vector>
#include <string>
#include <iostream>
#include <assert.h>
class Johnann
{
public:
static std::vector<long long> john(long long n);
static std::vector<long long> ann(long long n);
static std::vector<long long> john(long long n,int hier);
static std::vector<long long> ann(long long n,int hier);
static long long sumJohn(long long n);
static long long sumAnn(long long n);
static void compose(long long n);
static std::vector<long long> v_john;
static std::vector<long long> v_ann;
private:
};
std::vector<long long> Johnann::v_john;
std::vector<long long> Johnann::v_ann;
std::vector<long long> Johnann::john(long long n)
{
compose(n);
n--;
//return john(n,0);
std::vector<long long>::const_iterator first=v_john.begin();
std::vector<long long>::const_iterator last =v_john.begin()+n+1;
std::vector<long long> r(first,last);
PRINT_VECTOR(r);
return r;
}
//-------------------------------------------------------------------------
std::vector<long long> Johnann::john(long long ind,int hier)
{
int hierbk=hier;
std::string indent="";
while(hierbk>0) {indent+=" ."; hierbk--;}
std::cout<<indent<<">-----------------------"<<std::endl;
std::cout<<indent<<"CALL john("<<ind<<")"<<std::endl;
assert(ind>=0);
std::vector<long long>& v_ann_ref=v_ann;
std::vector<long long>& v_john_ref=v_john;
PRINTVAR(v_john_ref.size());
PRINTVAR(v_ann_ref.size());
PRINT_VECTOR(v_john_ref);
PRINT_VECTOR(v_ann_ref);
if(v_john_ref.size()>=ind+1)
{
PRINT_DEBUG_INFO_PREFIX("FAST john\t");
std::vector<long long>::const_iterator first=v_john_ref.begin();
std::vector<long long>::const_iterator last =v_john_ref.begin()+ind+1;
std::vector<long long> r(first,last);
PRINTVAR(v_ann_ref.size());
PRINTVAR(r.size());
return r;
}
if(ind==0)
{
v_john_ref.push_back(0);
}
else
{
john(ind-1,hier+1);
ann(v_john_ref[ind-1],hier+1);
v_john_ref.push_back(ind-v_ann_ref[v_john_ref[ind-1]]);
}
PRINTVAR(v_john_ref.size());
PRINTVAR(v_ann_ref.size());
PRINT_VECTOR(v_john_ref);
PRINT_VECTOR(v_ann_ref);
std::cout<<indent<<"<john"<<ind<<" = "<<v_john_ref[v_john_ref.size()-1]<<std::endl;
std::cout<<indent<<"<-----------------------"<<std::endl;
PRINT_DEBUG_INFO();
PRINTVAR(ind);
std::vector<long long>::const_iterator first=v_john_ref.begin();
std::vector<long long>::const_iterator last =v_john_ref.begin()+ind+1;
std::vector<long long> r(first,last);
PRINTVAR(v_john_ref.size());
PRINTVAR(r.size());
return r;
}
//-------------------------------------------------------------------------
std::vector<long long> Johnann::ann(long long n)
{
compose(n);
n--;
//return ann(n,0);
std::vector<long long>::const_iterator first=v_ann.begin();
std::vector<long long>::const_iterator last =v_ann.begin()+n+1;
std::vector<long long> r(first,last);
PRINT_VECTOR(r);
return r;
}
//-------------------------------------------------------------------------
std::vector<long long> Johnann::ann(long long ind,int hier)
{
int hierbk=hier;
std::string indent="";
while(hierbk>0) {indent+=" ."; hierbk--;}
std::cout<<indent<<">-----------------------"<<std::endl;
std::cout<<indent<<"CALL ann("<<ind<<")"<<std::endl;
assert(ind>=0);
std::vector<long long>& v_john_ref=v_john;
std::vector<long long>& v_ann_ref=v_ann;
PRINTVAR(v_ann_ref.size());
PRINTVAR(v_john_ref.size());
PRINT_VECTOR(v_ann_ref);
PRINT_VECTOR(v_john_ref);
if(v_ann_ref.size()>=ind+1)
{
PRINT_DEBUG_INFO_PREFIX("FAST ann\t");
std::vector<long long>::const_iterator first=v_ann_ref.begin();
std::vector<long long>::const_iterator last =v_ann_ref.begin()+ind+1;
std::vector<long long> r(first,last);
return r;
}
if(ind==0)
{
v_ann_ref.push_back(1);
}
else
{
ann(ind-1,hier+1);
john(v_ann_ref[ind-1],hier+1);
v_ann_ref.push_back(ind-v_john_ref[v_ann_ref[ind-1]]);
}
PRINTVAR(v_ann_ref.size());
PRINTVAR(v_john_ref.size());
PRINT_VECTOR(v_ann_ref);
PRINT_VECTOR(v_john_ref);
std::cout<<indent<<"<ann"<<ind<<" = "<<v_ann_ref[v_ann_ref.size()-1]<<std::endl;
std::cout<<indent<<"<-----------------------"<<std::endl;
std::vector<long long>::const_iterator first=v_ann_ref.begin();
std::vector<long long>::const_iterator last =v_ann_ref.begin()+ind+1;
std::vector<long long> r(first,last);
return r;
}
//-------------------------------------------------------------------------
long long Johnann::sumJohn(long long n)
{
long long r=0;
for(auto v:john(n))
r+=v;
return r;
}
long long Johnann::sumAnn(long long n)
{
long long r=0;
PRINTVAR(n);
for(auto v:ann(n))
r+=v;
PRINTVAR(r);
return r;
}
void Johnann::compose(long long n)
{
for(long long i=0;i<n;i++)
{
v_john.push_back(-1);
v_ann.push_back(-1);
}
v_john[0]=0;
v_ann[0]=1;
for(long long i=1;i<n;i++)
{
v_john[i]=i-v_ann [v_john[i-1]];
v_ann[i] =i-v_john[ v_ann[i-1]];
}
}
int main ()
{
//Johnann::ann(6);
//{1, 1, 2, 2, 3, 3};
//Johnann::john(11);
//{0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6};
//Johnann::compose(11);
//PRINT_VECTOR(Johnann::v_john);
//PRINT_VECTOR(Johnann::v_ann);
Johnann::ann(6);
Johnann::john(11);
//Johnann::john(1);
//Johnann::john(4);
//Johnann::john(3,0);
//Johnann::ann(6,0);
//Johnann::ann(4,0);
//Johnann::ann(2,0);
//Johnann::ann(10000);
return 0;
}
<file_sep>/cpp/exe_permutation/s.cpp
#include <vector>
#include <iostream>
#include <assert.h>
using namespace std;
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
vector<vector<int>> genPermutations(int n);
void show(vector<vector<int>> p,int length=0);
vector<vector<int>> breakIntoMatrix(vector<int> v,int length);
bool isLegal(vector<vector<int>> v);
// Catalan number
#define N 6
#define LEN 2
int main()
{
//vector<int> a;
//for(int i=0;i<12;i++)
// a.push_back(i);
//PRINT_VECTOR(a);
vector<vector<int>> p=genPermutations(N);
vector<vector<int>> result;
cout<<"SHOW------------------\t\n";
show(p);
PRINTVAR(p.size());
for(auto v:p)
if(isLegal(breakIntoMatrix(v,N/LEN)))
{
PRINT_VECTOR_hor(v);
result.push_back(v);
}
cout<<"RESULT------------------\t\n";
show(result,N/LEN);
PRINTVAR(result.size());
cout<<"END------------------\t\n";
//vector<int> t;
//t.push_back(0);
//t.push_back(1);
//t.push_back(2);
//t.push_back(3);
//auto u=breakIntoMatrix(t,2);
////for(auto i:u)
//// for(auto j:i)
//// PRINTVAR(j);
//for (int i=0;i<u.size();i++)
// for (int j=0;j<u[0].size();j++)
// PRINTVAR(u[i][j]);
//PRINTVAR(isLegal(u));
return 1;
}
vector<vector<int>> genPermutations(int n)
{
vector<vector<int>> r;
if(n==1)
{
vector<int> p;
p.push_back(0);
r.push_back(p);
return r;
}
else
{
int NEW_ADDED_NUM=n-1;
auto permutations_n_1=genPermutations(n-1);
for(auto one_p_n_1:permutations_n_1)
{
int marker=n-1;
while(marker!=-1)
{
vector<int> p;
int cntr=0;
for(auto num:one_p_n_1)
{
//PRINT_DEBUG_INFO();
if(cntr==marker)
p.push_back(NEW_ADDED_NUM);
p.push_back(num);
cntr++;
}
if(marker==one_p_n_1.size())
p.push_back(NEW_ADDED_NUM);
r.push_back(p);
marker--;
}
}
return r;
}
}
void show(vector<vector<int>> p,int length)
{
//PRINT_DEBUG_INFO();
//PRINTVAR(p.size());
for(auto i:p)
{
//PRINTVAR(i.size());
if(length!=0)
cout<<"------"<<endl;
if(length==0)
{
for(auto j:i)
{
cout<<j;
cout<<"\t";
}
cout<<endl;
}
else
{
int cnt=0;
for(auto j:i)
{
cout<<j;
cout<<"\t";
if((cnt+1)%length==0)
cout<<endl;
cnt++;
}
cout<<endl;
}
}
}
vector<vector<int>> breakIntoMatrix(vector<int> v,int length)
{
//PRINTVAR(v.size());
//PRINTVAR(length);
assert(v.size()%length==0);
vector<vector<int>> r;
int cntr=0;
vector<int> t;
for(auto i:v)
{
//PRINTVAR(i);
//PRINTVAR(cntr);
if((cntr+1)%length!=0)
{
t.push_back(i);
//PRINT_VECTOR_hor(t);
}
else
{
t.push_back(i);
//PRINT_VECTOR_hor(t);
r.push_back(t);
t.clear();
}
cntr++;
//PRINT_DEBUG_INFO();
}
//PRINT_DEBUG_INFO();
return r;
}
bool isLegal(vector<vector<int>> v)
{
for (int i=0;i<v.size();i++)
{
for (int j=0;j<v[0].size();j++)
{
//PRINTVAR(v[i][j]);
if(i!=0 && v[i][j]<v[i-1][j])
return false;
if(j!=0 && v[i][j]<v[i][j-1])
return false;
}
}
return true;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/8.2.cpp
#include "8.2.h"
#include "include.top.h"
#include <iostream>
using namespace std;
void f8_2() {//FUNC
cout<<"=================="<<endl;
cout<<"Joseph Game"<<endl;
cout<<"=================="<<endl;
int N;
do {
N=10;
cout<<"please enter num of children(10):"<<endl;
cin>>N;
//cout<<"GET strN="<<strN<<endl;
cout<<"GET N="<<N<<endl;
} while(N<1);
int D;
do {
D=3;
cout<<"please enter distance of count(3):"<<endl;
cin>>D;
cout<<"GET D="<<D<<endl;
} while(D<1 || D>N);
bool * array;
if((array=new bool[N])==NULL) {
cout<<"can't allocate more mem, terminating.\n";
exit(1);
}
//cout<<"TRUE:"<<(double)true<<endl;
//cout<<"FALSE:"<<(double)false<<endl;
for (int i=0;i<N;i++) {
array[i]=true;
}
//show_array(array,N) ;
int curr_loc=0;
//int*mark_loc_list=&curr_loc;
int curr_num=1;
int alive_cnt=N;
int ITER_CNT=0;
int next_loc=-1;
int next_num=-1;
do {
bool flag_die=false;
// update loc:
if (curr_loc==N-1) {
next_loc=0;
} else {
next_loc=curr_loc+1;
}
// update num:
if (array[curr_loc]==true) {
next_num=curr_num+1;
// update living status:
if(curr_num==D) {
next_num=1;
array[curr_loc]=false;
alive_cnt--;
flag_die=true;
}
} else {
next_num=curr_num;
}
// show:
//cout<<curr_num<<"!"<<endl;
//// update alive
//if(curr_num==D) {
// curr_num=1;
// array[curr_loc]=false;
// alive_cnt--;
//}
//// show:
if (array[curr_loc]==true || flag_die) {
cout<<"========================"<<endl;
cout<<"curr_loc:"<<curr_loc<<" curr_num:"<<curr_num<<endl;
//cout<<"curr_loc:"<<curr_loc<<" DEAD"<<endl;
show_array(array,N,true,1,&curr_loc) ;
cout<<alive_cnt<<" alive"<<endl;
cout<<"========================"<<endl;
}
ITER_CNT++;
curr_loc=next_loc;
curr_num=next_num;
} while (alive_cnt>=D && ITER_CNT<100);
delete [] array;
}
<file_sep>/cpp/POJ/include/GRAPH.class.h
#ifndef GRAPH_CLASS_H
#define GRAPH_CLASS_H
#include <map>
#include <deque>
#include <iostream>
#include <vector>
#include "include.top.h"
using namespace std;
#define NIL -999
#define COLOR_WHITE 0
#define COLOR_GREY 1
#define COLOR_BLACK 2
template <typename DATA_TYPE>
class NodeInGraph
{
public:
NodeInGraph();
NodeInGraph(DATA_TYPE v);
NodeInGraph(DATA_TYPE v,NodeInGraph* ns,NodeInGraph* fc);
void setmData(DATA_TYPE v){mData=v;};
DATA_TYPE getmData(){return mData;};
void setmNextSibling(NodeInGraph* v){mNextSibling=v;};
NodeInGraph<DATA_TYPE>* getmNextSibling(){return mNextSibling;};
NodeInGraph<DATA_TYPE>* getmNextNSibling(int n=1);
void setmFirstChild(NodeInGraph* v){mFirstChild=v;};
NodeInGraph* getmFirstChild(){return mFirstChild;};
void show();
int mD;
private:
DATA_TYPE mData;
NodeInGraph* mNextSibling;
NodeInGraph* mFirstChild;
};
template <typename TYPE_WEIGHT_Edge>
class Edge
{
public:
Edge() { setWeight(1); directed=false; };
Edge(TYPE_WEIGHT_Edge w) { setWeight(w);directed=false;};
Edge(TYPE_WEIGHT_Edge w,bool d) { setWeight(w);directed=d;};
Edge(TYPE_WEIGHT_Edge w,bool d,double rv,double cv):weight(w),directed(d),r(rv),c(cv) {};
void setWeight(TYPE_WEIGHT_Edge w){weight=w;};
TYPE_WEIGHT_Edge getWeight(){ return weight; };
void setR(double rv){r=rv;};
void setC(double cv){c=cv;};
double getR(){return r;};
double getC(){return c;};
bool isDirected(){return directed;};
void show() { std::cout<<weight<<","<<directed<<","<<r<<","<<c<<std::endl; };
private:
TYPE_WEIGHT_Edge weight;
double r,c;
bool directed;
};
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
class GRAPH
{
public:
GRAPH(unsigned nodeCnt,Edge<TYPE_OF_WEIGHT> defaultEdge);
void addEdge(TYPE_OF_NODE* from,TYPE_OF_NODE* to,Edge<TYPE_OF_WEIGHT> edge);
Edge<TYPE_OF_WEIGHT> getEdge(TYPE_OF_NODE* from,TYPE_OF_NODE* to);
private:
unsigned getNewId();
public:
bool isExistNode(TYPE_OF_NODE* node){
//return !(MAP_name2id.find(node)==MAP_name2id.end());
for(auto p:MAP_name2id)
{
PRINTVAR(p.first);
PRINTVAR(p.second);
PRINTVAR(*p.first);
if(*p.first==*node)
return true;
}
return false;
};
bool isExistId(unsigned id){ return !(MAP_id2name.find(id)==MAP_id2name.end()); };
TYPE_OF_NODE* getNodeById(unsigned id) {return MAP_id2name[id];};
TYPE_OF_NODE* getNodeByName(TYPE_OF_NODE name) {
// name is the value stored in TYPE_OF_NODE*
for(auto p:MAP_name2id)
{
if(*p.first==name)
return p.first;
}
assert(0);
//return 0;
//return MAP_id2name[id];
};
unsigned getIdByNode(TYPE_OF_NODE* node) {return MAP_name2id[node];};
void show();
void showWeight();
void showR();
void showC();
void showMAP_id2BFSdepth(){
for(auto i:MAP_id2BFSdepth)
{
std::cout<<i.first<<"\t->\t"<<i.second<<std::endl;
}
};
void showMAP_id2BFSparent(){
for(auto i:MAP_id2BFSparent)
{
std::cout<<i.first<<"\t->\t"<<i.second<<std::endl;
}
};
vector<vector <Edge<TYPE_OF_WEIGHT>>> getMat(){ return mat; };
map<unsigned,int> getMAP_id2BFSdepth (){ return MAP_id2BFSdepth;};
public:
vector<unsigned> getChildIdList(unsigned nodeId);
vector<unsigned> getParentIdList(unsigned nodeId);
//void traverseDFS(void (*func)(TYPE_OF_NODE*)=0){traverseDFS(Root,"0",func);};
//void traverseBFS(void (*func)(TYPE_OF_NODE*)=0){traverseBFS(Root,"0",func);};
void traverseDFS(TYPE_OF_NODE* fromNode,void (*func)(TYPE_OF_NODE*)=0);
void traverseBFS(TYPE_OF_NODE* fromNode,void (*func)(TYPE_OF_NODE*)=0);
void printBFSTree() {
bool flag_print=true;
for(int depth=0;flag_print;depth++)
{
flag_print=false;
for(auto i:MAP_id2BFSdepth)
{
if(i.second==depth)
{
int tmpd=depth;
while(tmpd--)
cout<<"-->";
cout<<i.first<<"("<<*MAP_id2name[i.first]<<")"<<endl;
flag_print=true;
}
}
}
};
void printShortestPath(unsigned fromId,unsigned toId,std::string prefix="PSP:\t"){
std::cout<<"calling printShortestPath(), from "<<fromId<<" to "<<toId<<std::endl;
// this method must be used after run traverseBFS()
if(fromId==toId)
std::cout<<prefix<<fromId<<std::endl;
else if (MAP_id2BFSparent[toId]==NIL)
{
std::cout<<"in printShortestPath(), no path from "<<fromId<<" to "<<toId<<std::endl;
}
else
{
printShortestPath(fromId,MAP_id2BFSparent[toId],prefix);
std::cout<<prefix<<toId<<std::endl;
}
};
map<unsigned,int> MAP_id2DFSdepth_grey;
map<unsigned,int> MAP_id2DFSdepth_black;
private:
map<unsigned,unsigned> MAP_nodeId2color_DFS; // map id2color 0:white,1:grey,2:black;
vector<unsigned> visitStack_DFS;
int DFSvisitTime;
map<unsigned,int> MAP_id2DFSparent;
void traverseDFS_recur(TYPE_OF_NODE* fromNode,
vector<unsigned>* ptr_visitedList,
void (*func)(TYPE_OF_NODE*)=0
);
private:
map<TYPE_OF_NODE*,unsigned> MAP_name2id;
map<unsigned,TYPE_OF_NODE*> MAP_id2name;
map<unsigned,int> MAP_id2BFSdepth;
map<unsigned,int> MAP_id2BFSparent;
//std::vector<unsigned> nodeIdList;
vector<vector <Edge<TYPE_OF_WEIGHT>>> mat;
unsigned mNodeCnt;
};
#endif
<file_sep>/cpp/7_EXEs_separated/exe_remove_some_lines/run.sh
#echo "existing" > existing
rm a.out; g++ -v -g -Wall -std=c++11 copy.cpp ; ./a.out
<file_sep>/tcl/tcl_call_cpp/2_swig/dbg.sh
echo "--------------------------------->"
gcc -c fract.c fract_wrap.c -fPIC -I/home/zz/Downloads/tcl8.6.10/generic
gcc -shared -fPIC -o libfract.so fract_wrap.o fract.o
/usr/bin/tclsh test.tcl
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch1_life_game/include/life_game.h
void main_life_game();
<file_sep>/cpp/exe_nullptr/s.cpp
#include <iostream>
using namespace std;
class TEST
{
public:
int* getP(){
return p;
};
void setP(int* n){
p=n;
}
void show() {
cout<<*p<<endl;
}
private:
int* p;
};
int main() {
TEST t;
int i=1234;
int* n=&i;
//t.setP(n);
t.show();
return 1;
}
<file_sep>/python/workspace_python/design_pattern/src/Strategy/Cashier.py
__author__ = 'jc'
__version__='use Abstract Factory'
class Cashier:
def getMethod(self,name):
if name=='normal':
return calcBasic()
elif name=='debate':
return calcDebate()
elif name=='fullcut'
return calcFullCut
else:
print 'illegal argument:'+name
class AbstractCalc:
def calc(self,sumIn):
pass
class calcBasic(AbstractCalc):
def calcBasic(self):
pass
def calc(self,sumIn):
return sumIn
class calcDebate(AbstractCalc):
def calcDebate(debate):
self.debate=debate
def calc(self,sumIn):
return sumIn*self.debate
class calcFullCut(AbstractCalc):
def calcFullCut(bound,cut):
self.bound=bound
self.cut=cut
def calc(self,sumIn):
if sumIn>=self.bound:
return sumIn-self.cut
else:
return sumIn
if __name__ == "__main__":
cs=Cashier()
method=cs.getMethod('normal')
method
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/11.2.h
void f11_2();
<file_sep>/python/workspace_python/dive_into_python/src/1/1/1p3.py
# tuple
cm=("a","b","c")
print cm[1]
u=["u1","u2"]
v=["v1","v2"]
cm=(u,v,"w")
print cm
#cm[0]="change" ;# can not change, cause error
print cm
cm[0][0]="u1change";# can change, because u is list not a tuple
print cm
<file_sep>/python/workspace_python/Ocr/Ocr.py
__author__ = 'admin'
import sys
from pyocr import pyocr
print ('TEST')
tools = pyocr.get_available_tools()[:]
if len(tools) == 0:
print("No OCR tool found")
sys.exit(1)
print("Using '%s'" % (tools[0].get_name()))
tools[0].image_to_string(Image.open('test.png'), lang='fra',
builder=TextBuilder())<file_sep>/python/workspace_python/basic_algorithm_of_python/print_star_recur.py
__author__ = 'jc'
def p(n,total):
if n==1:
print(" "*(total-1)+"*",end="")
else:
p(n-1,total)
print()
u=2*n-1
print(" "*(total-n)+"*"*u,end="")
def p_top(u):
p(u,u)
p_top(60)<file_sep>/cpp/5_BOOK_CPP_PRIMER/src/exe_3.2.cpp
#include "include.top.h"
using namespace std;
using std::string;
string choose_larger_string(string s1,string s2) {
return s1>s2?s1:s2;
}
string choose_longer_string(string s1,string s2) {
return s1.length()>s2.length()?s1:s2;
}
void exe_3_2() {
#if 0
cout<<"==============="<<endl;
cout<<"exe_3_2:"<<""<<endl;
cout<<"==============="<<endl;
cout<<"read line;"<<endl;
string s;
getline(cin,s);
PRINTVAR(s);
cout<<"read words;"<<endl;
string word;
while(cin>>word) {
cout<<"word:"<<word<<""<<endl;
}
#endif
cout<<"==============="<<endl;
cout<<"exe_3_4:"<<""<<endl;
cout<<"==============="<<endl;
string s1("abcde"),s2("wxyz");
cout<<"larger="<<choose_larger_string(s1,s2)<<""<<endl;
cout<<"longer="<<choose_longer_string(s1,s2)<<""<<endl;
for(auto c:s1) {
cout<<"ITER: "<<c<<""<<endl;
}
cout<<"==============="<<endl;
cout<<"exe use reference:"<<""<<endl;
cout<<"==============="<<endl;
string s3="Hello world!!";
for(auto &c:s3) {
c=toupper(c);
}
PRINTVAR(s3);
cout<<"==============="<<endl;
cout<<"exe_3_6:"<<""<<endl;
cout<<"==============="<<endl;
string s6("This is 1 string!");
PRINTVAR(s6);
for(char &c:s6)
{
if(isalpha(c)) {
//c=toupper(c);
c='X';
}
}
PRINTVAR(s6);
cout<<"==============="<<endl;
cout<<"exe_3_8:"<<""<<endl;
cout<<"==============="<<endl;
cout<<"use while:"<<endl;
string s8("This is 1 string!");
PRINTVAR(s8);
int cnt=0;
char c;
while(s8[cnt]) {
//cout<<"s8[cnt]="<<s8[cnt]<<""<<endl;
c=s8[cnt];
if(isalpha(c)) {
//cout<<"X"<<""<<endl;
s8[cnt]='X';
}
cnt++;
}
PRINTVAR(s8);
cout<<"use traditional for:"<<endl;
string s81("This is 1 string!");
PRINTVAR(s81);
for(decltype(s8.size()) cnt=0;cnt<s8.size();cnt++)
{
//cout<<"s81[cnt]="<<s81[cnt]<<""<<endl;
c=s81[cnt];
if(isalpha(c)) {
//cout<<"X"<<""<<endl;
s81[cnt]='X';
}
}
PRINTVAR(s81);
cout<<"==============="<<endl;
cout<<"exe_3_10:"<<""<<endl;
cout<<"==============="<<endl;
string s10("this is a sting, with , . ; ) and [");
PRINTVAR(s10);
for(char &c:s10)
{
if(isalpha(c)) {
//c=toupper(c);
//c='X';
} else {
c=' ';
}
}
PRINTVAR(s10);
cout<<"==============="<<endl;
cout<<"end"<<""<<endl;
cout<<"==============="<<endl;
//string u=toupper(s10.begin());
string u=string(1,toupper(s10[0]));
string out1="Upper first: "+u;
//string out1="Upper first: ";
cout<<out1<<endl;
cout<<"==============="<<endl;
cout<<"END OF DEBUG"<<""<<endl;
}
<file_sep>/tcl/tcl_call_cpp/1/Makefile
# 【Makefile】:
t = libfract.so
all: $t
clean:
rm -f $t core
libfract.so: fract.c
gcc -I. -shared -o $@ fract.c
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/src/lib.cpp
#include <math.h>
#include <stdio.h>
#include <iostream>
//#include "lib.h"
#include "include.top.h"
using namespace std;
double myfac (int n) {// FUNC
if (n<=1) {return 1;
} else {
double r=n*myfac(n-1);
cout <<"myfac "<<n<<" = "<<r<<endl;
return r;
}
}
double calc_sum_of_power (int n,int power) {// FUNC
double sum=0;
while (n!=0) {
int curr=n%10;
double p=pow(curr,power);
sum+=p;
n=n/10;
}
return sum;
}
bool is_tulip (int n, int power) {// FUNC
return (n==calc_sum_of_power(n,power));
}
bool is_prime (int n, int print) {// FUNC
int up_bound=(int)sqrt(n);
for (int i=2;i<=up_bound;i++) {
if(n%i==0) {
return false;
}
}
return true;
}
bool is_full_num (int n, int print) {// FUNC
//计算100000以内完数:
//1 2 3 =6
//1 2 4 7 14 =28
//1 2 4 8 16 31 62 124 248 =496
//1 2 4 8 16 32 64 127 254 508 1016 2032 4064 =8128
int n_left=n;
int up_bound=n-1;
for (int i=1;i<=up_bound;i++) {
if (n%i==0) {
if (print==1) printf("%d ",i);
n_left-=i;
}
}
if (n_left==0 && !print) {
is_full_num (n,1);
return true;
} else {
return false;
}
}
double calc_use_do (double x, double stop) {// FUNC
double r=0;
int n=0;
double incr;
do {
incr=pow(-1,n+1)*pow(x,n)/ myfac(n);
r+=incr;
//cout<<"ITER:"<<n<<";incr="<<incr<<";r="<<r<<endl;
n++;
//cout<<"fabs(incr)="<<fabs(incr)<<endl;
} while (fabs(incr) >= stop);
cout<<"calc_use_do return="<<r<<endl;
return r;
}
bool is_int (double v) {// FUNC
return ((int)v==v);
}
//double integral(double from,double to){// FUNC
// cout<<"calc integral from: "<<from<<" to: "<<to<<endl;
// cout<<" target func: f("<<from<<")= "<<target_func(from)
// <<" target func: f("<<to <<")= "<<target_func(to )<<endl;
// return 1.1;
//}
bool item_is_in_array (int item,int array[] ,int a_length) {// FUNC
bool tag=false;
for (int j=0;j<a_length;j++) {
if (item==array[j]) {tag=true;break;}
}
return tag;
}
void show_array(double a[],int size,bool in_a_line,int num_of_marker, int marker[]) {// FUNC
//int size=sizeof(a)/sizeof(double);
if (in_a_line) {
for (int i=0;i<size;i++) {// print index line
//cout<<"swap:"<<","<<a[i+1]endl;
char tag;
if (item_is_in_array(i,marker,num_of_marker)) {
tag='M';
}else{
tag=' ';
}
printf("%9d%1c,",i,tag);
}
printf("\n");
for (int i=0;i<size;i++) {// print value line
//cout<<"swap:"<<","<<a[i+1]endl;
printf("%10.2f,",a[i]);
}
printf("\n");
} else {
printf("--------------\n");
printf("show array of size %d\n",size);
for (int i=0;i<size;i++) {
char tag;
if (item_is_in_array(i,marker,num_of_marker)) {
tag='M';
}else{
tag=' ';
}
//cout<<"swap:"<<","<<a[i+1]endl;
printf("array[%5d](%10.2f)%10c\n",i,a[i],tag);
}
printf("--------------\n");
}
}
void show_array(int a[],int size,bool in_a_line,int num_of_marker, int marker[]) {// FUNC
double da[size];
for (int i=0;i<size;i++) {// convert int to double
da[i]=(double)a[i];
}
show_array(da,size,in_a_line,num_of_marker,marker);
}
void show_array(bool a[],int size,bool in_a_line,int num_of_marker, int marker[]) {// FUNC
if (in_a_line) {
for (int i=0;i<size;i++) {// print index line
//cout<<"swap:"<<","<<a[i+1]endl;
char tag;
if (item_is_in_array(i,marker,num_of_marker)) {
tag='M';
}else{
tag=' ';
}
printf("%9d%1c,",i,tag);
}
printf("\n");
for (int i=0;i<size;i++) {// print value line
//cout<<"swap:"<<","<<a[i+1]endl;
//printf("%10.2f,",a[i]);
if(a[i]) {printf("%10s,","A");
} else {printf("%10s,","_");}
}
printf("\n");
} else {
printf("--------------\n");
printf("show array of size %d\n",size);
for (int i=0;i<size;i++) {
char tag;
if (item_is_in_array(i,marker,num_of_marker)) {
tag='M';
}else{
tag=' ';
}
//cout<<"swap:"<<","<<a[i+1]endl;
printf("array[%5d](%10.2f)%10c\n",i,a[i],tag);
}
printf("--------------\n");
}
}
void sort_bubble(double a [],int size,int return_list[]) {// FUNC
//int return_list[2];
int swap_cnt=0;
int diff_cnt=0;
bool swap_tag=1;
int pass=1;
while (swap_tag) {
cout<<"ITER from 0,1 to $-1,"<<size-pass<<endl;
swap_tag=0;
for (int i=0;i<size-pass;i++) {
if (a[i]<a[i+1]) {
swap_tag=1;
//cout<<"swap:"<<","<<a[i+1]endl;
//printf("swap a[%d](%10.2f) a[%d](%10.2f)\n",i,a[i],i+1,a[i+1]);
int tmp[]={i,i+1};
show_array(a,size,true,2,tmp);
double temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
show_array(a,size,true,2,tmp);
swap_cnt++;
}
diff_cnt++;
}
//cout<<"diff_cnt="<<diff_cnt<<endl;
//cout<<"swap_cnt="<<swap_cnt<<endl;
return_list[0]=diff_cnt;
return_list[1]=swap_cnt;
show_array(return_list,2,false);
pass++;
}
//return return_list;
}
string dec2bin(int n) {
string s;
long r=0;
if(n==0)
{
//cout<<" 0-->0\n";
return 0;
}
s=" ";
int mul=1;
for(int a=n;a;a=a/2)
{
s=s+(a%2?'1':'0');
r=r+(a%2?1:0)*mul;
mul*=10;
}
std::reverse(s.begin(),s.end());
const char *sss=s.c_str();
//cout.width(11);
//cout<<n<<(n<0?"-->-":"-->")<<sss<<"\n";
return s;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/3.5.cpp
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
typedef int INT;
int main3_5 () {
INT cnt=0;
const int width=20;
cout<<setw(3*width)<<setfill('-')<<" "<<endl;
cout<<setfill(' ');
cout<<setw(width)<<"x"
<<setw(width)<<"%3"
<<setw(width)<<"%5"
<<setw(width)<<"%7"
<<endl;
string can_div_by_3;
string can_div_by_5;
string can_div_by_7;
string tag;
for (int x=7;x<=20;x++) {
can_div_by_3=" ";
can_div_by_5=" ";
can_div_by_7=" ";
if (x%3==0) {can_div_by_3="3"; }
if (x%5==0) {can_div_by_5="5"; }
if (x%7==0) {can_div_by_7="7"; }
if (can_div_by_3==" "
&& can_div_by_5==" "
&& can_div_by_7==" "
) {
tag="X";
} else {
tag="";
}
cout
<<setw(width)<<x
<<setw(width)<<can_div_by_3
<<setw(width)<<can_div_by_5
<<setw(width)<<can_div_by_7
<<setw(width)<<tag
<<endl;
}
return 0;
}
<file_sep>/cpp/leetcode/sort_list/time.sh
t1=`./get_date.tcl`
./a.out
t2=`./get_date.tcl`
echo "$t2-$t1" | bc -l
<file_sep>/tcl/tcl_call_cpp/1/fract.c
// 【fract.c】:
#include "tcl.h"
int Tcl_myfract(ClientData notUsed, Tcl_Interp *interp, int argc, char **argv)
{
int i, j;
double res=1.0;
char re[30];
if (argc > 2)
{
Tcl_SetResult(interp, "wrong args: should be myfract", TCL_VOLATILE);
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[1], &i) != TCL_OK)
{
return TCL_ERROR;
}
for (j=1;j<=i;j++)
res *= j;
sprintf(re,"%le",res);
Tcl_SetResult(interp, re, TCL_VOLATILE);
return TCL_OK;
}
int Fract_Init(Tcl_Interp *Interp) {
Tcl_CreateCommand (Interp, "myfract", (Tcl_CmdProc *)Tcl_myfract, (ClientData)0, 0);
return TCL_OK;
}
<file_sep>/cpp/sort_algorithms/include/1_bubble_sort.h
#include <stdio.h>
#include <iostream>
int func_1_bubble_sort(int*r_cnt) ;
int func_1_bubble_sort(int*r_cnt,int LENGTH) ;
int func_1_bubble_sort(int*r_cnt,int LENGTH,int seed_incr) ;
<file_sep>/cpp/ch1.1.cpp/hello_world.cpp
#include <iostream>
#include <math.h>
using namespace std;
int main () {
cout <<"Hi there!\n";
return 0;
}
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/src/f13_2.cpp
#include "include.top.h"
void f13_2() {
PRINT_DEBUG_INFO();
}
void showInfo() {
cout<<"-------------"<<endl;
//cout<<"FILE:\t"<<__FILE__<<endl;
//cout<<"LINE:\t"<<__LINE__<<endl;
//cout<<"DATE:\t"<<__DATE__<<endl;
//cout<<"TIME:\t"<<__TIME__<<endl;
//cout<<"STDC:\t"<<__STDC__<<endl;
cout<<"DEBUG: " <<__FILE__<<":" <<__LINE__<<" compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<endl;
cout<<"-------------"<<endl;
}
<file_sep>/cpp/POJ/src/main.cpp
//#include "include.top.h"
//--------------------------------------
#include "poj1000.h"
#include "poj1001.h"
#include "poj1002.h"
#include "poj1003.h"
#include "poj1006.h"
#include "poj1753.h"
#include "poj2965.h"
#include "poj1328.h"
#include "poj2109.h"
#include "poj3295.h"
#include "poj2632.h"
#include "poj1860.h"
//using namespace std;
int main() {
//-----------------------------------------------
cout<<"-----------------------------------------------"<<endl;
cout<<"POJ:"<<endl;
//-----------------------------------------------
//poj1000();
//poj1001();
//poj1002();
//poj1003();
//poj1006();
//poj1753();
//poj2965();
//poj1328(); // use gnuplot
//poj2109(); // use bitInt library to calc 22-bit int
//poj3295();
//poj2632();// board and robots
poj1860(); // graph
return 0;
}
<file_sep>/cpp/6_EXEs/include/exe_operator.h
class Employee_class {
public:
Employee_class(int age, std::string name) : age(age), name(name) { }
Employee_class& operator+=(const int age)
{
this->age=this->age+1;
return *this;
}
Employee_class& operator+=(const Employee_class & rhs)
{
this->age=this->age+rhs.age;
return *this;
}
Employee_class& operator++()
{
this->age++;
return *this;
}
bool operator< (const Employee_class & rhs) { return this->getAge() < rhs.getAge(); }
bool operator> (const Employee_class & rhs) { return this->getAge() > rhs.getAge(); }
bool operator<=(const Employee_class & rhs) { return !(*this>rhs); }
bool operator>=(const Employee_class & rhs) { return !(*this<rhs); }
int getAge() const {return age; }
std::string getName() const {return name;}
private:
int age;
std::string name; // Does not particpate in comparisons
};
void exe_operator ();
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/ch_7.5.h
#include <stdio.h>
#include <iostream>
int f_ch_7_5() ;
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph/GraphAdjList.cpp
#include "../../include/include.h"
#include "GraphAdjList.h"
GraphAdjList::GraphAdjList(int ve){
DENTER;
//DLOG(ve);
mV=ve;
mE=0;
mAdj={};
for(int i=0;i<ve;i++)
mAdj.push_back({});
DRETURN;
}
GraphAdjList::GraphAdjList(string fname){
string filename=fname;
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
int a, b;
int sum;
int cntLine=0;
while (infile >> a >> b)
{
cntLine++;
DLOG(cntLine);
DLOG(a);
DLOG(b);
if(cntLine==1)
{
mV=a;
mE=0;
mAdj={};
for(int i=0;i<a;i++)
mAdj.push_back({});
}
else
{
addEdge(a,b);
}
}
}
int GraphAdjList::V(){
return mV;
}
int GraphAdjList::E(){
DENTER;
DRETURN;
return mE;
}
void GraphAdjList::addEdge(int v,int w){
DENTER;
//DLOG(v);
//DLOG(w);
mAdj[v].push_back(w);
mAdj[w].push_back(v);
//DLOG(mAdj.size());
//DLOG(mAdj[v].size());
mE++;
DRETURN;
}
vector<int> GraphAdjList::adj(int v){
DENTER;
//DLOG(v);
//DLOG(mAdj.size());
//DLOG(mAdj[v].size());
DRETURN;
return mAdj[v];
}
//////////////////////////
// P337 Table4.1.4
//////////////////////////
vector<int> GraphAdjList::search(int s) // find all nodes connected s
{
return {};
}
bool GraphAdjList::marked(int s,int v) // does v connected to s
{
return 0;
}
int GraphAdjList::count(int s) // # of nodes connected s
{
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/5.1.h
int f5_1 () ;
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/4.3.cpp
#include <iostream>
#include <math.h>
#include <iomanip>
#include <time.h>
#include <stdio.h>
#include "lib.h"
using namespace std;
int main4_3 () {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
for (int cnt=0;cnt<=1e4;cnt++) {
if (is_tulip(cnt,3)) {
cout<<cnt<<endl;
}
}
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/8.1.h
void f8_1();
int* findmax(int* array,int size,int* index);
void show_array_with_addr(int* array,int size);
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.2_directed_graph/DirectedDFS.h
#include "../../include/include.h"
#include "Digraph.h"
class DirectedDFS
{
//////////////////////////////
// Table 4.2.3
//////////////////////////////
public:
DirectedDFS(Digraph*G,int s)
{
mMarked.resize(G->V(),0);
dfs(G,s);
}
DirectedDFS(Digraph*G,vector<int> sources)
{
mMarked.resize(G->V(),0);
for(int s:sources )
if(!mMarked[s]) dfs(G,s);
}
bool marked(int v)
{
return mMarked[v];
}
private:
void dfs(Digraph*G,int v)
{
mMarked[v]=true;
for(int w:G->adj(v))
if(!mMarked[w])
dfs(G,w);
}
private:
vector<bool> mMarked;
};
class TestDirectedDFS
{
public:
TestDirectedDFS()
{
Digraph*G=new Digraph("tinyG.txt");
DLOG(G->toString());
G->dumpDOT("TestDirectedDFS.dot");
vector<int> sources;
sources.push_back(5);
//sources.push_back(11);
DLOG(sources);
DirectedDFS* reachable=new DirectedDFS(G,sources);
for(int v=0;v<G->V();v++)
{
if(reachable->marked(v))
cout<<v<<" ";
}
cout<<endl;
}
};
<file_sep>/cpp/exe_operator_for_map/run.sh
rm a.out
g++ -g -Wall -std=c++11 s.cpp;
#g++ -g -Wall s.cpp;
./a.out
<file_sep>/python/workspace_python/dive_into_python/src/1/scan_chain_research/scan_chain_oo.py
rname=range(10)
rx=range(10)
ry=range(10)
rx[0] = 859
ry[0] = 740
rx[1] = 134
ry[1] = 92
rx[2] = 315
ry[2] = 721
rx[3] = 840
ry[3] = 621
rx[4] = 638
ry[4] = 772
rx[5] = 690
ry[5] = 591
rx[6] = 950
ry[6] = 191
rx[7] = 606
ry[7] = 596
rx[8] = 130
ry[8] = 494
rx[9] = 687
ry[9] = 653
import random
W=1000
H=1000
r=None
class Reg(object):
def __init__(self, name, loc_x,loc_y):
self.name= name
self.x=loc_x
self.y=loc_y
self.pre=None
self.next=None
self.print_loc()
def print_loc(self):
print 'reg: %s is located in %s, %s' %(self.name, self.x, self.y)
head=Reg('head',0,0)
lastReg=Reg('temp',0,0)
lastReg=head
for i in range(10):
tempReg=Reg(rname[i],rx[i],ry[i])
lastReg.next=tempReg
tempReg.pre=lastReg
lastReg=head
thisReg=Reg('temp',0,0)
while lastReg.next!=None:
thisReg=lastReg.next
thisReg.print_loc()
<file_sep>/java/Assignment2/Pyramid.java
/*
* File: Pyramid.java
* Name:
* Section Leader:
* ------------------
* This file is the starter file for the Pyramid problem.
* It includes definitions of the constants that match the
* sample run in the assignment, but you should make sure
* that changing these values causes the generated display
* to change accordingly.
*/
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
import sun.java2d.loops.DrawLine;
import sun.java2d.loops.DrawRect;
public class Pyramid extends GraphicsProgram {
/** Width of each brick in pixels */
private static final int BRICK_WIDTH = 30;
/** Height of each brick in pixels */
private static final int BRICK_HEIGHT = 12;
/** Number of bricks in the base of the pyramid */
private static final int BRICKS_IN_BASE = 12;
private static final Color BRICKS_COLOR = Color.BLACK;
public void run() {
/* You fill this in. */
System.out.println( this.getHeight());
int currSumOfBricks=BRICKS_IN_BASE;
double currX=BRICK_WIDTH*3;
double currY=this.getHeight()-BRICK_HEIGHT;
while (currSumOfBricks>=1) {
drawARow(currX, currY,currSumOfBricks );
currSumOfBricks--;
currX+=BRICK_WIDTH/2;
currY-=BRICK_HEIGHT;
}
}
//-----------------
public GRect drawRect (double x,double y,double width, double height, Color c) {
GRect rect=new GRect(x,y,width,height);
rect.setFilled(false);
rect.setColor(c);
add(rect);
return rect;
}
public void drawARow (double startX,double startY,int numOfBricks) {
int cntr=0;
double currX=startX;
double currY=startY;
while (cntr<numOfBricks) {
drawRect(currX, currY, BRICK_WIDTH, BRICK_HEIGHT, BRICKS_COLOR);
currX+=BRICK_WIDTH;
//currY+=BRICK_HEIGHT;
cntr++;
}
}
}
<file_sep>/cpp/leetcode/Longest_Increasing_Subsequence/s.handout.cpp
#include <vector>
#include <string>
#include <iostream>
//#include <algorithm>
//#include <deque>
//#include <map>
//#include <assert.h>
using namespace std;
class Solution {
public:
int isIncremental(vector<int>& nums,int from,int to)
{
for(int i=from;i<=to-1;i++)
{
if(nums[i]>nums[i+1])
return false;
}
return true;
}
void getMaxIncr(vector<int>&nums,int from,int to,int lowBound,vector<int>&vInd)
{
if(from>to)
{
return;
}
if(from==to && nums[from]>lowBound)
{
vInd.push_back(from);
return;
}
// from < to:
// with from:
vector<int> vIndSub1,vIndSub2;
if(nums[from]>lowBound)
{
vIndSub1.push_back(from);
getMaxIncr(nums,from+1,to,nums[from],vIndSub1);
}
// without from:
getMaxIncr(nums,from+1,to,lowBound,vIndSub2);
auto added=(vIndSub1.size()>vIndSub2.size())?vIndSub1:vIndSub2;
for(auto i:added)
{
vInd.push_back(i);
}
}
int lengthOfLIS(vector<int>& nums) {
if(nums.size()==0)
return 0;
////////////////
bool ordered=true;
for(int i=0;i<nums.size()-1;i++)
{
if(nums[i]>=nums[i+1])
{
ordered=false;
break;
}
}
if(ordered)
{
return nums.size();
}
////////////////
vector<int> vInd;
getMaxIncr(nums,0,nums.size()-1,-9999,vInd);
return vInd.size();
}
};
int main()
{
//vector<int> v={3,2,5,4,1,7};
vector<int> v={1,2,3,4};
//vector<int> v={2,2};
Solution s;
int R=s.lengthOfLIS(v);
cout<<"R="<<R<<""<<endl;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/3.4.cpp
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
typedef int INT;
int main3_4 () {
INT cnt=0;
const int width=20;
cout<<setw(3*width)<<setfill('-')<<" "<<endl;
cout<<setfill(' ');
cout<<setw(width)<<"x"<<setw(width)<<"f(x)=x*(x+2)"<<endl;
for (int x=2;x<=10;x++) {
cout<<setw(width)<<x<<setw(width)<<x*(x+2)<<endl;
}
cout<<setw(3*width)<<setfill('-')<<" "<<endl;
cout<<setfill(' ');
cout<<setw(width)<<"x"<<setw(width)<<"f(x)=2*x"<<endl;
for (int x=-1;x<=2;x++) {
cout<<setw(width)<<x<<setw(width)<<x*2<<endl;
}
cout<<setw(3*width)<<setfill('-')<<" "<<endl;
cout<<setfill(' ');
cout<<setw(width)<<"x"<<setw(width)<<"f(x)=x-1"<<endl;
for (int x=-7;x<=-1;x++) {
cout<<setw(width)<<x<<setw(width)<<x-1<<endl;
}
return 0;
}
<file_sep>/cpp/codewar/fun_with_trees/max_sum/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
//#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#include <vector>
#include <string>
#include <iostream>
#include <deque>
#include <assert.h>
class TreeNode
{
public:
TreeNode* left;
TreeNode* right;
int value;
};
class Solution
{
public:
static int maxSum(TreeNode* root)
{
// TODO: implementation
if(!root->left )
{
if(!root->right)
return value;
else
return maxSum(root->right);
}
else
{
if(!root->right)
return maxSum(root->left);
else
{
auto max_left= maxSum(root->left);
auto max_right= maxSum(root->right);
return (max_left>max_right)?max_left:max_right;
}
}
}
};
int main ()
{
std::vector<int> arr = {17, 0, -4, 3, 15};
//TreeNode* expected = new TreeNode(17, new TreeNode(0, new TreeNode(3), new TreeNode(15)), new TreeNode(-4));
//Assert::That(*Solution::arrayToTree(arr), Equals(*expected));
//*Solution::arrayToTree(arr);
auto n1=TreeNode(1);
auto n2=TreeNode(1);
PRINTVAR((n1==n2));
return 0;
}
<file_sep>/cpp/leetcode/combinational_sum/golden/s.cpp
#define SIMPLE_LOG 0
#define LNX 1
#if (!SIMPLE_LOG)
#define DLOG(x) cout<<#x<<"="<<x<<" @"<<__LINE__<<endl;
#define DLOG1(x) cout<<#x<<"="<<x<<"\t";
#else
#define DLOG(x)
#define DLOG1(x)
#endif
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#if (!SIMPLE_LOG)
#define DENTER \
LVCALL++; PRLVCALL; ::std::cout<<"-->"<<__FUNCTION__<<::std::endl;
#define DRETURN \
PRLVCALL; ::std::cout<<"<--"<<__FUNCTION__<<"@" <<__LINE__<<::std::endl; LVCALL--;
#endif
#define DEBUG_MARK PRINT_DEBUG_INFO()
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define DPRINT(x) \
(::std::cout<<x<<::std::endl )
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#if SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define DEBUG_MARK
#define PRINT_DEBUG_INFO_PREFIX(p)
#define DPRINT(x)
#define PRINT_COUT(p)
#define DENTER
#define DRETURN
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <regex>
#include <map>
#include <assert.h>
using namespace std;
#if !SIMPLE_LOG
static int LV=0;
static int LVCALL=-1;
//#define PRLV std::cout<<LV<<"\t"; for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLV for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLVCALL std::cout<<"L"<<LVCALL<<"\t"; for(int u12=LVCALL;u12>0;u12--) {std::cout<<" .. ";}
template <class U>
std::ostream & operator <<(std::ostream &os, const std::vector<U> &m)
{
if(m.size()==0)
return os;
os << std::endl;
PRLV(LV);
os << "->";
os << std::endl;
LV++;
PRLV(LV);
for (const auto &p : m)
{
os << p << ", " ;
}
os << std::endl;
LV--;
PRLV(LV);
os << "<-";
return os;
}
template <class U, class V>
std::ostream & operator <<(std::ostream &os, const std::map<U, V> &m)
{
os << "->";
os << std::endl;
for (const auto &p : m)
{
os << p.first << ": " << p.second;
os << std::endl;
}
os << "<-";
return os;
}
#endif
//=========================================================================================
//Accepted 16ms c++ solution use backtracking for Combination Sum:
int cntSort=0;
int cntPushPop=0;
class Solution1 {
public:
std::vector<std::vector<int> > combinationSum(std::vector<int> &candidates, int target) {
DENTER;
std::sort(candidates.begin(), candidates.end());
cntSort++;
std::vector<std::vector<int> > res;
std::vector<int> combination;
combinationSum(candidates, target, res, combination, 0);
DRETURN;
return res;
}
private:
void combinationSum(std::vector<int> &candidates, int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin) {
DENTER;
DLOG1(target);
DLOG1(begin);
DLOG(res);
if (!target) {
DPRINT("res.push_back");
res.push_back(combination);
cntPushPop++;
DRETURN;
return;
}
for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) {
combination.push_back(candidates[i]);
DLOG(combination );
combinationSum(candidates, target - candidates[i], res, combination, i);
combination.pop_back();
cntPushPop+=2;
}
DRETURN;
}
};
//Accepted 12ms c++ solution use backtracking for Combination Sum II:
class Solution2 {
public:
std::vector<std::vector<int> > combinationSum(std::vector<int> &candidates, int target) {
std::sort(candidates.begin(), candidates.end());
std::vector<std::vector<int> > res;
std::vector<int> combination;
combinationSum(candidates, target, res, combination, 0);
return res;
}
private:
void combinationSum(std::vector<int> &candidates, int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin) {
if (!target) {
res.push_back(combination);
return;
}
for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i)
if (i == begin || candidates[i] != candidates[i - 1]) {
combination.push_back(candidates[i]);
combinationSum(candidates, target - candidates[i], res, combination, i + 1);
combination.pop_back();
}
}
};
//Accepted 0ms c++ solution use backtracking for Combination Sum III:
class Solution3 {
public:
std::vector<std::vector<int> > combinationSum(int k, int n) {
std::vector<std::vector<int> > res;
std::vector<int> combination;
combinationSum(n, res, combination, 1, k);
return res;
}
private:
void combinationSum(int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin, int need) {
if (!target) {
res.push_back(combination);
return;
}
else if (!need)
return;
for (int i = begin; i != 10 && target >= i * need + need * (need - 1) / 2; ++i) {
combination.push_back(i);
combinationSum(target - i, res, combination, i + 1, need - 1);
combination.pop_back();
}
}
};
#if LNX
int main()
{
clock_t start, end;
start = clock();
////////////////////////////////////////////////
Solution1 sol;
//vector<int> cand={1,2,3,6,7};
//vector<int> cand={1,2,4,7,8,9,10,11,12,13,14};
vector<int> cand={48,22,49,24,26,47,33,40,37,39,31,46,36,43,45,34,28,20,29,25,41,32,23};
//vector<int> cand={48,22,49,24,26,47,33,40,37,39,31};
//auto ans=sol.combinationSum(cand,2);
auto ans=sol.combinationSum(cand,69);
DLOG(ans);
//DLOG(sol.genPermRep(2));
//DLOG(sol.genPermRep(cand));
DLOG(cntSort);
DLOG(cntPushPop);
////////////////////////////////////////////////
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
}
#endif
<file_sep>/cpp/exe_TSP/gen_data/run.sh
/usr/bin/tclsh gen_tsp.tcl > data.dat
gnuplot r.scr
evince data_p.ps
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/4.6.h
#include <stdio.h>
#include <iostream>
#include "lib.h"
int f4_6 () ;
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/src/f13_3.cpp
#include "include.top.h"
#define GET_VALUE(x) (x)
#define TRUE a
#ifdef TRUE
#undef TRUE
#define TRUE 1
#else
#define TRUE 1
#endif
#define TRUE 0
#if TRUE
#define FALSE 0
#else
#define FALSE 1
#endif
#define SQUARE_VOLUME(a) (a*a*a)
void f13_3() {
cout<<YES<<endl;
PRINT_DEBUG_INFO();
cout<<"MACRO TRUE="<<GET_VALUE(TRUE)<<endl;
cout<<"MACRO FALSE="<<GET_VALUE(FALSE)<<endl;
int a=3;
for (a=1;a<=10000;a++) {
cout<<"SQUARE_VOLUME("<<a<<")="<<SQUARE_VOLUME(a)<<endl;
if(SQUARE_VOLUME(a)<0) {break;}
}
#line 3000
PRINT_DEBUG_INFO();
//cout<<"DEBUG: " <<__FILE__<<":" <<__LINE__<<" compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<endl;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/3.4.h
int main3_4 () ;
<file_sep>/cpp/POJ/src/poj2109.cpp
#include "include.top.h"
//#include "gnuplot_i.h"
#include "poj2109.h"
#include "bigInt.h"
#include <math.h>
#include <iomanip>
#include <map>
#include <fstream>
using namespace std;
//typedef BigInt::Rossi R;
#define SHOW_BIG_INT(x) cout << #x << " : Hex Value = " << x.toStr0xHex() << ", Hex Digits = " << x.getActualHexDigits() << "; Dec Value = " << x.toStrDec() << ", Dec Digits = " << x.getActualDecDigits() << std::endl << std::endl
#define SHOW_DOUBLE(x) cout << #x << " : " << std::fixed << x << std::endl << std::endl
#define PRINTVAR_BIG(a) cout<<#a<<"\t=\t"<<a.toStrDec()<<endl;
void poj2109 ()
{
cout<<"-----------------------------------------------"<<endl;
cout<<"poj2109"<<endl;
//----------------------------------------------------------
string filename="input/poj2109.in";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
string filename_out="output/poj2109.out";
// clean the file "output/poj2109.out"
std::ofstream outfile_init(filename_out);
outfile_init.close();
std::ofstream outfile(filename_out,ios::app);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
//----------------------------------------------------------
std::cout << "parsing " << filename << " ...\n";
std::ostream& o_stream=std::cout;
SET_START_TEST_NAME(o_stream);
string line;
int N;
string pstr;
R p("4357186184021382204544", BigInt::DEC_DIGIT);
while(infile >> N >> pstr)
{
cout<<"LINE-------"<<endl;
PRINTVAR(N);
PRINTVAR(pstr);
p=R(pstr,BigInt::DEC_DIGIT);
//SHOW_BIG_INT(p);
PRINTVAR(p);
R p_down_limit=R("1",BigInt::DEC_DIGIT);
R p_up_limit =R::pow(R("10",BigInt::DEC_DIGIT),R(101));
if(N<1 || N>200 || p<p_down_limit || p>p_up_limit)
{
cout<<"Error: illegal inputs: "<<endl;
PRINTVAR(N);
PRINTVAR(p);
break;
}
R ans=R(0);
auto r=solve_root(ans,p,N,R(1),pow(10,9));
PRINTVAR(ans);
if (r!=0)
break;
}
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
//----------------------------------------------------------
// dump output file
outfile<<"====================="<<endl;
//----------------------------------------------------------
std::cout << "FINISH " << " \n";
cout<<"-----------------------------------------------"<<endl;
outfile.close();
}
//--------------------------------------
// DEF
int solve_root(R &ans, R p,int N,R k1,R k2)
{
#if 1
//PRINT_DEBUG_INFO();
//PRINTVAR(p);
R k_mid;
int is_bigger; // -1:smaller;0=get answer;1=bigger
if(k1==R(0) && k2==R(0))
{
k2=R(1);
R t=R(0);
while(t<pow(10,5))
{
k2++;
t=pow(k2,N);
}
cout<<"GOT k2="<<k2<<endl;
}
k_mid=((k1+k2)/R(2));
//PRINTVAR_hor(k1);
//PRINTVAR_hor(k2);
//PRINTVAR_hor(k_mid);
//cout<<endl;
R bound1=pow(k1,N);
R bound2=pow(k2,N);
//PRINTVAR(bound1);
//PRINTVAR(bound2);
if(bound1>p && bound2>p)
return 1;
if(bound1<p && bound2<p)
return -1;
R bound_mid=pow(k_mid,N);
//PRINTVAR(bound_mid);
if(bound_mid>p)
{
//cout<<"go smaller"<<endl;
return solve_root(ans,p,N,k1,k_mid);
}
else if(bound_mid<p)
{
//cout<<"go larger"<<endl;
return solve_root(ans,p,N,k_mid,k2);
}
else
{
//cout<<"SOLVED!"<<endl;
ans=k_mid;
return 0;
}
#endif
}
R pow(int k , int n)
{
return R::pow(R(k),R(n));
}
R pow(R k , int n)
{
return R::pow(k,R(n));
}
R pow(int k , R n)
{
return R::pow(R(k),n);
}
<file_sep>/tcl/bdd/dot2path_rpt/run.sh
#!/bin/bash
echo "----------------------------"
echo "START EXE dot2path run.sh "
echo "----------------------------"
ls log && rm -rf log
ls output && rm -rf output
ls log || mkdir log
ls output || mkdir output
for d in `ls *.dot`
do
log=./log/dot2path.$d.log
echo "----------------------------"
echo "DOT TO PATH"
echo "perl dot2path.pl $d > $log ..."
echo "----------------------------"
perl dot2path.pl $d > $log
done
for dot in `ls ./output/*.dot`
do
echo "----------------------------"
echo "OUTPUT PATH DOT TO SVG"
echo "dot -Tsvg -o $dot.svg $dot ..."
echo "----------------------------"
dot -Tsvg -o $dot.svg $dot
done
<file_sep>/cpp/leetcode/combinational_sum/s2.cpp
#include <stdio.h>
#include <stdlib.h>
void gen(int numbers)
{
int temp;
int a[numbers], upto = numbers+1, temp2;
for( temp2 = 1 ; temp2 <= numbers; temp2++){
a[temp2]=1;
}
a[numbers]=0;
temp=numbers;
while(1){
if(a[temp]==upto-1){
temp--;
if(temp==0)
break;
}
else{
a[temp]++;
while(temp<numbers){
temp++;
a[temp]=1;
}
printf("(");
for( temp2 = 1 ; temp2 <= numbers; temp2++){
printf("%d", a[temp2]-1);
}
printf(")\n");
}
}
}
int main(){
gen(1);
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/5.6.cpp
#include <iostream>
#include "5.6.h"
using namespace std;
void f5_6() {
for (int ni=0; ni<10;ni++) {
cout<<"===================="<<endl;
for (int xi=0;xi<5;xi++) {
double n=(double)ni;
double x=(double)xi;
cout<<"POLY("<<ni<<","<<xi<<") ="<<poly(n,x)<<endl;
}
}
}
double poly(double n, double x) {
if(n==0) {
return 1.0;
} else if(n==1) {
return x;
} else {
return ((2*n-1)*x*poly(n-1,x)-(n-1)*poly(n-2,x))/n;
}
}
<file_sep>/cpp/7_EXEs_separated/exe_get_run_dir/s.cpp
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <glob.h>
using namespace std;
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_MAP(a) std::cout<<#a<<":"<<std::endl;for(auto u:a) {std::cout<<u.first<<"\t->\t"<<u.second<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_POINTER1(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER2(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<"\t->\t"<<**a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER3(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<"\t->\t"<<**a; \
std::cout<<"\t->\t"<<***a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER(a) PRINT_POINTER1(a)
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//inline std::vector<std::string> glob(const std::string& pat);
#include <stdio.h> /* defines FILENAME_MAX */
// #define WINDOWS /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
#include<iostream>
std::string GetCurrentWorkingDir( void ) {
char buff[FILENAME_MAX];
GetCurrentDir( buff, FILENAME_MAX );
std::string current_working_dir(buff);
return current_working_dir;
}
int main(){
std::cout <<"CWD = "<< GetCurrentWorkingDir() << std::endl;
return 1;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/Node.h
struct Node {
int a;
Node*next;
};
//class Node{
// public:
// Node(int v, Node* n);
// void setA(int v);
// void setNext(Node* n);
// int getA();
// Node*getNext();
// private:
// int a;
// Node* next;
//};
<file_sep>/cpp/sort_algorithms/include/lib.h
#ifndef LIB_CPP
#define LIB_CPP
#include <math.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <algorithm>
double myfac (int n) ;
double calc_sum_of_power (int n,int power=3) ;
bool is_tulip (int n, int power=3) ;
bool is_prime (int n, int print=0) ;
bool is_full_num (int n, int print=0) ;
double calc_use_do (double x, double stop=1e-8) ;
bool is_int (double v) ;
//double integral(double from,double to);
bool item_is_in_array (int i,int a[] ,int a_length) ;
void show_array(double a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void show_array(int a[],int size,bool in_a_line=true,int num_of_marker=0, int marker[]=0) ;
void sort_bubble(int return_list[],double a [],int size) ;
int* gen_rand_array_int (int from,int to,int seed_incr) ;
int* gen_rand_array_int (int from,int to) ;
std::string int2string(int n);
#endif
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/8.9.h
void f8_9();
<file_sep>/cpp/6_EXEs/include/sort_insert.h
void sort_insert_wrp ();
void sort_insert (vector<int> &);
bool sanity_check(vector<int> &a,vector<int> &a_bk);
void sort_insert2 (vector<int> &arr);
void swap(int& a,int& b);
void swap(int* a,int* b);
<file_sep>/cpp/codewar/k_primes/back.cpp
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <regex>
#include <assert.h>
#include <math.h>
using namespace std;
class KPrimes
{
public:
static std::vector<long long> countKprimes(int k, long long start, long long end);
static int puzzle(int s);
static bool isPrime(int n);
static void getAllFactors(int n,vector<int>& v );
static vector<int> vprime;
static map<int,vector<int>>* pmap_n_all_fac;
};
vector<int> KPrimes::vprime={};
map<int,vector<int>>* KPrimes::pmap_n_all_fac=new map<int,vector<int>>;
std::vector<long long> KPrimes::countKprimes(int k, long long start, long long end)
{
//auto map_n_all_fac=*pmap_n_all_fac;
auto ans=new std::vector<long long> ;
for(int i=start;i<=end;i++)
{
if(i==1)
continue;
std::vector<int> v;
int count=pmap_n_all_fac->count(i);
if(count==0)
{
getAllFactors(i,v);
(*pmap_n_all_fac)[i]=v;
}
else
{
v=(*pmap_n_all_fac)[i];
}
long long tobe=1;
int size=v.size();
if(size>k)
continue;
else if(v.size()==1)
tobe=pow(v[0],k);
else if(v.size()<k) // <k and !=1
continue;
else
{
for(auto n:v)
{
tobe*=n;
}
}
if(tobe==i)
ans->push_back(i);
}
return *ans;
}
int KPrimes::puzzle(int s)
{
vector<long long > v1=countKprimes(1,0,s);
vector<long long > v3=countKprimes(3,0,s);
vector<long long > v7=countKprimes(7,0,s);
int cnt=0;
for(auto i1:v1)
for(auto i3:v3)
for(auto i7:v7)
if(i1+i3+i7==s)
{
cnt++;
}
return cnt;
}
bool KPrimes::isPrime(int n)
{
auto result=find(vprime.begin(),vprime.end(),n);
if(result!=vprime.end())
{
return true;
}
for(int i=2;i<(int)sqrt(n)+1;i++)
{
if((int)((double)n/i)==(double)((double)n/i))
return false;
}
vprime.push_back(n);
return true;
}
void KPrimes::getAllFactors(int n,vector<int>& v )
{
if(n<=1)
return;
if(isPrime(n))
v.push_back(n);
for(int i=2;i<n;i++)
{
if(
(int)((double)n/i)==(double)((double)n/i)
&& isPrime(i)
)
{
v.push_back(i);
getAllFactors(n/i,v);
break;
}
}
return;
}
<file_sep>/cpp/5_BOOK_CPP_PRIMER/include/exe_3.16.h
void exe_3_16();
<file_sep>/cpp/codewar/Weird_prime_generator/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define SIMPLE_LOG
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#if(SIMPLE_LOG)
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#define PRINT_COUT(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {::std::cout<<u<<":\t"<<*a+u<<::std::endl;}
#define PRINTVAR(a) ::std::cout<<#a<<"\t=\t"<<a<<"\t@["<<__LINE__<<"]:["<<__FUNCTION__<<"]\t@\tFUNC="<<__PRETTY_FUNCTION__<<"\t@"<<__FILE__<<":"<<__LINE__<<::std::endl;
#define PRINTVAR_hor(a) ::std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_MAP_TMP(a) std::cout<<"PRINT_MAP_TMP: "<<#a<<std::endl;for(auto it=a.begin();it!=a.end();++it) { std::cout<<it->first<<"->"; for(auto i:it->second) { std::cout<<"\t"<<i<<endl; } }
#define MEM_B(x) (*((byte*)(x)))
#define MEM_W(x) (*((WORD*)(x)))
#if 0
#define PRINT_DEBUG_INFO() \
(::std::cout<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"\tzjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#endif
#define PRINT_DEBUG_INFO() \
(::std::cout<<"zjc debug: " \
<<":\tFUNC="<<__PRETTY_FUNCTION__ \
<<":\tLINE=" <<__LINE__ \
<<":\tFILE=" <<__FILE__ \
<<":\tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"\tzjc debug: " \
<<":\tFUNC="<<__PRETTY_FUNCTION__ \
<<":\tLINE=" <<__LINE__ \
<<":\tFILE=" <<__FILE__ \
<<":\tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
using namespace std;
class WeirdPrimeGen
{
public:
static long long countOnes(long long n);
static long long maxPn(long long n);
static int anOverAverage(long long n);
static long long gcd(long long a,long long b);
static vector<long long>* an(long long n);
static vector<long long>* gn(long long n);
//static vector<long long>* pn(long long n);
static vector<long long>* anOver(long long n);
};
long long WeirdPrimeGen::gcd(long long a, long long b){ return a == 0 ? b : gcd(b % a, a); }
vector<long long>* WeirdPrimeGen::an(long long n)
{
if(n==1)
{
auto r=new vector<long long>();;
r->push_back(7);
return r;
}
else
{
auto r=an(n-1);
auto anm1=r->back();
auto new_item=anm1+gcd(n,anm1);
r->push_back(new_item);
PRINTVAR(new_item);
PRINT_VECTOR_hor((*r));
return r;
}
};
vector<long long>* WeirdPrimeGen::gn(long long n)
{
auto r=new vector<long long>();
for(int i=0;i<n;i++)
r->push_back(1);
auto anv=*(an(n));
PRINT_VECTOR_hor(anv);
auto it=r->begin();
it++;
for(int i=0;i<n;i++)
{
*it=anv[i+1]-anv[i];
it++;
}
PRINT_VECTOR_hor((*r));
return r;
};
long long WeirdPrimeGen::countOnes(long long n)
{
long long cntr=0;
auto p=gn(n);
for(auto it=p->begin();it!=p->end();it++)
if(*it==1)
cntr++;
return cntr;
};
long long WeirdPrimeGen::maxPn(long long n)
{
auto gnsize=n;
vector<long long>* g;
while(1)
{
g=gn(gnsize);
if(gnsize-countOnes(gnsize)>=n)
break;
gnsize*=2;
PRINTVAR(gnsize-countOnes(gnsize)-n);
}
PRINTVAR(gnsize-countOnes(gnsize)-n);
PRINTVAR(gnsize);
PRINTVAR(n);
long long maxV=0;
auto p=g;
int p_item_cntr=0;
for(auto it=p->begin();it!=p->end();it++)
{
if(*it!=1)
p_item_cntr++;
if(p_item_cntr>n)
break;
if(*it>maxV)
maxV=*it;
}
return maxV;
};
int WeirdPrimeGen::anOverAverage(long long n)
{
auto gnsize=n;
while(1)
{
auto g=gn(gnsize);
if(gnsize-countOnes(gnsize)==n)
break;
gnsize++;
}
long long maxV=0;
auto p=gn(gnsize);
long long cntr=0;
for(auto it=p->begin();it!=p->end();it++)
{
if(*it!=1)
{
//float anOver=*it/cntr;
float anOver=2/3;
PRINTVAR_hor((*it));
PRINTVAR_hor(cntr);
PRINTVAR(anOver);
}
cntr++;
}
return maxV;
};
int main ()
{
WeirdPrimeGen::gn(10);
WeirdPrimeGen::maxPn(10);
//WeirdPrimeGen::anOverAverage(20);
return 0;
}
<file_sep>/cpp/5_BOOK_CPP_PRIMER/src/exe_2.3.1.cpp
#include "include.top.h"
using namespace std; // you'd better not use using command in header files.
void exe_2_3_1() {
PRINT_DEBUG_INFO();
cout<<"------------------------"<<endl;
int ival=1.01;
//int&rval1=1.01;
int& rval2=ival;
//int&rval3;
cout<<"------------------------"<<endl;
int i=7,&r1=i;
double d=0.1,&r2=d;
r2=3.14;
PRINTVAR(r2);
r2=r1;
PRINTVAR(r2);
r2=4.15;
i=r2;
PRINTVAR(i);
r1=d;
PRINTVAR(r1);
}
<file_sep>/cpp/exe_game/tetris/global.h
#ifndef GLOBAL_H
#define GLOBAL_H
//------------------------------
#define CATCH_CONFIG_MAIN
#ifdef CATCH_CONFIG_MAIN
#define UNIT_TEST
#endif
//#include "catch.hpp"
//------------------------------
#include <stdio.h>
#include <sys/select.h>
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <iostream>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include "lib.h"
////////////////////////////////
#define DEBUG 1
#if DEBUG
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#else
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_ARRAY(a,len)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#endif
////////////////////////////////
//#define UNIT_TEST
////////////////////////////////
#endif
<file_sep>/cpp/exe_game/tetris/Control.class.h
#ifndef CONTROL_CLASS_H
#define CONTROL_CLASS_H
#include "global.h"
using namespace std;
class Control
{
public:
#ifdef UNIT_TEST
void run(){
while(true){
char ch;
cout<<"ch (q to break)=";
ch=getch();
cout<<ch<<""<<endl;
if(ch=='q')
break;
if(ch=='r')
{
cout<<"REFRESH!"<<""<<endl;
// call
}
}
};
/*
void run(){
// init
// loop
while(true){
char ch;
cout<<"ch (q to break)=";
ch=getch();
cout<<ch<<""<<endl;
if(ch=='q')
break;
if(ch=='r')
{
cout<<"REFRESH!"<<""<<endl;
// call
}
}
};
*/;
#else
void run(){
};
#endif
int getch(void) {
fcntl( 0, F_SETFL, O_NONBLOCK); // make it non-blocking
struct termios tm, tm_old;
int fd = STDIN_FILENO, c;
if(tcgetattr(fd, &tm) < 0)
return -1;
tm_old = tm;
cfmakeraw(&tm);
if(tcsetattr(fd, TCSANOW, &tm) < 0)
return -1;
c = fgetc(stdin);
if(tcsetattr(fd, TCSANOW, &tm_old) < 0)
return -1;
return c;
}
Matrix* mat;
Display* display;
private:
int T; // ms
};
#endif
<file_sep>/cpp/game/three_pig/threePig.cpp
//#define SIMPLE_LOG
#ifdef SIMPLE_LOG
#define DBG 0
#else
#define DBG 1
#endif
#if (DBG)
#define DLOG(x) cout<<#x<<"="<<x<<" @"<<__LINE__<<endl;
#else
#define DLOG(x)
#endif
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#if (DBG)
#define DENTER \
LVCALL++; PRLVCALL; ::std::cout<<"-->"<<__FUNCTION__<<::std::endl;
#define DRETURN \
PRLVCALL; ::std::cout<<"<--"<<__FUNCTION__<<::std::endl; LVCALL--;
#endif
#define DEBUG_MARK PRINT_DEBUG_INFO()
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define DPRINT(x) \
(::std::cout<<x<<::std::endl )
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define DEBUG_MARK
#define PRINT_DEBUG_INFO_PREFIX(p)
#define DPRINT(x)
#define PRINT_COUT(p)
#define DENTER
#define DRETURN
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <regex>
#include <map>
#include <assert.h>
using namespace std;
#if DBG
static int LV=0;
static int LVCALL=0;
#define PRLV for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLVCALL for(int u12=LVCALL;u12>0;u12--) {std::cout<<" .. ";}
template <class U>
std::ostream & operator <<(std::ostream &os, const std::vector<U> &m)
{
os << std::endl;
PRLV(LV);
os << "->";
os << std::endl;
LV++;
PRLV(LV);
for (const auto &p : m)
{
os << p << ", " ;
}
os << std::endl;
LV--;
PRLV(LV);
os << "<-";
return os;
}
template <class U, class V>
std::ostream & operator <<(std::ostream &os, const std::map<U, V> &m)
{
os << "->";
os << std::endl;
for (const auto &p : m)
{
os << p.first << ": " << p.second;
os << std::endl;
}
os << "<-";
return os;
}
#endif
//=========================================================================================
#include "character.h"
#include "shape.h"
#include "board.h"
int main()
{
DENTER;
// init
Board b,bk;
bk=b;
b.showBoardShape();
b.show();
// add Character
Character* p1=new Character("P",0,1);
Character* p2=new Character("P",1,1);
Character* p3=new Character("P",2,2);
Character* w=new Character("W",3,3);
b.characterVec.push_back(p1);
b.characterVec.push_back(p2);
b.characterVec.push_back(p3);
b.characterVec.push_back(w);
b.applyChar();
// add Shape
Shape* s1=new Shape();
Shape* s2=new Shape({{0,0},{1,0},{1,1}});
Shape* s3=new Shape({{0,0},{1,0},{2,0},{2,1}});
s1->name="A";
//s2->name="B";
//s3->name="C";
b.shapeVec.push_back(s1);
bool r;
//b.shapeVec.push_back(s2);
//b.shapeVec.push_back(s3);
// r=b.applyShape();
//DLOG(r);
// final show
//s1->print();
//DEBUG_MARK;
//b.showBoardShape();
//b.show();
//DLOG((Point(0,0)==Point(0,1)));
//DLOG((Point(0,0)==Point(0,0)));
//DLOG(((*s1)%(*s2)));
# if 1
for(int i=0;i<b.board.size();i++ )
{
auto v1=b.board[i];
for(int j=0;j<v1.size();j++)
{
string s=v1[j];
DLOG(s);
if(std::regex_match(s, std::regex("^0.*")))
{
continue;
//DPRINT("INVALID:"<<s);
}
//cout<<i<<","<<j<<":"<<s<<"\t";
s1->setLoc(i,j);
#if 1
b.resetShape();
r=b.applyShape();
DLOG(r);
//assert(r);
if(!r)
continue;
s1->print();
DEBUG_MARK;
b.show();
#endif
DEBUG_MARK;
#if 1
s1->r90();
b.resetShape();
r=b.applyShape();
DLOG(r);
DEBUG_MARK;
//assert(r);
if(!r)
continue;
DEBUG_MARK;
s1->print();
DEBUG_MARK;
b.show();
#endif
DEBUG_MARK;
}
cout<<""<<""<<endl;
}
#endif
//s1->setLoc(3,3);
//s1->setLoc(0,1);
//b.resetShape();
//r=b.applyShape();
//DLOG(r);
//assert(r);
//s1->print();
//DEBUG_MARK;
//b.showBoardShape();
//b.show();
DRETURN;
return 1;
}
<file_sep>/cpp/ex3.4/date.cpp
#include <iostream>
#include <math.h>
using namespace std;
class Tdate {
public:
Tdate();
Tdate(int d);
Tdate(int m, int d);
Tdate(int m,int d,int y);
protected:
int month;
int day;
int year;
public:
void show ();
int CalculateJulianDay();
int invCJD(int jd);
};
Tdate::Tdate() {
month=1;
day=1;
year=1900;
}
Tdate::Tdate(int y, int m, int d) {
month=m;
day=d;
year=y;
}
void Tdate::show() {
cout<<"NOW is"<<year<<"-"<<month<<"-"<<day<<endl;
cout<<"JD is"<<CalculateJulianDay()<<endl;
}
//int Tdate::CalculateJulianDay(int year, int month, int day)
int Tdate::CalculateJulianDay()
{
int B = 0;
if(month <= 2)
{
month += 12;
year -= 1;
}
//if(IsGregorianDays(year, month, day))
if(1)
{
B = year / 100;
B = 2 - B + year / 400;
}
double dd = day + 0.5000115740; /*本日12:00后才是儒略日的开始(过一秒钟)*/
return int(365.25 * (year + 4716) + 0.01) + int(30.60001 * (month + 1)) + dd + B - 1524.5;
}
int Tdate::invCJD(int jd){
if (CalculateJulianDay()<jd) {
while (CalculateJulianDay()<jd) { year++;}
year--;
while (CalculateJulianDay()<jd) { month++;}
month--;
while (CalculateJulianDay()<jd) { day++;}
day--;
}
if (CalculateJulianDay()>jd) {
while (CalculateJulianDay()>jd) { year--;show();}
year++;
while (CalculateJulianDay()>jd) { month--;}
month++;
while (CalculateJulianDay()>jd) { day--;}
day++;
}
return 1;
}
int main () {
//Tdate aday;
//int gre=aday.CalculateJulianDay();
Tdate bday(1996,1,1);
bday.show();
//cout <<bday.CalculateJulianDay()<<endl;
bday.invCJD(2443230);
cout <<"finished"<<endl;
bday.show();
}
<file_sep>/cpp/POJ/include/poj1002.h
void poj1002 () ;
<file_sep>/cpp/leetcode/sort_list/s.cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#define SIMPLE_LOG 1
#define LNX 1
//#define DBG 0
#if (SIMPLE_LOG)
#define DLOG(x)
#else
#define DLOG(x) cout<<#x<<"="<<x<<" @"<<__LINE__<<endl;
#endif
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#if (SIMPLE_LOG)
#define DENTER
#define DRETURN
#else
#define DENTER \
LVCALL++; PRLVCALL; ::std::cout<<"-->"<<__FUNCTION__<<":LINE="<<__LINE__<<::std::endl;
#define DRETURN \
PRLVCALL; ::std::cout<<"<--"<<__FUNCTION__<<::std::endl; LVCALL--;
#endif
#define DEBUG_MARK PRINT_DEBUG_INFO()
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define DPRINT(x) \
(::std::cout<<x<<::std::endl )
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#if SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define DEBUG_MARK
#define PRINT_DEBUG_INFO_PREFIX(p)
#define DPRINT(x)
#define PRINT_COUT(p)
#define DENTER
#define DRETURN
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <regex>
#include <map>
#include <assert.h>
#include<string>
#include <algorithm>
#include <vector>
#include <iostream>
#include <sstream>
#include <stdlib.h> /* srand, rand */
using namespace std;
#if (SIMPLE_LOG)
#else
static int LV=0;
static int LVCALL=0;
#define PRLV for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLVCALL for(int u12=LVCALL;u12>0;u12--) {std::cout<<" .. ";}
#endif
#if LNX
struct ListNode
{
int val;
ListNode *next;
ListNode (int x):val (x), next (0)
{}
ListNode (int x,ListNode* n):val (x), next (n)
{
}
};
#endif
class Solution
{
public:
int getLen (ListNode * head)
{
int r = 0;
while (head)
{
r++;
head = head->next;
}
return r;
}
ListNode *getIthItem (ListNode * head, int i)
{
int r = 0;
while (head)
{
if (r == i)
return head;
r++;
head = head->next;
}
return 0;
}
void show (ListNode * head, bool withAddr=0)
{
#if SIMPLE_LOG
return;
#endif
DENTER;
vector<ListNode*> record;
while (head)
{
cout << head->val ;
if(withAddr)
cout <<"[@"<< head<<"]" ;
if(find(record.begin(),record.end(),head)!=record.end())
{
cout<<"Warning: GOT LOOP!"<<endl;
break;
}
record.push_back(head);
cout<< "\t";
head = head->next;
}
cout << endl;
DRETURN;
}
void swap (int& a,int& b)
{
DPRINT("swap:"<<a<<","<<b);
int tmp=a;
a=b;
b=tmp;
}
void swap (ListNode *& head, int i, int j)
{
if (i > j)
return swap (head, j, i);
if(i==j)
return;
auto n1 = getIthItem (head, i);
auto n2 = getIthItem (head, j);
auto n2pre = getIthItem (head, j - 1);
//pre
if(i!=0)
{
auto n1pre = getIthItem (head, i - 1);
// swap
auto tmp=n1pre->next; n1pre->next=n2pre->next; n2pre->next=tmp;
}
else
{ // swap
auto tmp=head; head= n2pre->next; n2pre->next=tmp;
}
//next
auto tmp=n1->next;
n1->next=n2->next;
n2->next=tmp;
}
ListNode *sortList (ListNode * head)
{
if (head == 0)
return 0;
auto newhead=head;
mergeSort(newhead,0,getLen(head)-1);
bubbleSort(newhead,0,0);
DLOG(newhead);
return newhead;
}
void mergeSort(ListNode*&head,int from,int to)
{
DENTER;
DLOG(from);
DLOG(to);
if(from==to)
return;
if(to-from<=40)
{
bubbleSort(head,from,to);
return;
}
if(to-from==1)
{
auto pFrom=getIthItem(head,from);
auto pTo=pFrom->next;
if(pFrom->val>pTo->val)
swap(pFrom->val,pTo->val);
DRETURN;
return;
}
int mid=(from+to)/2;
mergeSort(head,from,mid);
mergeSort(head,mid+1,to);
merge(head,from,mid+1,to+1);
DLOG(head);
DRETURN;
}
void merge(ListNode*&head,int from,int mid,int to)
{
DENTER;
vector<int> inp={from,mid,to};
PRINT_VECTOR_hor(inp);
//show(head,1);
ListNode* n1=getIthItem(head,from);
ListNode* n2=getIthItem(head,mid);
ListNode* NFROM=n1;
ListNode* NMID=n2;
ListNode* NTO=getIthItem(head,to);
ListNode* NPRE=0;
if(from==0)
{
NPRE=new ListNode(-999);
NPRE->next=NFROM;
}
else
NPRE=getIthItem(head,from-1);
//DLOG(NPRE);
//DLOG(NFROM);
//DLOG(NMID);
//DLOG(NTO);
ListNode* nNew=NPRE;
//DLOG(n1);
//DLOG(n2);
//DLOG(nNew);
while(n1!=NMID && n2!=NTO)
{
//DPRINT("------------------------->");
if(n1->val<=n2->val)
{
//DPRINT("n1val="<<n1->val<<" <=n2val="<<n2->val);
DPRINT("ADD:"<<n1->val);
DPRINT(nNew<<"->"<<n1);
nNew->next=n1;
n1=n1->next;
nNew=nNew->next;
}
else
{
//DPRINT("n1val="<<n1->val<<" >n2val="<<n2->val);
DPRINT("ADD:"<<n2->val);
DPRINT(nNew<<"->"<<n2);
nNew->next=n2;
n2=n2->next;
nNew=nNew->next;
}
//DLOG(n1);
//DLOG(n2);
//DLOG(nNew);
//DPRINT("<-------------------------");
}
//DLOG((n1!=NMID));
if(n1!=NMID)
{
nNew->next=n1;
DPRINT(nNew<<"->"<<n1);
//NMID->next=NTO;
//DPRINT(NMID<<"->"<<NTO);
while(nNew->next!=NMID)
nNew=nNew->next;
nNew->next=NTO;
DPRINT(nNew<<"->"<<NTO);
}
//DLOG((n2!=NTO));
if(n2!=NTO)
{
nNew->next=n2;
DPRINT(nNew<<"->"<<n2);
}
//NPRE->next=NFROM;
if(from==0)
head=NPRE->next;
//show(head,1);
DRETURN;
}
int qSort (ListNode *& head,int from,int to)
{
ListNode* pivot=head;
ListNode* g1=head;
ListNode* g2=head;
// LI:
// (head,g1] is smaller
// (g1,g2] is larger
while(g2->next)
{
g2=g2->next;
if(g2->val<pivot->val)
{
g1=g1->next;
}
}
return 0;
}
ListNode* bubbleSort(ListNode*& head,int from,int to)
{
DENTER;
auto fromPtr=getIthItem(head,from);
auto toPtr=getIthItem(head,to);
toPtr=toPtr->next;
ListNode* p1=fromPtr ;
bool flag_swap=1;
while(flag_swap)
{
flag_swap=0;
DLOG(p1);
ListNode* p2=p1;
while(p2!=toPtr && p2->next!=toPtr)
{
DLOG(p2);
if(p2->next->val<p2->val)
{
swap(p2->next->val,p2->val);
flag_swap=1;
}
p2=p2->next;
show(head);
}
}
DRETURN;
return head;
}
};
#if LNX
vector<int> genRandVec(int len)
{
vector<int> r;
while(len>0)
{
srand (time(NULL)+len);
/* generate secret number between 1 and 10: */
int randi=rand();
int i = randi % len;
r.push_back(i);
len--;
}
return r;
}
ListNode* vecToListNode( vector<int> list)
{
// Generate list from the input
// Now convert that list into linked list
ListNode* dummyRoot = new ListNode(0);
ListNode* ptr = dummyRoot;
for(int item : list) {
ptr->next = new ListNode(item);
ptr = ptr->next;
}
ptr = dummyRoot->next;
delete dummyRoot;
return ptr;
}
int main ()
{
// ListNode *head = new ListNode(0);
//ListNode *head = vecToListNode({0,1,2,3,4,5,6});
//ListNode *head = vecToListNode({3,2,5,1,4,6,0,55,66,34,23,13,53,1,32});
// 0 1 2 3 4 5 6
//ListNode *head = vecToListNode({1,3,3, 1,1,3,2,2,1});
//ListNode *head = vecToListNode({10,3,2,4,5,6,8});
// 0 1 2 3 4 5 6
ListNode *head = vecToListNode(genRandVec(150000));
DEBUG_MARK;
Solution().show(head,1);
DLOG(head);
//Solution().merge(head,0,2,5);
#if 1
auto ans=Solution().sortList(head);
DEBUG_MARK;
DLOG(ans);
Solution().show(ans,1);
#endif
//ListNode *ret = Solution ().sortList (head);
//DEBUG_MARK;
//Solution().show(ret,1);
return 0;
}
#endif
<file_sep>/cpp/exe_game/tetris/TetrisCalc.class.h
//--------------------------------------
// include lib files
//--------------------------------------
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
using namespace std;
class TetrisCalc {
public:
TetrisCalc(){
};
~TetrisCalc(){
};
void init() {};
private:
int WIDTH;
int HEIGHT;
};
<file_sep>/cpp/POJ_separated/1001/poj.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#define SIMPLE_LOG
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#define PRINT_COUT(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
#include <math.h>
#include <iomanip>
#include <map>
#include <fstream>
using namespace std;
int main ()
{
PRINT_DEBUG_INFO();
//----------------------------------------------------------
string filename="input.txt";
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
//----------------------------------------------------------
double a, b;
double result;
while (true)
{
int CNT=2;
if(!(infile >> a >> b))
break;
PRINTVAR(a);
PRINTVAR(b);
//result=pow(a,b);
//cout<<a<<"\t^\t"<<b<<"\t=\t"<<setprecision(3000)<<result<<setprecision(10)<<endl;
//cout<<setprecision(3000)<<result<<setprecision(10)<<endl;
}
cout<<"-----------------------------------------------"<<endl;
return 0;
}
<file_sep>/cpp/game/three_pig/board.h
#include "character.h"
#include "shape.h"
class Board:public ShapeBase
{
public:
// MEMBER
vector<Character*> characterVec;
vector<Shape*> shapeVec;
vector<vector<string>> boardShape;
// METHOD
Board ()
{
DENTER;
board={
{"0","1","1","0"},
{"1","1","1","1"},
{"1","1","1","1"},
{"0","1","1","1"},
};
boardShape={
{"","","",""},
{"","","",""},
{"","","",""},
{"","","",""},
};
DLOG(board.size());
DRETURN;
};
//Board& operator=(Board& other)
//{
//}
void applyChar()
{
for(auto oneChar:characterVec )
{
auto loc=oneChar->getLoc();
if(board[loc.x][loc.y]!="1")
{
DPRINT("ERROR, illegal char loc:"<<loc.x<<","<<loc.y);
}
board[loc.x][loc.y]=oneChar->getType();
}
}
void resetShape()
{
boardShape={
{"","","",""},
{"","","",""},
{"","","",""},
{"","","",""},
};
}
bool applyShape()
{
for(auto oneShape:shapeVec )
{
bool r=oneShape->apply(boardShape,board);
if(!r)
return 0;
//if(board[loc.x][loc.y]!="1")
//{
// DPRINT("ERROR, illegal char loc:"<<loc.x<<","<<loc.y);
//}
//board[loc.x][loc.y]=oneChar->getType();
}
return 1;
}
void show() {
DEBUG_MARK;
DPRINT("-------------------------------");
int ii=0,jj=0;
for(auto v1:board)
{
jj=0;
for(auto i:v1)
{
cout<<""<<i;
if(i=="")
cout<<"_";
//DLOG(ii);
//DLOG(jj);
//DLOG(boardShape.size());
//DLOG(boardShape[ii].size());
if(boardShape.size()>ii && boardShape[ii].size()>jj )
{
//DPRINT("use boardShape:"<<ii<<","<<jj);
cout<<boardShape[ii][jj];
}
cout<<"\t";
jj++;
}
cout<<""<<""<<endl;
ii++;
}
DPRINT("-------------------------------");
}
void showBoardShape() {
DEBUG_MARK;
DPRINT("-------------------------------");
for(auto v1:boardShape )
{
for(auto i:v1)
{
cout<<""<<i;
if(i=="")
cout<<"_";
cout<<"\t";
}
cout<<""<<""<<endl;
}
DPRINT("-------------------------------");
}
};
<file_sep>/cpp/5_BOOK_CPP_PRIMER/src/exe_3.22.cpp
#include <vector>
#include "include.top.h"
using namespace std;
using std::string;
using std::vector;
void f_3_22() {
cout<<"==============="<<endl;
cout<<"exe_3_22:"<<""<<endl;
cout<<"==============="<<endl;
string s("this is a string!");
PRINTVAR(s);
for (auto &c:s)
{
if(isspace(c))
{
break;
}
c=toupper(c);
}
PRINTVAR(s);
cout<<"==============="<<endl;
cout<<"exe_3_23:"<<""<<endl;
cout<<"==============="<<endl;
vector<int> vi(10,0);
int cnt=0;
for (auto& i:vi)
{
i=cnt;
cnt++;
}
print_vector(vi);
for (auto& i:vi)
{
i*=2;
}
print_vector(vi);
cout<<"==============="<<endl;
cout<<"exe_3_25:"<<""<<endl;
cout<<"==============="<<endl;
vector<int> score{11,22,33,44,51,4,23,99,100,66,77,88,67,23,1,0};
vector<int> stat(11,0);
print_vector(score);
auto it_sum=stat.begin();
for(auto it=score.begin();it!=score.end();it++)
{
int step=*it;
step=step/10;
PRINTVAR(step);
auto target=it_sum+step;
*target+=1;
}
print_vector(stat);
}
<file_sep>/cpp/leetcode/trapping_rain_water/s.cpp
#define SIMPLE_LOG 0
#define LNX 1
#if (!SIMPLE_LOG)
#define DLOG(x) cout<<#x<<"="<<x<<" @"<<__LINE__<<endl;
#define DLOG1(x) cout<<#x<<"="<<x<<"\t";
#else
#define DLOG(x)
#define DLOG1(x)
#endif
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#if (!SIMPLE_LOG)
#define DENTER \
LVCALL++; PRLVCALL; ::std::cout<<"-->"<<__FUNCTION__<<::std::endl;
#define DRETURN \
PRLVCALL; ::std::cout<<"<--"<<__FUNCTION__<<"@" <<__LINE__<<::std::endl; LVCALL--;
#endif
#define DEBUG_MARK PRINT_DEBUG_INFO()
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define DPRINT(x) \
(::std::cout<<x<<::std::endl )
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#if SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define DEBUG_MARK
#define PRINT_DEBUG_INFO_PREFIX(p)
#define DPRINT(x)
#define PRINT_COUT(p)
#define DENTER
#define DRETURN
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <regex>
#include <map>
#include <assert.h>
using namespace std;
#if !SIMPLE_LOG
static int LV=0;
static int LVCALL=-1;
//#define PRLV std::cout<<LV<<"\t"; for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLV for(int u12=LV; u12>0;u12--) {std::cout<<" .. ";}
#define PRLVCALL std::cout<<"L"<<LVCALL<<"\t"; for(int u12=LVCALL;u12>0;u12--) {std::cout<<" .. ";}
template <class U>
std::ostream & operator <<(std::ostream &os, const std::vector<U> &m)
{
if(m.size()==0)
return os;
os << std::endl;
PRLV(LV);
os << "->";
os << std::endl;
LV++;
PRLV(LV);
for (const auto &p : m)
{
os << p << ", " ;
}
os << std::endl;
LV--;
PRLV(LV);
os << "<-";
return os;
}
template <class U, class V>
std::ostream & operator <<(std::ostream &os, const std::map<U, V> &m)
{
os << "->";
os << std::endl;
for (const auto &p : m)
{
os << p.first << ": " << p.second;
os << std::endl;
}
os << "<-";
return os;
}
#endif
//=========================================================================================
class Solution {
public:
template <class T>
T min(T& a,T& b) {
return a>b?b:a;
}
vector<int> search(vector<int>& height, bool left) {// left==1 from left to right
DENTER;
DLOG(left);
vector<int> r;
vector<int> lv;
bool flagIn=0;
int hEdge=-1;
if(!left) // from right to left
{
//int size=height.size();
int curMax=0;
for(int i=height.size()-1;i>=0;i-- )
{
if(height[i]>curMax)
curMax=height[i];
lv.push_back(curMax);
}
std::reverse(lv.begin(),lv.end());
}
else
{
int curMax=0;
for(int i=0;i<height.size();i++ )
{
if(height[i]>curMax)
curMax=height[i];
lv.push_back(curMax);
}
}
DLOG(lv);
DLOG(r);
DRETURN;
return lv;
};
int trap(vector<int>& height) {
DLOG(height);
auto l1=search(height,1);
auto l2=search(height,0);
auto l=l1;
auto depth=l1;
int r=0;
for(int i=0;i<l.size();i++)
{
if(l[i]>l2[i])
l[i]=l2[i];
depth[i]=l[i]-height[i];
r+=depth[i];
}
DLOG(l);
DLOG(depth);
return r;
};
};
#if LNX
int main()
{
clock_t start, end;
start = clock();
////////////////////////////////////////////////
Solution sol;
vector<int> height={2,0,3,0,7,1,5};
height={0,1,0,2,1,0,1,3,2,1,2,1};
//auto ans=sol.combinationSum(height,6);
auto ans=sol.trap(height);
DLOG(ans);
//DLOG(cntSort);
//DLOG(cntPushPop);
////////////////////////////////////////////////
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
}
#endif
#if 0
#endif
<file_sep>/cpp/POJ/include/WFF.class.h
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
static string legalChars="KANCEpqrst";
// WFF=Well-Formed Formula
class WFF
{
public:
WFF() {
WFF("");
};
WFF(string s) {
//cout<<"Construct:"<<s<<"@"<<this<<endl;
mForm=s ;
mOp=' ';
};
~WFF() {
//cout<<"Deconstruct:"<<mForm<<"@"<<this<<endl;
for (WFF* p:mUnitWFFs)
{
delete p;
}
};
string getMForm() {return mForm;};
void setMForm(string s) {mForm=s;};
bool isLegal();
bool isLegal(int level);
void show();
void showMUnitWFFs(int indent=0);
//void breakIntoUnitWFFs();
bool calcValue(string cond) ;
vector<string> genTestPatterns();
private:
string mForm;
char mOp;
vector<WFF*> mUnitWFFs;
};
vector<int> findAllUpperLetterInString(string str);
vector<int> findAllMatchesInString(string str,string subStr);
//static vector<WFF> WFFs;
<file_sep>/cpp/exe_split/use_boost/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t'"<<a<<"'\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"='"<<*u<<"'"<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#define SIMPLE_LOG
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/split.hpp>
using namespace std;
using namespace boost;
int main ()
{
std::string s=" var_name ( + ) ";
PRINTVAR(s);
s=trim_left_copy(s);
s=trim_right_copy(s);
PRINTVAR(s);
typedef vector<string> split_vector_type;
split_vector_type SplitVec;
split(SplitVec,s,is_any_of("()"));
// delete empty string
for(auto it=SplitVec.begin();it!=SplitVec.end();)
{
if(*it=="")
it=SplitVec.erase(it);
else
++it;
}
//
PRINT_VECTOR(SplitVec );
PRINTVAR(SplitVec.size());
for(string& s:SplitVec )
{
s=trim_left_copy(s);
s=trim_right_copy(s);
}
PRINT_VECTOR(SplitVec );
//auto v=split(s,"e");
//
//PRINT_VECTOR(v);
return 0;
}
<file_sep>/cpp/sort_algorithms/src/1_bubble_sort.cpp
#include <stdio.h>
#include <iostream>
//#include <iostream.h>
#include "1_bubble_sort.h"
#include "lib.h"
using namespace std;
int func_1_bubble_sort(int* r_cnt) {//FUNC
return func_1_bubble_sort(r_cnt,10);
}
int func_1_bubble_sort(int*r_cnt,int LENGTH) {//FUNC
return func_1_bubble_sort(r_cnt,LENGTH,0);
}
int func_1_bubble_sort(int*r_cnt,int LENGTH,int seed_incr) {//FUNC
int len=LENGTH;
//double a[]={3,2,1,4,6,-8,100,10};
//double a[]={8,7,6,5,4,3,2,1};
//double a[]={1,2,3,4,5,6,7,8};
int* r=gen_rand_array_int(0,8,seed_incr);
double a[LENGTH];
int* r_bk=r;
for(int i=0;i<=LENGTH;i++) {
a[i]=(double)*r++;
}
r=r_bk;
//cout<<"before, r:"<<endl;
//show_array(r,len,true,0);
cout<<"before:"<<endl;
//int len=sizeof(a)/sizeof(*a);
cout<<"length:"<<len<<endl;
show_array(a,len,true,0);
//int r_list[2];
sort_bubble(r_cnt,a,len);
cout<<"after:"<<endl;
show_array(a,len,true,0);
cout <<"diff_cnt,swap_cnt="<<r_cnt[0]<<","<<r_cnt[1]<<endl;
return 0;
}
<file_sep>/python/workspace_python/Beauty_of_programming/1.1.py
__author__ = 'jc'
while True:
print("ITER")<file_sep>/cpp/codewar/ranking_poker_hands/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#define SIMPLE_LOG
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <regex>
#include <assert.h>
#define WIN Result::Win
#define LOSS Result::Loss
#define TIE Result::Tie
enum class Result { Win, Loss, Tie };
void split(std::string& s, std::string& delim,std::vector< std::string >* ret)
{
size_t last = 0;
size_t index=s.find_first_of(delim,last);
while (index!=std::string::npos)
{
ret->push_back(s.substr(last,index-last));
last=index+1;
index=s.find_first_of(delim,last);
}
if (index-last>0)
{
ret->push_back(s.substr(last,index-last));
}
}
struct PokerHand {
std::vector<std::string> cards;
std::string input;
PokerHand (const char* pokerhand) {
std::cout<<pokerhand<<std::endl;
std::string p=pokerhand;
input=p;
// poker to hex:
p=std::regex_replace(p,std::regex("T"),"a");
p=std::regex_replace(p,std::regex("J"),"b");
p=std::regex_replace(p,std::regex("Q"),"c");
p=std::regex_replace(p,std::regex("K"),"d");
p=std::regex_replace(p,std::regex("A"),"e");
//
//std::cout<<p<<std::endl;
std::string tmp="";
std::string blank=" ";
split(p,blank,&cards);
PRINT_VECTOR_hor(cards);
sort(cards.begin(),cards.end());
PRINT_VECTOR_hor(cards);
};
int getValue(std::string card) const
{
if(card.size()!=2)
{
PRINT_VECTOR_hor(cards);
}
assert(card.size()==2);
char c=card[0];
int r;
if( c>='0'
&& c<='9')
r=c-48;
else if(c=='T') r=10; // joker
else if(c=='J') r=11;
else if(c=='Q') r=12;
else if(c=='K') r=13;
else if(c=='A') r=14;
else if(c=='a') r=10; // hex
else if(c=='b') r=11;
else if(c=='c') r=12;
else if(c=='d') r=13;
else if(c=='e') r=14;
//PRINTVAR(r);
return(r);
};
char getSuit(std::string card) const
{
if(card.size()!=2)
{
PRINTVAR(card);
}
assert(card.size()==2);
char c=card[1];
//PRINTVAR(c);
return c;
}
//int rank;
//1Straight flush** | flushJack of clubs10 of clubs9 of clubs8 of clubs7 of clubs
//2Four of a kind | 5 of clubs5 of diamonds5 of hearts5 of spades2 of diamonds
//3Full house | 6 of spades6 of hearts6 of diamondsKing of clubsKing of hearts
//4HFlush** | 4HFlushJack of diamonds9 of diamonds8 of diamonds4 of diamonds3 of diamonds
//5QueenStraight** | 5QueenStraight10 of diamonds9 of spades8 of hearts7 of diamonds6 of clubs
//6Three of a kind | 5Queen of clubsQueen of spadesQueen of hearts9 of hearts2 of spades
//7Two pair | Jack of heartsJack of spades3 of clubs3 of spades2 of hearts
//8One pair | Jack10 of spades10 of hearts8 of spades7 of hearts4 of clubs
//9High card |
bool theSame(PokerHand other) const
{
for(int i=0;i<5;i++)
{
if(cards[i]!=other.cards[i])
return false;
}
return true;
};
bool theSameValue(PokerHand other) const
{
for(int i=0;i<5;i++)
{
if(getValue(cards[i])!=getValue(other.cards[i]))
return false;
}
return true;
};
int getLargestPairValue() const
{
for(auto it=cards.end()-1;it!=cards.begin()+1;it--)
{
auto card1=*(it-1);
auto card2=*it;
if(getValue(card1)==getValue(card2))
return getValue(card1);
}
return -1;
};
int getLargestPairValue(std::vector<std::string> cc) const
{
for(auto it=cc.end();it!=cc.begin()+1;it--)
{
auto card1=*(it-1);
auto card2=*it;
if(getValue(card1)==getValue(card2))
return getValue(card1);
}
return -1;
};
int getLargestThreeValue() const
{
for(auto it=cards.end()-1;it!=cards.begin()+2;it--)
{
auto card0=*(it-2);
auto card1=*(it-1);
auto card2=*it;
if(
getValue(card0)==getValue(card1) &&
getValue(card1)==getValue(card2)
)
return getValue(card0);
}
return -1;
};
int getLargestFourValue() const
{
for(auto it=cards.end()-1;it!=cards.begin()+3;it--)
{
auto card0=*(it-3);
auto card1=*(it-2);
auto card2=*(it-1);
auto card3=*it;
if(
getValue(card0)==getValue(card1) &&
getValue(card1)==getValue(card2) &&
getValue(card2)==getValue(card3)
)
return getValue(card0);
}
return -1;
};
Result compare (int a,int b) const
{
if(a==b)
return TIE;
else
return (a>b)?WIN:LOSS;
};
Result compare (std::string stra,std::string strb) const
{
int a=getValue(stra);
int b=getValue(strb);
return compare(a,b);
};
Result compareInRank1(PokerHand other) const
{
if(getValue(cards[4])<getValue(other.cards[4]))
return Result::Loss;
if(getValue(cards[4])==getValue(other.cards[4]))
return Result::Tie;
if(getValue(cards[4])>getValue(other.cards[4]))
return Result::Win;
};
Result compareInRank2(PokerHand other) const
{
if(getLargestFourValue()<other.getLargestFourValue())
return Result::Loss;
else if(getLargestFourValue()>other.getLargestFourValue())
return Result::Win;
else
if(getLargestPairValue()<other.getLargestPairValue())
return Result::Loss;
else if(getLargestPairValue()>other.getLargestPairValue())
return Result::Win;
else
return Result::Tie;
};
Result compareInRank3(PokerHand other) const
{
if(theSameValue(other))
return Result::Tie;
if(getLargestThreeValue()==getLargestThreeValue())
return (getLargestPairValue()>getLargestPairValue())?Result::Win:Result::Loss;
else
return (getLargestThreeValue()>getLargestThreeValue())?Result::Win:Result::Loss;
};
Result compareInRank4(PokerHand other) const
{
if(cards[4]==other.cards[4])
if(cards[3]==other.cards[3])
if(cards[2]==other.cards[2])
if(cards[1]==other.cards[1])
if(cards[0]==other.cards[0])
return Result::Tie;
else
return (cards[0]>other.cards[0])?Result::Win:Result::Loss;
else
return (cards[1]>other.cards[1])?Result::Win:Result::Loss;
else
return (cards[2]>other.cards[2])?Result::Win:Result::Loss;
else
return (cards[3]>other.cards[3])?Result::Win:Result::Loss;
else
return (cards[4]>other.cards[4])?Result::Win:Result::Loss;
};
Result compareInRank5(PokerHand other) const
{
return compareInRank1(other);
};
Result compareInRank6(PokerHand other) const
{
if(theSameValue(other))
return Result::Tie;
if(getLargestThreeValue()==other.getLargestThreeValue())
return (getLargestPairValue()>other.getLargestPairValue())?Result::Win:Result::Loss;
else
return (getLargestThreeValue()>other.getLargestThreeValue())?Result::Win:Result::Loss;
};
Result compareInRank7(PokerHand other) const
{
return TIE;
};
Result compareInRank8(PokerHand other) const
{
if(theSameValue(other))
return Result::Tie;
if(getLargestPairValue()==other.getLargestPairValue())
if(compare(cards[4],other.cards[4])!=TIE)
return compare(cards[4],other.cards[4]);
else if(compare(cards[3],other.cards[3])!=TIE)
return compare(cards[3],other.cards[3]);
else if(compare(cards[2],other.cards[2])!=TIE)
return compare(cards[2],other.cards[2]);
else if(compare(cards[1],other.cards[1])!=TIE)
return compare(cards[1],other.cards[1]);
else if(compare(cards[0],other.cards[0])!=TIE)
return compare(cards[0],other.cards[0]);
else
return (getLargestPairValue()>other.getLargestPairValue())?Result::Win:Result::Loss;
};
Result compareInRank9(PokerHand other) const
{
compare(cards[4],other.cards[4]);
};
bool isRank1() const
{
for(auto it=cards.begin()+1;it!=cards.end();it++)
{
auto card1=*(it-1);
auto card2=*it;
if(getSuit(card1)!=getSuit(card2))
return false;
if(getValue(card1)+1!=getValue(card2))
return false;
}
return true;
};
bool isRank2() const
{
auto it=cards.begin();
auto card0=*it;
it++; auto card1=*it;
it++; auto card2=*it;
it++; auto card3=*it;
it++; auto card4=*it;
if(
getValue(card0)==getValue(card1) &&
getValue(card1)==getValue(card2) &&
getValue(card2)==getValue(card3)
)
return true;
if(
getValue(card1)==getValue(card2) &&
getValue(card2)==getValue(card3) &&
getValue(card3)==getValue(card4)
)
return true;
return false;
};
bool isRank3() const
{
auto it=cards.begin();
auto card0=*it;
it++; auto card1=*it;
it++; auto card2=*it;
it++; auto card3=*it;
it++; auto card4=*it;
if(
( getValue(card0)==getValue(card1) &&
getValue(card1)==getValue(card2)
) &&
getValue(card3)==getValue(card4)
)
return true;
if(
( getValue(card2)==getValue(card3) &&
getValue(card3)==getValue(card4)
) &&
getValue(card0)==getValue(card1)
)
return true;
return false;
};
bool isRank4() const
{
for(auto it=cards.begin()+1;it!=cards.end();it++)
{
auto card1=*(it-1);
auto card2=*it;
if(getSuit(card1)!=getSuit(card2))
return false;
}
return true;
};
bool isRank5() const
{
for(auto it=cards.begin()+1;it!=cards.end();it++)
{
auto card1=*(it-1);
auto card2=*it;
if(getValue(card1)+1!=getValue(card2))
return false;
}
return true;
};
bool isRank6() const
{
auto it=cards.begin();
auto card0=*it;
it++; auto card1=*it;
it++; auto card2=*it;
it++; auto card3=*it;
it++; auto card4=*it;
if(
getValue(card0)==getValue(card1) &&
getValue(card1)==getValue(card2)
)
return true;
if(
getValue(card2)==getValue(card3) &&
getValue(card3)==getValue(card4)
)
return true;
return false;
};
bool isRank7() const
{
auto it=cards.begin();
auto card0=*it;
it++; auto card1=*it;
it++; auto card2=*it;
it++; auto card3=*it;
it++; auto card4=*it;
if(
getValue(card0)==getValue(card1) &&
getValue(card2)==getValue(card3)
) return true;
if(
getValue(card0)==getValue(card1) &&
getValue(card3)==getValue(card4)
) return true;
if(
getValue(card1)==getValue(card2) &&
getValue(card3)==getValue(card4)
) return true;
return false;
};
bool isRank8() const
{
std::vector<int>dashboard;
for(auto it=cards.begin();it!=cards.end();it++)
{
auto card=*it;
auto v=getValue(card);
if(find(dashboard.begin(),dashboard.end(),v)==dashboard.end())
dashboard.push_back(v);
}
return (dashboard.size()==4);
};
bool isRank9() const
{
std::vector<int>dashboard;
for(auto it=cards.begin();it!=cards.end();it++)
{
auto card=*it;
auto v=getValue(card);
if(find(dashboard.begin(),dashboard.end(),v)==dashboard.end())
dashboard.push_back(v);
}
return (dashboard.size()==5);
};
int getRank() const
{
int r;
PRINT_DEBUG_INFO_PREFIX("getRank for:");
for(auto s:cards)
{
//PRINTVAR(s);
}
if(isRank1()) r= 1;
else if(isRank2()) r= 2;
else if(isRank3()) r= 3;
else if(isRank4()) r= 4;
else if(isRank5()) r= 5;
else if(isRank6()) r= 6;
else if(isRank7()) r= 7;
else if(isRank8()) r= 8;
else if(isRank9()) r= 9;
PRINTVAR(r);
return r;
};
};
Result compare (const PokerHand &player, const PokerHand &opponent) {
std::cout<<"============================================="<<""<<std::endl;
PRINTVAR(player.input );
PRINTVAR(opponent.input );
int r1=player.getRank();
int r2=opponent.getRank();
Result rv;
if(r1!=r2)
rv= (r1<r2)?WIN:LOSS;
else if(player.theSame(opponent))
rv= TIE;
else if(r1==1)
rv= player.compareInRank1(opponent );
else if(r1==2)
rv= player.compareInRank2(opponent );
else if(r1==3)
rv= player.compareInRank3(opponent );
else if(r1==4)
rv= player.compareInRank4(opponent );
else if(r1==5)
rv= player.compareInRank5(opponent );
else if(r1==6)
rv= player.compareInRank6(opponent );
else if(r1==7)
rv= player.compareInRank7(opponent );
else if(r1==8)
rv= player.compareInRank8(opponent );
else if(r1==9)
rv= player.compareInRank9(opponent );
PRINT_DEBUG_INFO_PREFIX("rv");
if(rv==WIN) PRINT_DEBUG_INFO_PREFIX("WIN");
if(rv==LOSS) PRINT_DEBUG_INFO_PREFIX("LOSS");
if(rv==TIE) PRINT_DEBUG_INFO_PREFIX("TIE");
PRINTVAR(player.input );
PRINTVAR(opponent.input );
return rv;
}
int main ()
{
char* s1="2H 3H 4H 5H 6H";
char* s2="KS AS TS QS JS";
s1="AS AH 2H AD AC";
s2="JS JD JC JH 3D";
s1="6S AD 7H 4S AS";
s2="AH AC 5H 6H 7S";
PokerHand p1(s1);
PokerHand p2(s2);
#if 0
//compare(p1,p2);
PokerHand p3("2H 2H 4H 2H 2D");
PRINTVAR(p1.isRank1());
PRINTVAR(p2.isRank1());
PRINTVAR(p3.isRank1());
PRINTVAR(p3.isRank2());
#endif
compare(p1,p2);
#if 0
for(int i=0;i<1000;i++)
{
char c=i;
PRINTVAR_hor(i);
PRINTVAR(c);
}
#endif
return 0;
}
<file_sep>/cpp/tree_structure/main.cpp
#include <string>
#include <deque>
#include "../POJ/include/lib.h"
#include "tree.class.h"
#include "tree.class.cpp" // to write templated class into h/cpp files separately, h/cpp should included both into main.cpp to fix compile errors
using namespace std;
void f(Node<int>* node);
int main()
{
//tree<> T;
std::cout<<"NODE:"<<std::endl;
Node<int> n(3);
n.show();
Node<int> m;
m.show();
std::cout<<"TREE:"<<std::endl;
Tree<int> T;
T.insertNode(T.getRoot(),0,2);
T.insertNode(T.getRoot(),0,1);
T.insertNode(T.getRoot(),0,0);
T.insertNode(T.getNodeById("0_1"),0,12);
T.insertNode(T.getNodeById("0_1"),0,11);
T.insertNode(T.getNodeById("0_1"),0,10);
T.insertNode(T.getNodeById("0_1_1"),0,111);
T.insertNode(T.getNodeById("0_1_1"),0,110);
PRINT_DEBUG_INFO();
std::cout<<"=================================="<<std::endl;
std::cout<<"TRAVERSE BFS:"<<std::endl;
T.traverseBFS(f);
std::cout<<"=================================="<<std::endl;
std::cout<<"=================================="<<std::endl;
std::cout<<"TRAVERSE DFS:"<<std::endl;
T.traverseDFS(f);
std::cout<<"=================================="<<std::endl;
//auto nn=T.getNodeById("0_1_1_0");
std::cout<<"=================================="<<std::endl;
std::cout<<"SHOW:"<<std::endl;
//T.traverseDFS(Tree<int>::_print_used_in_show);
//T.traverseDFS(f);
T.show();
std::cout<<"=================================="<<std::endl;
/*
// Create a deque containing integers
std::deque<int> d = {7, 5, 16, 8};
// Add an integer to the beginning and end of the deque
d.push_back(13);
d.push_back(14);
d.push_back(15);
PRINTVAR(d.front());
d.pop_front();
PRINTVAR(d.front());
d.pop_front();
PRINTVAR(d.front());
d.pop_front();
// Iterate and print values of deque
for(int n : d) {
std::cout << n << '\n';
}
*/
return 0;
};
void f(Node<int>* node)
{
cout<<"do for node:"<<node->getmIdInATree()<<"\t@"<<node<<endl;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/4.7.h
int f4_7 (double a) ;
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/20.2.h
void f20_2();
template <class T>
class Stack {
public:
Stack();
~Stack();
void Push(int n);
int Pop();
private:
int stack[SIZE];
int tos;
}
// zjc here
<file_sep>/cpp/6_EXEs/src/sort_insert.cpp
#include <chrono>
//using namespace std;
//using namespace std::chrono;
#include "include.top.h"
void sort_insert_wrp ()
{
cout<<"=============="<<endl;
PRINT_DEBUG_INFO();
vector <int> a={6,5,1,2,3,10,2,3,4,5};
//vector <int> a={6,2,15,3};
//vector <int> a={6,2};
PRINT_VECTOR(a);
cout<<"=============="<<endl;
vector <int> a_bk=a;
chrono::high_resolution_clock::time_point t1 = chrono::high_resolution_clock::now();
sort_insert(a);
//sort_insert2(a);
chrono::high_resolution_clock::time_point t2 = chrono::high_resolution_clock::now();
cout<<"=============="<<endl;
PRINT_VECTOR(a);
cout<<"=============="<<endl;
sanity_check(a,a_bk);
auto duration = chrono::duration_cast< chrono::microseconds>( t2 - t1 ).count();
cout<<"duration:"<<duration<<endl;
}
bool sanity_check(vector<int> &a,vector<int> &a_bk)
{
cout<<"=============="<<endl;
cout<<"SANITY CHECK:"<<endl;
cout<<"before:\t";
PRINT_VECTOR_hor(a_bk);
cout<<"after:\t";
PRINT_VECTOR_hor(a);
cout<<"=============="<<endl;
assert(a.size()==a_bk.size());
for(auto it=a.begin();it!=a.end()-1;it++)
{
cout<<"checking-1:"<<(*it)<<""<<endl;
assert(*it<=*(it+1));
}
for(auto it=a.begin();it!=a.end();it++)
{
auto t=*it;
cout<<"checking-2:"<<t<<""<<endl;
int cnt1=std::count(a.begin(),a.end(),t);
int cnt2=std::count(a_bk.begin(),a_bk.end(),t);
PRINTVAR(cnt1);
PRINTVAR(cnt2);
assert(cnt1==cnt2);
}
cout<<"=============="<<endl;
cout<<"SANITY CHECK DONE!"<<endl;
return true;
}
void sort_insert(vector<int> &arr) // this version is the same as MIT web course
{
for(auto it=arr.begin()+1;it!=arr.end();it++) // n-1+1=n
{
cout<<"============================"<<""<<endl;
PRINT_VECTOR_hor(arr);
auto get=*it; // n
PRINTVAR(get);
auto it_sorted=it-1;
while(it_sorted!=arr.begin()-1 && *it_sorted>get) // sum(k[i]), where k[i]=i+1 ,i=1~n
{
cout<<"-----"<<""<<endl;
PRINTVAR(*it_sorted);
*(it_sorted+1)=*it_sorted;
PRINT_VECTOR_hor(arr);
it_sorted--;
}
*(it_sorted+1)=get;
PRINT_VECTOR_hor(arr);
cout<<"============================"<<""<<endl;
}
}
void sort_insert_zjc (vector<int> &arr) // this version is like the MIT web course
{
for(auto it=arr.begin()+1;it!=arr.end();it++) // n-1+1=n
{
cout<<"============================"<<""<<endl;
PRINT_VECTOR_hor(arr);
auto get=*it; // n
PRINTVAR(get);
for(auto it_sorted=it-1;it_sorted!=arr.begin()-1;it_sorted--) // sum(k[i]), where k[i]=i+1 ,i=1~n
{
cout<<"-----"<<""<<endl;
auto item_sorted=*it_sorted;
PRINTVAR(item_sorted);
if(*it_sorted>get )
{
*(it_sorted+1)=*it_sorted;
}
else
{
*(it_sorted+1)=get;
break;
}
if(it_sorted==arr.begin())
*(it_sorted)=get;
PRINT_VECTOR_hor(arr);
}
PRINT_VECTOR_hor(arr);
cout<<"============================"<<""<<endl;
}
}
void sort_insert2 (vector<int> &arr)
{
for(auto it=arr.begin()+1;it!=arr.end();it++)
{
cout<<"============================"<<""<<endl;
PRINT_VECTOR_hor(arr);
auto get=*it;
PRINTVAR(get);
for(auto it_sorted=arr.begin();it_sorted!=it+1;it_sorted++)
{
cout<<"-----"<<""<<endl;
auto item_sorted=*it_sorted;
PRINTVAR(item_sorted);
if(*it_sorted>get )
{
cout<<"swap:"<<get<<","<<*it_sorted<<endl;
int& ref=(*it_sorted);
swap(get,ref);
}
if (it_sorted==it)
*(it_sorted)=get;
PRINT_VECTOR_hor(arr);
}
PRINT_VECTOR_hor(arr);
cout<<"============================"<<""<<endl;
}
}
void swap(int& a,int& b)
{
int tmp;
tmp=a;
a=b;
b=tmp;
}
void swap(int* a,int* b)
{
int tmp;
tmp=*a;
*a=*b;
*b=tmp;
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/TwoColor.h
/////////////////////////////////
// P352 Table 4.1.7 TwoColor
/////////////////////////////////
class TwoColor
{
private:
vector<bool> mMarked;// MEMBER
vector<int> mColor;
bool mIsTwoColorable=true;// MEMBER
public:
TwoColor(Graph* G)// METHOD
{
mMarked.resize(G->V(),0);
mColor.resize(G->V(),1);
for(int s=0;s<G->V();s++)
if(!mMarked[s])
dfs(G,s);
cout<<"-----------------------"<<endl;
for(int ii=0;ii<mColor.size();ii++)
{
cout<<"Color "<<ii<<"\t=\t"<<mColor[ii]<<endl;
}
cout<<"-----------------------"<<endl;
}
void dfs(Graph* G,int v)// METHOD
{
mMarked[v]=1;
for(int w:G->adj(v))
{
//PRINTVAR_hor(v);
//DPRINT_hor(" ref:"<<u<<",");
//DPRINT(w<<" of adj("<<v<<")");
if(!mMarked[w])
{
mColor[w]=!mColor[v];
DPRINT("ADD Color "<<w<<": "<<mColor[w]);
dfs(G,w);
}
else if(mColor[w]==mColor[v])
{
mIsTwoColorable=0;
DPRINT("not Colorable because same color:"<<w<<","<<v);
}
}
}
bool isBipartite() {return mIsTwoColorable;}
//bool connected(int v,int w) { return mId[v]==mId[w]; }// METHOD
//int id(int v){return mId[v];}// METHOD
//int count(){return mCount;}// METHOD
};
class TestTwoColor// METHOD
{
public:
TestTwoColor(Graph* G)//METHOD
{
TwoColor* cy=new TwoColor(G);
DLOG(cy->isBipartite());
}
};
void testTwoColor()//METHOD
{
Graph* g=new Graph("twoColor.txt");
DLOG(g->toString());
new TestTwoColor(g);
}
<file_sep>/cpp/codewar/best_travel/others_Durdo/run.gprof.sh
#rm a.out; g++ -v -g -Wall -std=c++11 s.cpp ; ./a.out
#rm a.out; g++ -v -g -Wall -std=c++11 s.handout.cpp ; ./a.out
rm a.out; g++ -v -g -O -Wall -std=c++11 -pg others.cpp ; ./a.out
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/4.3.h
int main4_3 () ;
<file_sep>/cpp/codewar/best_travel/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#define SIMPLE_LOG
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#if(SIMPLE_LOG)
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#define PRINT_COUT(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
typedef std::map<int, std::map<int, std::map<int, int>>> TYPEMAP ;
class BestTravel
{
public:
static int chooseBestSum(int t, int k, std::vector<int>& ls);
static int chooseBestSum(int start_from,int up_bound,int findItemCnt,std::vector<int>& ls,
TYPEMAP& cache_keep_max);
// cache_keep_max : MAP: start_from,up_bound,findItemCnt -> sum
static int findLargestOne(std::vector<int> keepInd,int up_bound, std::vector<int>& ls,
TYPEMAP& cache_keep_max);
static int max(int a,int b) {
//std::cout<<"MAX:"<<a<<" , "<<b<<std::endl;
return a>b?a:b;};
static int CALL_LEVEL;
static std::vector<int> ANS_LIST;
};
int BestTravel::CALL_LEVEL=0;
int BestTravel::chooseBestSum(int start_from,int up_bound,int findItemCnt,std::vector<int>& ls,TYPEMAP& cache_keep_max) // recur
{
if(findItemCnt<=0)
return 0;
if(findItemCnt+start_from>ls.size())// cannot find findItemCnt items
return -1;
//PRINTVAR(cache_keep_max.size());
if( cache_keep_max.count(start_from)!=0 &&
cache_keep_max[start_from].count(up_bound)!=0 &&
cache_keep_max[start_from][up_bound].count(findItemCnt)!=0
)
{
#ifndef SIMPLE_LOG
std::cout<<"USE CACHE: cache_keep_max";
std::cout<<"\t"<<start_from;
std::cout<<"\t"<<up_bound;
std::cout<<"\t"<<findItemCnt;
std::cout<<"=\t"<<cache_keep_max[start_from][up_bound][findItemCnt];
PRINT_ENDL();
#endif
return cache_keep_max[start_from][up_bound][findItemCnt];
}
CALL_LEVEL++;
#ifndef SIMPLE_LOG
std::cout<<CALL_LEVEL<<")\t";
for(int i=CALL_LEVEL;i>0;i--)
std::cout<<" .";
PRINT_COUT("-->");
PRINT_COUT(__FUNCTION__);
PRINTVAR_hor(start_from);
PRINTVAR_hor(up_bound);
PRINTVAR_hor(findItemCnt);
PRINTVAR_hor(ls.size());
PRINT_ENDL();
//PRINT_VECTOR_hor(keepInd);
//PRINT_VECTOR_hor(ls);
std::cout<<"ls:\t";
int cntr=0;
for(auto u=ls.begin();u!=ls.end();u++) {
bool keep=0;
if(start_from==cntr)
std::cout<<cntr<<":"<<*u<<"*\t";
else
std::cout<<cntr<<":"<<*u<<"\t";
cntr++;
}
std::cout<<""<<std::endl;
#endif
int sum;
if(start_from>=ls.size()-1) // the last one item;
{
if(ls[start_from]>up_bound)
sum=-1;
else
sum= ls[start_from];
}
else
{
if(ls[start_from]>up_bound)
sum= chooseBestSum(start_from+1,up_bound,findItemCnt,ls,cache_keep_max);
else
{
PRINT_COUT(start_from);
PRINT_DEBUG_INFO_PREFIX("left\t");
int left=chooseBestSum(start_from+1,up_bound-ls[start_from],findItemCnt-1,ls,cache_keep_max);
PRINT_COUT(start_from);
PRINT_DEBUG_INFO_PREFIX("right\t");
int right =chooseBestSum(start_from+1,up_bound,findItemCnt,ls,cache_keep_max);
PRINTVAR(left);
PRINTVAR(right);
PRINTVAR(ls[start_from]);
int sum_of_left=(left==-1)?-1:(left+ ls[start_from]);
sum= max(
sum_of_left,
right
);
}
}
PRINTVAR(sum);
//cache_keep_max[keepInd]=sum;
#ifndef SIMPLE_LOG
std::cout<<CALL_LEVEL<<")\t";
for(int i=CALL_LEVEL;i>0;i--)
std::cout<<" .";
PRINT_COUT("<--");
PRINT_COUT(__FUNCTION__);
PRINTVAR_hor(sum);
PRINT_ENDL();
#endif
CALL_LEVEL--;
cache_keep_max[start_from][up_bound][findItemCnt]=sum;
return sum;
}
int BestTravel::chooseBestSum(int t, int k, std::vector<int>& ls)
{
PRINT_DEBUG_INFO();
clock_t start, end;
start = clock();
TYPEMAP cache_keep_max;
std::vector<int> lsLessThanT;
for(auto i:ls)
{
if(i<=0)
return -1;
if(i<=t)
lsLessThanT.push_back(i);
}
PRINTVAR(ls.size());
PRINTVAR(lsLessThanT.size());
if(k>lsLessThanT.size())
return -1;
end = clock(); std::cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
auto ans= chooseBestSum(0,t,k,lsLessThanT,cache_keep_max);
end = clock();
//std::cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
//std::cout << "CPU-TIME START " << start << "\n";
//std::cout << "CPU-TIME END " << end << "\n";
//std::cout << "CPU-TIME END - START " << end - start << "\n";
std::cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
#if 0
verbose_PRINT_VECTOR_hor(ls);
verbose_PRINT_VECTOR_hor(lsLessThanT);
PRINTVAR(lsLessThanT.size());
verbose_PRINTVAR_hor(t);
verbose_PRINTVAR_hor(k);
verbose_PRINT_DEBUG_INFO_PREFIX("=====================");
verbose_PRINTVAR(ans);
#endif
//std::cout<<std::endl;
verbose_PRINT_DEBUG_INFO_PREFIX("=====================");
PRINTVAR(cache_keep_max.size());
for(auto v1:cache_keep_max)
for(auto v2:v1.second)
for(auto v3:v2.second)
{
//PRINTVAR_hor(v1.first);
//PRINTVAR_hor(v2.first);
//PRINTVAR_hor(v3.first);
//PRINTVAR_hor(v3.second);
PRINT_COUT(v1.first);
PRINT_COUT(v2.first);
PRINT_COUT(v3.first);
PRINT_COUT(v3.second);
PRINT_ENDL();
}
verbose_PRINT_DEBUG_INFO_PREFIX("=====================");
return ans;
}
void check(std::vector<int>& arr,int sum){
for(int i1=0;i1<arr.size();i1++)
for(int i2=i1+1;i2<arr.size();i2++)
for(int i3=i2+1;i3<arr.size();i3++)
for(int i4=i3+1;i4<arr.size();i4++)
for(int i5=i4+1;i5<arr.size();i5++)
{
if(
arr[i1]+
arr[i2]+
arr[i3]+
arr[i4]+
arr[i5]==sum
)
{
PRINTVAR(i1);
PRINTVAR(i2);
PRINTVAR(i3);
PRINTVAR(i4);
PRINTVAR(i5);
return;
}
}
PRINT_DEBUG_INFO_PREFIX("NO MATCH!");
}
int main ()
{
//std::vector<int> arr = {17, 0, -4, 3, 15};
//std::vector<int> arr = {3,4,8,9,10};
#if 0
std::vector<int> arr = {91,74,73,73,73,73,73};
std::map<std::vector<int>,int> cache_keep_max;
auto r=BestTravel::chooseBestSum(300,3,arr);
#endif
#if 0
std::vector<int> arr = {1,2,91,74,73,82,71};
std::map<std::vector<int>,int> cache_keep_max;
auto r=BestTravel::chooseBestSum(500,5,arr);
#endif
#if 1
std::vector<int> arr = {100, 76, 56, 44, 89, 73, 68, 56, 64, 123, 2333, 144, 50, 132, 123, 34, 89 };
//std::vector<int> arr = {100, 44, 89, 73, 68, 56, 64, 123, 34, 89 };
auto r=BestTravel::chooseBestSum(500,5,arr);
#endif
#if 0
std::vector<int> arr = { 91,74,73,85,73,81,87};
auto r=BestTravel::chooseBestSum(331,5,arr);
#endif
#if 0
std::vector<int> arr = { 91,74,73,85,73,81,87 };
auto r=BestTravel::chooseBestSum(331,4,arr);
#endif
//PRINTVAR(BestTravel::findLargestOne(std::vector<int>(),100,arr,cache_keep_max));
//PRINT_DEBUG_INFO_PREFIX("================================================");
//std::vector<int> a={1,2,3};
//std::vector<int> b={1,3,2};
//sort(b.begin(),b.end());
//PRINTVAR((a==b));
//PRINT_DEBUG_INFO_PREFIX("================================================");
PRINTVAR(r);
check(arr,r);
check(arr,331);
//
//
return 0;
}
<file_sep>/python/workspace_python/pendulum_phase/src/SinglePendulumClass.py
# _*_ coding:utf-8 _*_
'''
Created on 2015年8月9日
@author: admin
'''
import pygame
import random
import gl
import math
class SinglePendulumClass (object):
def __init__(self, pos,freq,A,phi,name,time_tick,direction, color=(0, 255, 0)):
print('INIT:'+str(name)+'pos='+str(pos)+'freq='+str(freq)+'A='+str(A)+'')
self.m_x = pos[0]
self.m_y = pos[1]
self.x = self.m_x * 10
self.old_x=self.m_x
self.old_y=self.m_y
self.y = self.m_y * 10
self.color = color
self.name=name
self.freq=freq
self.A=A
self.phi=phi
self.direction=direction
self.length = 10
self.tail = []
#self.time_tick = 100 ;
self.time_tick = time_tick ;
self.speed = gl.INIT_SPEED
self.time = 0
self.last_key = None
self.is_dead=False
self.point = 0
def blit(self, screen):
rect = pygame.Rect(self.x, self.y, 10, 10)
pygame.draw.rect(screen, self.color, rect)
def update_position(self, dt,screen):
self.time += dt
if self.direction=='x':
self.y=self.y
self.x=self.old_x+self.A*math.cos(2*math.pi*self.freq*self.time+self.phi)
else:
self.x=self.x
self.y=self.old_y+self.A*math.cos(2*math.pi*self.freq*self.time+self.phi)
#print 't='+str(self.time)+'; update:' + self.name + ' IN: ' + str(self.x) + ' ' + str(self.y)
#print("%s;%s;%s;%s;%s;%s"%(self.name,self.A,self.freq,self.phi,self.time,self.direction))
self.blit(screen)
if self.time >= self.time_tick :
#self.x += self.h_x
#self.y += self.h_y
#self.head.x, self.head.y = self.x * 10, self.y * 10
self.time = 0
def update(self,dt,screen):
self.update_position(dt,screen)
def get_loc(self):
return (self.x,self.y)<file_sep>/cpp/codewar/best_travel/others_Durdo/others.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_COUT(p) \
(::std::cout<<p<<"\t" )
#define PRINT_ENDL() \
(::std::cout<<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#define SIMPLE_LOG
#define verbose_PRINT_VECTOR_hor(a) std::cout<<#a<<":\t";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define verbose_PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define verbose_PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define verbose_PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//#if(SIMPLE_LOG)
#ifdef SIMPLE_LOG
#define PRINTVAR(a)
#define PRINTVAR_hor(a)
#define PRINT_VECTOR(a)
#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p)
#endif
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <map>
#include <assert.h>
#include <vector>
#include <string>
#include <algorithm>
/*
* Stop giving me classes with only
* one static method! Geez....
*/
namespace BestTravel
{
static int CALL_LEVEL=0;
void getBestValue(std::vector<int> &dist, int max, int depth,
int curValue, int lastIdx, int &sum)
{
CALL_LEVEL++;
PRINT_COUT(CALL_LEVEL);
for(int i=CALL_LEVEL;i>0;i--)
PRINT_COUT("\t");
PRINT_COUT("-->");
PRINTVAR_hor(max);
PRINTVAR_hor(depth);
PRINTVAR_hor(curValue);
PRINTVAR_hor(lastIdx);
PRINTVAR_hor(sum);
PRINT_ENDL();
for(auto i=0;i<dist.size();i++)
{
if(i!=lastIdx)
PRINT_COUT(dist[i]);
else
std::cout<<dist[i]<<"*\t";
}
PRINT_ENDL();
// start in the begining
int i = 0;
// generic name, waiting for the code review
int value;
// let's go!
for (std::vector<int>::iterator it = dist.begin();
it < dist.end(); it++, i++)
{
// there is no looking back now
if (i <= lastIdx)
continue;
// best result achieved, get out of here!
if (sum == max && sum != -1)
break;
// maybe I should store this
value = curValue + (*it);
PRINTVAR_hor(i);
PRINTVAR_hor((*it));
PRINTVAR_hor(value);
PRINT_ENDL();
// nah, too big
if (value > max)
continue;
// should I go deeper?
if (depth > 1)
getBestValue(dist, max, depth - 1, value, i, sum);
// I hope this is the one!
if (depth == 1 && value > sum)
sum = value;
}
PRINT_COUT(CALL_LEVEL);
for(int i=CALL_LEVEL;i>0;i--)
PRINT_COUT("\t");
PRINT_COUT("<--");
PRINTVAR_hor(sum);
PRINT_ENDL();
//PRINTVAR(sum);
CALL_LEVEL--;
}
int chooseBestSum(int t, int k, std::vector<int>& ls)
{
CALL_LEVEL=0;
// final result
int sum = -1;
// start BIG!
PRINT_VECTOR_hor(ls);
//std::sort(ls.rbegin(), ls.rend());
PRINT_VECTOR_hor(ls);
// did i say recursion?
getBestValue(ls, t, k, 0, -1, sum);
//void getBestValue(std::vector<int> &dist,
// int max,
// int depth,
// int curValue,
// int lastIdx,
// int &sum)
//gg
return sum;
}
};
int main ()
{
//std::vector<int> arr = {17, 0, -4, 3, 15};
//std::vector<int> arr = {3,4,8,9,10};
#if 0
std::vector<int> arr = {91,74,73,73,73,73,73};
std::map<std::vector<int>,int> cache_keep_max;
auto r=BestTravel::chooseBestSum(300,3,arr);
#endif
#if 1
std::vector<int> arr = {1,8,3,6,5,4,7,2,9};
std::map<std::vector<int>,int> cache_keep_max;
auto r=BestTravel::chooseBestSum(30,5,arr);
#endif
#if 0
std::vector<int> arr = {100, 76, 56, 44, 89, 73, 68, 56, 64, 123, 2333, 144, 50, 132, 123, 34, 89 };
//std::vector<int> arr = {100, 44, 89, 73, 68, 56, 64, 123, 34, 89 };
auto r=BestTravel::chooseBestSum(500,5,arr);
#endif
#if 0
std::vector<int> arr = { 91,74,73,85,73,81,87};
auto r=BestTravel::chooseBestSum(331,5,arr);
#endif
#if 0
std::vector<int> arr = { 91,74,73,85,73,81,87 };
auto r=BestTravel::chooseBestSum(331,4,arr);
#endif
//PRINTVAR(BestTravel::findLargestOne(std::vector<int>(),100,arr,cache_keep_max));
//PRINT_DEBUG_INFO_PREFIX("================================================");
//std::vector<int> a={1,2,3};
//std::vector<int> b={1,3,2};
//sort(b.begin(),b.end());
//PRINTVAR((a==b));
//PRINT_DEBUG_INFO_PREFIX("================================================");
PRINTVAR(r);
//
//
return 0;
}
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch5/exe5.1/Tree.h
class Tree {
public:
Tree(){
mNodes={};
}
Tree(int n){
mNodes.resize(n);
for(int i=0;i<mNodes.size();i++)
mNodes[i]=i;
}
void show()
{
}
int addNode(){
mNodes.push_back(mNodes.size());
return mNodes.size()-1;
}
void addEdge(string f,string t){
if(std::find(mNodesStr.begin(),mNodesStr.end(),f)==mNodesStr.end())
mNodesStr.push_back(f);
if(std::find(mNodesStr.begin(),mNodesStr.end(),t)==mNodesStr.end())
mNodesStr.push_back(t);
mEdges.push_back(make_pair(f,t));
}
private:
map<int,string> map_N2S;
map<string,int> map_S2N;
vector<int> mNodes;
vector<string> mNodesStr;
vector<pair<int,int>> mEdges;
};
<file_sep>/cpp/exe_game/tetris/lib.h
//static void sleep_ms(unsigned int secs);
#include <vector>
#include "Shape.class.h"
void sleep_ms(unsigned int secs);
void deleteFromVectorShape(std::vector<Shape*>* vecPtr, Shape* item);
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/11.5.h
void f11_5();
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/include/f13_6.h
#include "include.top.h"
void f13_6() ;
<file_sep>/cpp/regexp/regexp.cpp
// regex_replace example
#include <iostream>
#include <string>
#include <regex>
#include <iterator>
#include <algorithm>
#include <vector>
#include <assert.h>
using namespace std;
#define PRINTVAR(a) cout<<#a<<"\t=\t"<<a<<endl;
#define PRINTVAR_hor(a) cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {cout<<u<<":\t"<<*a+u<<endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {cout<<*u<<endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {cout<<*u<<"\t";};cout<<""<<endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
//int main ()
//{
// std::string s ("there is a subsequence in the string\n");
// std::regex e ("\\b(sub)([^ ]*)"); // matches words beginning by "sub"
//
// // using string/c-string (3) version:
// std::cout << s;
// std::cout << std::regex_replace (s,e,"sub-$2");
//
// //// using range/c-string (6) version:
// //std::string result;
// //std::regex_replace (std::back_inserter(result), s.begin(), s.end(), e, "$2");
// //std::cout << result;
//
// //// with flags:
// //std::cout << std::regex_replace (s,e,"$1 and $2",std::regex_constants::format_no_copy);
// //std::cout << std::endl;
//
//std::cout<<"-----------------------------------"<<std::endl;
// std::string s1 ("func(v1,v2,v3)\n");
// std::regex e1 (",");
//
// std::cout << s1;
// std::cout << std::regex_replace (s1,e1,",\n\t");
// return 0;
//}
vector<string> ParseFuncInfo(string info,bool keep_braces=false); // info = "func_name({arg1},{arg2},{arg3},...)"; in {...} there can be any characters like [",(){}<>]
inline bool isMatchInBrackets (std::string& exp) ;
int main ()
{
string info("this is an example, 123,456");
string _str(", \n\t");
std::cout<<"TEST=================> "<<std::endl;
std::string s1 ("func(v1,v2,v3)\n");
std::regex e1 (",");
std::cout << s1;
std::cout << std::regex_replace(s1,e1,_str);
//------------------
_str="";
std::regex e2 ("\\(.*");
std::cout << s1;
std::cout << std::regex_replace(s1,e2,_str);
std::cout<<"TEST<================= "<<std::endl;
std::regex e(", ");
std::regex_match(info,e);
std::cout<<"BEFORE: "<<info<<std::endl;
info=std::regex_replace(info,e,_str);
std::cout<<"AFTER: "<<info<<std::endl;
std::cout<<"================= "<<std::endl;
s1="\"1232\",\"\",\"single quotation\",\"\"double quotations\"\",\"comma,in quotation\",\"str1=\"quote,in,quote\",str2=\"hi, \" is a quotation!\"\"";
// B ^ ^ ^ ^ ^ E
cout<<s1<<endl;
s1=std::regex_replace(s1,std::regex("ww"),"w");
//auto it=s1.begin();
bool flag_quotation=0;
for(int cntr=0;cntr<s1.size();cntr++)
{
//PRINTVAR(flag_quotation);
//PRINTVAR(cntr);
auto c=s1[cntr];
if(c=='"')
flag_quotation=!flag_quotation;
if(flag_quotation && c!='"')
c=' ';
if(!flag_quotation && c==',')
{
s1[cntr]='|';
//s1.insert(cntr,",@");
//cntr++;
//cntr++;
}
}
cout<<s1<<endl;
std::cout<<"TEST<================= "<<std::endl;
s1="w w {w} w w";
std::cout<<"BEFORE: "<<s1<<std::endl;
s1=std::regex_replace(s1,std::regex("w$"),"\nW");
PRINT_DEBUG_INFO();
std::cout<<"AFTER: "<<s1<<std::endl;
PRINT_DEBUG_INFO();
s1=std::regex_replace(s1,std::regex("\\{"),"\n{");
PRINT_DEBUG_INFO();
std::cout<<"AFTER: "<<s1<<std::endl;
PRINT_DEBUG_INFO();
std::cout<<"================= "<<std::endl;
//s1="method (out brace{br1{br2}} ,br0 {br11{br22}br11} br00, {c}, {d e} , {f})a\n";
s1="method({br1,{ab,{u}c}}, {br2})";
s1="SchedRegionManager::createLatencyRegion({Node 2 'call void (...)* @_ssdm_op_SpecLatency(i32 0, i32 0, [1 x i8]* @p_str) nounwind'})";
//s1="method (out brace{br1{br2}} ,\nbr0 {br11{br22}br11} br00, {c}, {d e} , {f})";
//s1="abcde";
PRINTVAR(s1);
auto r=ParseFuncInfo(s1);
PRINT_VECTOR(r);
string ttt="01234567\nabcde\n//comments\nline4";
//int end=ttt.size()-1;
//PRINTVAR(ttt.size());
//PRINTVAR(ttt.substr(0,3));
//PRINTVAR(ttt.substr(1,3));
//PRINTVAR(ttt.substr(2,3));
//PRINTVAR(ttt.substr(0,end-0));
//PRINTVAR(ttt.substr(1,end-1));
//PRINTVAR(ttt.substr(2,end-2));
////PRINTVAR(std::regex_replace(ttt,regex("^"),"\n//"));
PRINTVAR(ttt);
PRINTVAR(std::regex_replace(ttt,regex("\n"),"\t"));
//
//std::cout<<"================= "<<std::endl;
//PRINTVAR(ttt);
//std::cout<<"================= "<<std::endl;
//PRINTVAR(std::regex_replace(ttt,regex("(\n|^)([^/])"),"$1// $2"));
//std::cout<<"================= "<<std::endl;
}
#if 0
vector<string> ParseFuncInfo(string info,bool keep_braces) // info = "func_name({arg1},{arg2},{arg3},...)"; in {...} there can be any characters like [",(){}<>]
{
string info_bk=info;
//std::cout<<"BEFORE: "<<info_bk<<std::endl;
//info=std::regex_replace(info,std::regex("\\{[^,]\\}"),"{ }");
int found=info.find('\n');
//PRINTVAR(found);
//PRINTVAR(info.size());
assert(found==std::string::npos|| found==info.size()-1);
assert(isMatchInBrackets(info));
std::smatch m;
string s2;
string argument_holder;
while (std::regex_search(info,m,std::regex("\\{([^,]+)\\}")))
{
for (auto &x:m)
{
argument_holder=string(x);
argument_holder=std::regex_replace(argument_holder,std::regex("."),".");
}
s2+=m.prefix().str();
s2+="{"+argument_holder+"}";
info=m.suffix().str();
}
s2+=info;
std::cout<<"AFTER : "<<s2<<std::endl;
int pos=s2.find(",");
vector<int> positions;
while(pos!=string::npos)
{
//PRINTVAR(pos);
positions.push_back(pos);
pos=s2.find(",",pos+1);
}
//PRINT_VECTOR(positions);
//std::sort(positions.begin(),positions.end(),std::greater<int>());
//--------------------------------
vector<string> final_vector;
int begin=0;
int end=info_bk.find("(");
final_vector.push_back(info_bk.substr(begin,end-begin));
//auto it=positions.begin();
//PRINTVAR(info_bk.size());
//while(end!=info_bk.size())
// while(it!=positions.end())
for(int cnt=0;cnt!=positions.size()+1;cnt++)
{
begin=end+1;
//end=(*it++);
if(cnt!=positions.size())
end=positions[cnt];
else
end=info_bk.find_last_of(")");
string tmp=info_bk.substr(begin,end-begin);
tmp=std::regex_replace(tmp,std::regex("^\\s+"),"");
tmp=std::regex_replace(tmp,std::regex("\\s+$"),"");
if(!keep_braces)
{
int end;
end=tmp.size()-1;
if(tmp[0]=='{')
tmp=tmp.substr(1,end);
end=tmp.size()-1;
if(tmp[end]=='}')
tmp=tmp.substr(0,end-1);
}
final_vector.push_back(tmp);
}
return final_vector;
}
#endif
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#if 1
vector<string> ParseFuncInfo(string info, bool keep_braces)
{
// info = "func_name({arg1},{arg2},{arg3},...)"; in {...} there can be any characters like [",(){}<>]
string info_bk=info;
int found = info.find('\n');
bool tmp = ((found == std::string::npos) || (found == info.size() - 1));
assert(tmp);
//DEBUG_ASSERT(tmp);
tmp = isMatchInBrackets(info);
assert(tmp);
//DEBUG_ASSERT(tmp);
std::smatch m;
string s2;
string argument_holder;
int cnt_open=0;
for(auto c:info_bk)
{
if(c=='{' )
{
if(cnt_open==0)s2+=c;
else s2+='.';
cnt_open++;
continue;
}
if(c=='}' )
{
cnt_open--;
if(cnt_open==0)s2+=c;
else s2+='.';
continue;
}
if(cnt_open>0)
s2+=".";
else
s2+=c;
}
int pos=s2.find(",");
vector<int> positions;
while(pos != string::npos)
{
positions.push_back(pos);
pos=s2.find(",", pos+1);
}
//--------------------------------
vector<string> final_vector;
int begin = 0;
int end = info_bk.find("(");
final_vector.push_back(info_bk.substr(begin, end - begin));
for (int cnt = 0; cnt != positions.size() + 1; cnt++)
{
begin = end + 1;
if (cnt != positions.size())
end = positions[cnt];
else
end = info_bk.find_last_of(")");
string tmp = info_bk.substr(begin, end - begin);
// delete blanks in both sides:
tmp = std::regex_replace(tmp, std::regex("^\\s+"), "");
tmp = std::regex_replace(tmp, std::regex("\\s+$"), "");
tmp = std::regex_replace(tmp, std::regex("[)]$"),""); // remove ending )
// delete braces in both sides:
if(!keep_braces)
{
int end1 = tmp.size() - 1;
if (tmp[0] == '{' && tmp[end1] != '}' ||
tmp[0] != '{' && tmp[end1] == '}')
{
std::cout<<"Warning: one of {} is not at side:"<<tmp<<std::endl;
std::cout<<"Warning: full string :"<<info_bk<<std::endl;
assert(0);
//DEBUG_ASSERT(0);
}
if (tmp[0] == '{')
tmp[0] = '"';
if (tmp[end1] == '}')
tmp[end1] = '"';
}
final_vector.push_back(tmp);
}
return final_vector;
}
#endif
inline bool isMatchInBrackets (std::string& exp)
{
string pStack;
for(int i=0;i<exp.size();i++)
{
if(
exp[i]=='[' ||
exp[i]=='{' ||
exp[i]=='('
)
pStack.push_back(exp[i]);
if(
exp[i]==']' ||
exp[i]=='}' ||
exp[i]==')'
)
{
char c=pStack[pStack.size()-1];
pStack.pop_back();
if(c=='\a')
return false; // if the expression has only closing brackets
else if(
c=='['&&exp[i]==']' ||
c=='{'&&exp[i]=='}' ||
c=='('&&exp[i]==')'
)
{
}
else
return false; // if mismatch
}
}
if(!pStack.empty())
return false; // if the expression has only opening brackets
else
return true;
}
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch5/exe5.1/s.cpp
#include "h.h"
int f(int n)
{
DENTERV(n);
if(n==0) {
DRETURN;
return 0;
}
if(n%2==0)
{
auto r= f(n/2);
DRETURN;
return r;
}
{
auto r= 1+f(n-1);
DRETURN;
return r;
}
}
int f2(int n)
{
DENTERV(n);
if(n<=1)
{
DRETURN;
return n;
}
if(n%2==0)
{
auto r= n+f2(n/2);
DRETURN;
return r;
}
auto r= f2((n+1)/2)+f2((n-1)/2);
DRETURN;
return r;
}
int exe5p1e1(){
f(1);
f(2);
f(3);
f(99);
f(100);
f(128);
f(197);
}
int exe5p1e2(){
f2(1);
f2(2);
f2(3);
f2(4);
f2(5);
f2(6);
f2(197);
}
int main()
{
//exe5p1e1();
exe5p1e2();
return 0;
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/DepthFirstPaths.h
/////////////////////////////////
// P342 Table 4.1.5 Paths
/////////////////////////////////
#define USE_DFS_SEARCH 1
#include "BreadthFirstPaths.h"
class DepthFirstPaths
{
protected:
vector<bool> mMarked;// MEMBER
vector<int> mEdgeTo;// MEMBER
int mS;
public:
DepthFirstPaths() {}//METHOD
DepthFirstPaths(Graph* G,int s)//METHOD
{
mMarked.resize(G->V(),0);
mEdgeTo.resize(G->V(),-2); // -2 is init value
mEdgeTo[s]=-1; // -1 is root value
mS=s;
dfs(G,s);
cout<<"mEdgeTo:";
for(int i=0;i<G->V();i++)
{
cout<<i<<":"<<mEdgeTo[i]<<endl;
}
cout<<endl;
}
private:
void dfs(Graph*G,int v)//METHOD
{
//DENTER;
//DLOG(v);
mMarked[v]=1;
//DPRINT("set mMarked["<<v<<"]=1");
//DLOG(mMarked[v]);
for(int w:G->adj(v))
if(!mMarked[w])
{
mEdgeTo[w]=v;
DPRINT(" EdgeTo["<<w<<"]="<<v);
dfs(G,w);
}
//DRETURN;
}
public:
bool hasPathTo(int v) { return mMarked[v]; }//METHOD
vector<int> pathTo(int v)//METHOD
{
if(!hasPathTo(v)) return {};
vector<int> path={};
for(int x=v;x!=mS;x=mEdgeTo[x])
path.push_back(x);
path.push_back(mS);
return path;
}
};
#if USE_DFS_SEARCH
class Paths:public DepthFirstPaths
{
public:
using DepthFirstPaths::DepthFirstPaths;//METHOD
};
#else
class Paths:public BreadthFirstPaths
{
public:
using BreadthFirstPaths::BreadthFirstPaths;//METHOD
};
#endif
class TestPath
{
public:
TestPath(Graph* G,int s)//METHOD
{
DENTER;
Paths* search=new Paths(G,s);
DLOG(search);//0x55
for(int v=0;v<G->V();v++)
{
cout<<"from "<<s<<" to "<<v<<":\t";
if(search->hasPathTo(v))
for(int x:search->pathTo(v))
if(x==s) cout<<x;
else cout<<x<<"-";
else
cout<<"NA";
cout<<endl;
}
DRETURN;
}
};
void testPath()//METHOD
{
DENTER;
Graph* g=new Graph("tinyG.txt");
DLOG(g->toString());
int SOURCE=1;
new TestPath(g,SOURCE);
DRETURN;
}
<file_sep>/cpp/POJ/include/GRAPH.class.cpp
#include <map>
#include <iostream>
#include <vector>
#include "include.top.h"
#include "GRAPH.class.h"
using namespace std;
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::GRAPH(unsigned nodeCnt,Edge<TYPE_OF_WEIGHT> defaultEdge){
//vector<vector <Edge<TYPE_OF_WEIGHT>>> mat;
mNodeCnt=nodeCnt;
for(int i=0;i<nodeCnt;i++)
{
vector <Edge<TYPE_OF_WEIGHT>> tmp;
for(int j=0;j<nodeCnt;j++)
{
//mat[i][j]=defaultEdge;
tmp.push_back(defaultEdge);
//PRINTVAR(i);
//PRINTVAR(j);
//defaultEdge.show();
}
mat.push_back(tmp);
}
PRINTVAR(mat.size());
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
void GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::addEdge(TYPE_OF_NODE* from,TYPE_OF_NODE* to,Edge<TYPE_OF_WEIGHT> edge){
PRINT_DEBUG_INFO();
if(!isExistNode(from))
{
PRINT_DEBUG_INFO();
PRINTVAR(*from);
PRINTVAR(from);
auto newId=getNewId();
MAP_name2id[from]=newId;
MAP_id2name[newId]=from;
PRINTVAR(from);
PRINTVAR(newId);
}
else
{
from=getNodeByName(*from);
}
if(!isExistNode(to))
{
PRINT_DEBUG_INFO();
PRINTVAR(*to);
PRINTVAR(to);
auto newId=getNewId();
MAP_name2id[to]=newId;
MAP_id2name[newId]=to;
PRINTVAR(to);
PRINTVAR(newId);
}
else
{
to=getNodeByName(*to);
}
PRINT_DEBUG_INFO();
std::cout<<"-------------------------------"<<std::endl;
std::cout<<"addEdge:"<<from
<<"("<<MAP_name2id[from]<<"),"
<<to
<<"("<<MAP_name2id[to]<<")"
<<std::endl;
edge.show();
std::cout<<"-------------------------------"<<std::endl;
PRINT_DEBUG_INFO();
assert(from);
assert(to);
PRINT_DEBUG_INFO();
if(MAP_name2id[from])
PRINTVAR(MAP_name2id[from]);
PRINT_DEBUG_INFO();
if(MAP_name2id[to])
PRINTVAR(MAP_name2id[to]);
PRINT_DEBUG_INFO();
mat[MAP_name2id[from]][MAP_name2id[to]]=edge;
PRINT_DEBUG_INFO();
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
Edge<TYPE_OF_WEIGHT> GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::getEdge(TYPE_OF_NODE* from,TYPE_OF_NODE* to){
if(!isExistNode(from))
return 0;
if(!isExistNode(to))
return 0;
return mat[MAP_name2id[from]][MAP_name2id[to]];
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
unsigned GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::getNewId(){
unsigned id=0;
while(isExistId(id))
{
id++;
}
return id;
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
void GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::show(){
std::cout<<"-------------------------------"<<std::endl;
std::cout<<"MAP_id2name"<<std::endl;
for(auto id2name:MAP_id2name)
{
//PRINTVAR(id2name.first);
//PRINTVAR(id2name.second);
std::cout<<id2name.first<<"->"<<id2name.second<<std::endl;
}
std::cout<<"-------------------------------"<<std::endl;
std::cout<<"MAP_name2id"<<std::endl;
for(auto name2id:MAP_name2id)
{
//PRINTVAR(name2id.first);
//PRINTVAR(name2id.second);
std::cout<<name2id.first<<"->"<<name2id.second<<std::endl;
}
std::cout<<"-------------------------------"<<std::endl;
showWeight();
showR();
showC();
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
void GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::showWeight()
{
std::cout<<"-------------------------------"<<std::endl;
std::cout<<"showWeight()"<<std::endl;
//
cout<<"\t";
for(int j=0;j<mNodeCnt;j++)
{
cout<<MAP_id2name[j]<<"\t";
}
cout<<endl;
//
for(int i=0;i<mNodeCnt;i++)
{
cout<<MAP_id2name[i]<<"\t";
for(int j=0;j<mNodeCnt;j++)
{
auto cell=mat[i][j];
cout<<cell.getWeight()<<"\t";
}
cout<<endl;
}
std::cout<<"-------------------------------"<<std::endl;
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
void GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::showR()
{
std::cout<<"-------------------------------"<<std::endl;
std::cout<<"showRate()"<<std::endl;
//
cout<<"\t";
for(int j=0;j<mNodeCnt;j++)
{
cout<<MAP_id2name[j]<<"\t";
}
cout<<endl;
//
for(int i=0;i<mNodeCnt;i++)
{
cout<<MAP_id2name[i]<<"\t";
for(int j=0;j<mNodeCnt;j++)
{
auto cell=mat[i][j];
cout<<cell.getR()<<"\t";
}
cout<<endl;
}
std::cout<<"-------------------------------"<<std::endl;
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
void GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::showC()
{
std::cout<<"-------------------------------"<<std::endl;
std::cout<<"showCommission()"<<std::endl;
//
cout<<"\t";
for(int j=0;j<mNodeCnt;j++)
{
cout<<MAP_id2name[j]<<"\t";
}
cout<<endl;
//
for(int i=0;i<mNodeCnt;i++)
{
cout<<MAP_id2name[i]<<"\t";
for(int j=0;j<mNodeCnt;j++)
{
auto cell=mat[i][j];
cout<<cell.getC()<<"\t";
}
cout<<endl;
}
std::cout<<"-------------------------------"<<std::endl;
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
vector<unsigned> GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::getChildIdList(unsigned nodeId)
{
vector<unsigned> r;
unsigned toId=0;
for(auto edge:mat[nodeId])
{
if(edge.getWeight()>0)
r.push_back(toId);
toId++;
}
cout<<"getChildIdList("<<nodeId<<")=\t";
PRINT_VECTOR_hor(r);
return r;
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
vector<unsigned> GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::getParentIdList(unsigned nodeId)
{
vector<unsigned> r;
unsigned j=0;
for(int fromId=0;fromId<mNodeCnt;fromId++)
{
for(int toId=0;toId<mNodeCnt;toId++)
{
TYPE_OF_WEIGHT weight=mat[fromId][toId].getWeight();
if(toId==nodeId && weight>0)
r.push_back(fromId);
}
}
PRINT_VECTOR_hor(r);
return r;
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
void GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::traverseDFS(TYPE_OF_NODE* fromNode,void (*func)(TYPE_OF_NODE*))
{
vector<unsigned> visitedList; // store as id
//map<unsigned,unsigned> MAP_nodeId2color_DFS; // map id2color 0:white,1:grey,2:black;
// init
for(int u=0;u<mNodeCnt;u++)
{
MAP_nodeId2color_DFS[u]=COLOR_WHITE; // mark all white
MAP_id2DFSparent[u]=NIL;
MAP_id2DFSdepth_grey[u]=NIL;
MAP_id2DFSdepth_black[u]=NIL;
}
DFSvisitTime=0;
//
traverseDFS_recur(fromNode,&visitedList,func);
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
void GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::traverseDFS_recur(TYPE_OF_NODE* curNode,
vector<unsigned>* ptr_visitedList,
void (*func)(TYPE_OF_NODE*)
)
{
PRINT_MAP(MAP_nodeId2color_DFS);
unsigned curId=MAP_name2id[curNode];
cout<<"calling traverseDFS_recur("<<curId<<")"<<endl;
vector<unsigned> visitedList =*ptr_visitedList;
visitStack_DFS.push_back(curId);
MAP_nodeId2color_DFS[curId]=COLOR_GREY;
MAP_id2DFSdepth_grey[curId]=DFSvisitTime;
vector<unsigned> childList=getChildIdList(curId);
for(auto id:childList)
{
if(MAP_nodeId2color_DFS[id]!=COLOR_GREY)
{
MAP_id2DFSparent[id]=curId;
DFSvisitTime++;
traverseDFS_recur(getNodeById(id),ptr_visitedList,func);
}
}
MAP_nodeId2color_DFS[curId]=COLOR_BLACK;
DFSvisitTime++;
MAP_id2DFSdepth_black[curId]=DFSvisitTime;
PRINT_MAP(MAP_nodeId2color_DFS);
PRINT_MAP(MAP_id2DFSparent);
PRINT_MAP(MAP_id2DFSdepth_grey);
PRINT_MAP(MAP_id2DFSdepth_black);
PRINT_VECTOR_hor(visitStack_DFS);
assert(visitStack_DFS.back()==curId);
visitStack_DFS.pop_back();
};
// FUNC
template <typename TYPE_OF_NODE,typename TYPE_OF_WEIGHT>
void GRAPH<TYPE_OF_NODE,TYPE_OF_WEIGHT>::traverseBFS(TYPE_OF_NODE* fromNode,void (*func)(TYPE_OF_NODE*))
{
//vector<unsigned> visitedList; // store as id
map<unsigned,unsigned> MAP_nodeId2color; // map id2color 0:white,1:grey,2:black;
std::deque<unsigned> queue;
//---------------------
// init color/depth/parent
for(auto pair:MAP_id2name)
{
MAP_nodeId2color[pair.first]=COLOR_WHITE;
MAP_id2BFSdepth [pair.first]=NIL;
MAP_id2BFSparent[pair.first]=NIL;
}
//---------------------
//---------------------
// root node
TYPE_OF_NODE* curNode=fromNode;
unsigned curId=MAP_name2id[curNode];
PRINTVAR(curId);
MAP_id2BFSdepth[curId]=0;
MAP_id2BFSparent[curId]=NIL;
queue.clear();
cout<<"qpush "<<curId<<endl;
queue.push_back(curId);
//---------------------
while(queue.size()!=0)
{
//---------------------
// show queue
PRINTVAR(queue.size());
for (std::deque<unsigned>::iterator it = queue.begin(); it!=queue.end(); ++it)
std::cout << " q" << *it;
cout<<endl;
//---------------------
curId=queue.front();
queue.pop_front();
PRINTVAR(curId);
curNode=MAP_id2name[curId];
cout<<"qpop "<<curId<<endl;
// visit
//PRINT_DEBUG_INFO();
//PRINTVAR_hor(curId);
//PRINTVAR(MAP_nodeId2color[curId]);
//if(MAP_nodeId2color[curId]!=COLOR_WHITE)
//{
// continue;
//}
//MAP_nodeId2color[curId]=COLOR_GREY;
//visitedList.push_back(curId);
//---------------------
// do some thing
if(func)
func(curNode);
//---------------------
//---------------------
// store child
//
vector<unsigned> childList=getChildIdList(curId);
//
for(unsigned c:childList)
{
if(MAP_nodeId2color[c]==COLOR_WHITE)
{
MAP_nodeId2color[c]=COLOR_GREY;
MAP_id2BFSdepth[c] =MAP_id2BFSdepth[curId]+1;
MAP_id2BFSparent[c]=curId;
queue.push_back(c);
cout<<"qpush "<<c<<endl;
}
}
MAP_nodeId2color[curId]=COLOR_BLACK;
}
};
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch1_life_game/src/life.cpp
#include <utility.h>
#include <life.h>
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <stdio.h>
#include <string>
using namespace std;
Life::Life(int w, int h) {
width=w;
height=h;
cout_table_width=3;
origin_col=1;
origin_row=1;
big_col=w-1;
big_row=h-1;
SHOW_WIDTH=big_col-origin_col;
SHOW_HEIGHT=big_row-origin_row;
init();
}
void Life::make_live(int show_col, int show_row) {
matrix[origin_col+show_col][origin_row+show_row]=1;
}
void Life::make_dead(int show_col, int show_row) {
matrix[origin_col+show_col][origin_row+show_row]=0;
}
void Life::init() {
cout<<"calling Life::init()"<<endl;
}
int Life::calc_neighbour_cnt (int show_col, int show_row) {
//cout<<"calling Life::calc_neighbour_cnt("<<show_col<<","<<show_row<<")"<<endl;
int cnt=0;
for (int i=show_col-1;i<=show_col+1;i++){
for (int j=show_row-1;j<=show_row+1;j++){
if (j==show_row&&i==show_col) {continue;}
if (matrix[origin_col+i][origin_row+j] ) {
cnt++;
}
}
}
//cout<<"calling Life::calc_neighbour_cnt return "<<cnt<<endl;
neighbour_cnt[origin_col+show_col][origin_row+show_row]=cnt;
return cnt;
}
void Life::update_neighbour_cnt() {
// calc:
cout<<"calling Life::update_neighbour_cnt()"<<endl;
printf("%d,%d\n",SHOW_HEIGHT,SHOW_WIDTH);
for (int r=0;r<SHOW_HEIGHT;r++){
for (int c=0;c<SHOW_WIDTH;c++){
int nc=calc_neighbour_cnt(c,r);
//cout<<"calling Life::update_neighbour_cnt ("<<c<<","<<r<<") ="<<nc<<endl;
}
}
//cout<<"return of Life::update_neighbour_cnt()"<<endl;
}
void Life::update() {
cout<<"calling Life::update()"<<endl;
update_neighbour_cnt();
// update live or dead:
SHOW_WIDTH=big_col-origin_col;
SHOW_HEIGHT=big_row-origin_row;
for (int r=0;r<SHOW_HEIGHT;r++){
for (int c=0;c<SHOW_WIDTH;c++){
int curr_neighbour_cnt=neighbour_cnt[origin_col+c][origin_row+r];
if (curr_neighbour_cnt==3) {
make_live(c,r);
} else if (curr_neighbour_cnt==2 && matrix[origin_col+c][origin_row+r]) {
make_live(c,r);
} else {
make_dead(c,r);
}
}
}
// calc:
for (int r=0;r<SHOW_HEIGHT;r++){
for (int c=0;c<SHOW_WIDTH;c++){
calc_neighbour_cnt(c,r);
}
}
}
void Life::show() {
cout<<"calling Life::show()"<<endl;
cout<<setw(cout_table_width)<<"";
cout<<setw(cout_table_width)<<"Cl=";
for (int i=origin_col;i<big_col;i++){
cout<<setw(cout_table_width)<<i-1;
}
cout<<endl;
for (int j=origin_row;j<big_row;j++){
cout<<setw(cout_table_width)<<"Rw="<<setw(cout_table_width)<<j-1;
for (int i=origin_col;i<big_col;i++){
char c;
if (matrix[i][j]) {
c='*';
} else {c=' ';}
cout<<setw(cout_table_width)<<c;
}
cout<<endl;
}
}
void Life::show_neighbour_cnt() {
cout<<"calling Life::show_neighbour_cnt()"<<endl;
update_neighbour_cnt();
cout<<setw(cout_table_width)<<"";
cout<<setw(cout_table_width)<<"Cl=";
for (int i=-1;i<SHOW_WIDTH;i++){
cout<<setw(cout_table_width)<<i;
}
cout<<endl;
for (int j=-1;j<SHOW_HEIGHT;j++){
cout<<setw(cout_table_width)<<"Rw="<<setw(cout_table_width)<<j;
for (int i=-1;i<SHOW_WIDTH;i++){
string s;
int curr_neighbour_cnt=neighbour_cnt[origin_col+i][origin_row+j];
if(curr_neighbour_cnt==0) {
s="";
} else {
char temp[3];
sprintf(temp,"%d",curr_neighbour_cnt);
string s1(temp);
s=s1.c_str();
}
cout<<setw(cout_table_width)<<s;
}
cout<<endl;
}
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/src/4.7.cpp
#include <stdio.h>
#include <math.h>
#include <iostream>
#include "4.7.h"
#include "lib.h"
using namespace std;
int f4_7 (double a=2) {
time_t timer;
struct tm *tblock;
timer=time(NULL);
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
////////////////////////////////////////////////
double after=10;
double before;
for (int ans=1;ans<=10000;ans++) {
before=after;
after=0.5*(before+a/before);
double diff=fabs(before-after);
cout<<"diff="<<diff<<endl;
if (fabs(diff)<1e-19) {
break;
}
}
cout<<a<<"^0.5="<<after<<endl;
////////////////////////////////////////////////
tblock=localtime(&timer);
cout<<asctime(tblock)<<endl;
//cout<<(int)tblock<<endl;
return 0;
}
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/20.1.h
void f20_1();
<file_sep>/cpp/2_BOOK_CPP_Program_Design_QianNeng/include/9.1.h
//int f9_1();
//void findmax_use_ptr(int*a,int n, int i, int*pk);
//void findmax_use_ref(int(&a)[10],int n, int i, int&pk);
<file_sep>/cpp/exe_game/tetris/Shape.class.cpp
#include "global.h"
#include "Shape.class.h"
#include "Matrix.class.h"
using namespace std;
//Shape::Shape(unsigned height,unsigned width,string v){}
Shape::Shape(vector<vector<string> > m){
steady=false;
}
Shape::Shape(int w_board,int h_board,int t,string ori)
{
width_board=w_board;
height_board=h_board;
ul_row=0;
ul_col=0;
type=t;
assert(type<7);
assert(type>-1);
orientation=ori;
steady=false;
}
//bool Shape::touchToShape(Shape* another)
//{
//return false;
//}
int Shape::getWidthN() {
if(!legalType())
return 0;
switch(type)
{
case 0:
return 4;
break;
case 1:
return 2;
break;
default:
return 3;
}
};
int Shape::getHeightN() {
if(!legalType())
return 0;
switch(type)
{
case 0:
return 1;
break;
default:
return 2;
}
};
int Shape::getWidth() {
if(orientation=="N")
return getWidthN();
if(orientation=="S")
return getWidthN();
if(orientation=="E")
return getHeightN();
if(orientation=="W")
return getHeightN();
return 0;
}
int Shape::getHeight() {
if(orientation=="N")
return getHeightN();
if(orientation=="S")
return getHeightN();
if(orientation=="E")
return getWidthN();
if(orientation=="W")
return getWidthN();
return 0;
}
bool Shape::legalType()
{
if(type <0)
return false;
if(type >6)
return false;
return true;
};
void Shape::setDots()
{
assert(type<7);
assert(type>-1);
switch(type)
{
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
default:
;
//return 0;
}
}
vector<Point*> Shape::getDots() // return {P1,P2,...Pn}
{
return dots;
}
vector<Point> Shape::getBorder() // return {{ul_row,ul_col}, {drx,dry}}
{
Point P_ul(ul_row,ul_col);
Point P_dr(ul_row+getWidth(),ul_col+getHeight());
vector<Point> r;
r.push_back(P_ul);
r.push_back(P_dr);
return r;
}
void Shape::initShapeFaceToN(int type)
{
switch(type)
{
case 0:
dots.push_back(new Point(0,0));
dots.push_back(new Point(0,1));
dots.push_back(new Point(0,2));
dots.push_back(new Point(0,3));
break;
case 1:
dots.push_back(new Point(0,0));
dots.push_back(new Point(0,1));
dots.push_back(new Point(1,1));
dots.push_back(new Point(1,0));
break;
case 2:
dots.push_back(new Point(0,0));
dots.push_back(new Point(0,1));
dots.push_back(new Point(1,1));
dots.push_back(new Point(1,2));
break;
case 3:
dots.push_back(new Point(0,1));
dots.push_back(new Point(0,2));
dots.push_back(new Point(1,0));
dots.push_back(new Point(1,1));
break;
case 4:
dots.push_back(new Point(0,1));
dots.push_back(new Point(1,0));
dots.push_back(new Point(1,1));
dots.push_back(new Point(1,2));
break;
case 5:
dots.push_back(new Point(0,0));
dots.push_back(new Point(1,0));
dots.push_back(new Point(1,1));
dots.push_back(new Point(1,2));
break;
case 6:
dots.push_back(new Point(0,2));
dots.push_back(new Point(1,0));
dots.push_back(new Point(1,1));
dots.push_back(new Point(1,2));
break;
}
}
void Shape::init()
{
// apply type
//dots.clear();
initShapeFaceToN(type);
//if(orientation=="E")
//if(orientation=="W")
//if(orientation=="S")
}
void Shape::update_ul()
{
ul_row=99999;
ul_col=99999;
for(Point* d:dots)
{
//PRINTVAR_hor(d->x);
//PRINTVAR_hor(d->y);
//cout<<""<<""<<endl;
if(d->x<ul_row)
ul_row=d->x;
if(d->y<ul_col)
ul_col=d->y;
}
PRINTVAR_hor(ul_row);
PRINTVAR_hor(ul_col);
cout<<""<<""<<endl;
}
void Shape::update()
{
// apply orientation
// apply ul_row,ul_col
update_ul();
// apply dotsMostN, E,W,S
dotsMostN.clear();
dotsMostE.clear();
dotsMostW.clear();
dotsMostS.clear();
findTheMost("N");
findTheMost("E");
findTheMost("W");
findTheMost("S");
}
void Shape::move(string orientation,unsigned times)
{
cout<<"***MOVE:"<<orientation<<" x "<<times<<endl;
while(times!=0)
{
move(orientation);
times--;
}
cout<<"***END MOVE:"<<orientation<<" x "<<times<<endl;
}
void Shape::move(string orientation)
{
cout<<"--------------"<<""<<endl;
cout<<"BEFORE MOVE:"<<""<<endl;
for(Point* d:dots)
{
PRINTVAR_hor(d->x);
PRINTVAR_hor(d->y);
cout<<""<<""<<endl;
}
cout<<"--------------"<<""<<endl;
PRINT_DEBUG_INFO_PREFIX(orientation);
if(orientation=="S")
{
//drop();
drop();
}
else if(orientation=="E")
{
if(hit("E"))
return;
if(hitInMatrix("E"))
return;
PRINT_DEBUG_INFO_PREFIX("can move E");
for(Point* d:dots)
{
d->y++;
}
}
else if(orientation=="W")
{
if(hit("W"))
return;
if(hitInMatrix("W"))
return;
PRINT_DEBUG_INFO_PREFIX("can move W");
for(Point* d:dots)
{
d->y--;
}
}
else if(orientation=="N")
{
if(hit("N"))
return;
if(hitInMatrix("N"))
return;
PRINT_DEBUG_INFO_PREFIX("can move N");
for(Point* d:dots)
{
d->x--;
}
}
cout<<"--------------"<<""<<endl;
cout<<"AFTER MOVE:"<<""<<endl;
for(Point* d:dots)
{
PRINTVAR_hor(d->x);
PRINTVAR_hor(d->y);
cout<<""<<""<<endl;
}
cout<<"--------------"<<""<<endl;
PRINT_DEBUG_INFO();
update_ul();
dotsMostN.clear();
dotsMostE.clear();
dotsMostW.clear();
dotsMostS.clear();
}
bool Shape::drop()
{
PRINT_DEBUG_INFO_PREFIX("DROP");
//if(hit_bottom())
if(hit("S"))
return false;
if(hitInMatrix("S"))
return false;
for(Point* d:dots)
{
d->x++;
}
return true;
}
void Shape::turn(string left_or_right)
{
PRINT_DEBUG_INFO_PREFIX(left_or_right);
vector<Point*> new_dots;
//string flag_out_of_border="";
//PRINTVAR(flag_out_of_border);
if(left_or_right=="left")
{
for(Point* p:dots)
{
int dx=p->x-ul_row;
int dy=p->y-ul_col;
int newdx=3-dy;
int newdy=dx;
int newx=ul_row+newdx;
int newy=ul_col+newdy;
PRINTVAR_hor(newx);
PRINTVAR_hor(newy);
cout<<""<<""<<endl;
// if(newx<0)
// flag_out_of_border="N";;
// if(newy<0)
// flag_out_of_border="W";;
// if(newx>height_board)
// flag_out_of_border="S";;
// if(newy>width_board)
// flag_out_of_border="E";;
//assert(newx>=0);
//assert(newy>=0);
new_dots.push_back(new Point(newx,newy));
}
vector<Point*> dots_bk=dots;
dots=new_dots;
if(contain())
dots=dots_bk;
else
{
if(hit_depth("E")>0)
move("W",hit_depth("E")+1);
if(hit_depth("W")>0)
move("E",hit_depth("W")+1);
if(hit_depth("S")>0)
move("N",hit_depth("S")+1);
}
}
//PRINTVAR(flag_out_of_border);
if(left_or_right=="right")
{
for(Point* p:dots)
{
int dx=p->x-ul_row;
int dy=p->y-ul_col;
int newdx=dy;
int newdy=3-dx;
int newx=ul_row+newdx;
int newy=ul_col+newdy;
PRINTVAR_hor(ul_row);
PRINTVAR_hor(ul_col);
PRINTVAR_hor(dx);
PRINTVAR_hor(dy);
PRINTVAR_hor(newdx);
PRINTVAR_hor(newdy);
PRINTVAR_hor(newx);
PRINTVAR_hor(newy);
cout<<""<<""<<endl;
//assert(newdx>=0);
//assert(newdy>=0);
cout<<""<<""<<endl;
//if(newx<0)
// flag_out_of_border="N";;
//if(newy<0)
// flag_out_of_border="W";;
//if(newx>height_board)
// flag_out_of_border="S";;
//if(newy>width_board)
// flag_out_of_border="E";;
new_dots.push_back(new Point(newx,newy));
}
vector<Point*> dots_bk=dots;
dots=new_dots;
if(contain())
{
PRINT_DEBUG_INFO();
dots=dots_bk;
;
}
else
{
PRINT_DEBUG_INFO();
if(hit_depth("E")>0)
move("W",hit_depth("E"));
if(hit_depth("W")>0)
move("E",hit_depth("W"));
if(hit_depth("S")>0)
move("N",hit_depth("S"));
}
}
PRINTVAR_hor(height_board);
PRINTVAR_hor(width_board);
//PRINTVAR(flag_out_of_border);
//dots.clear();
/*
if(flag_out_of_border=="") // succeed
{
dots=new_dots;
if(left_or_right=="left")
{
if(orientation=="N")
orientation="E";
if(orientation=="E")
orientation="S";
if(orientation=="W")
orientation="N";
if(orientation=="S")
orientation="W";
}
if(left_or_right=="right")
{
if(orientation=="N")
orientation="E";
if(orientation=="E")
orientation="S";
if(orientation=="W")
orientation="N";
if(orientation=="S")
orientation="W";
}
}
else
{
if(flag_out_of_border=="N")
{
cout<<"OOB N"<<endl;
move("S");
PRINT_DEBUG_INFO();
}
if(flag_out_of_border=="E")
{
cout<<"OOB E"<<endl;
move("W");
PRINT_DEBUG_INFO();
}
if(flag_out_of_border=="W")
{
cout<<"OOB W"<<endl;
move("E");
PRINT_DEBUG_INFO();
}
if(flag_out_of_border=="S")
{
cout<<"OOB S"<<endl;
move("N");
PRINT_DEBUG_INFO();
}
//turn(left_or_right);
}
*/
PRINT_DEBUG_INFO();
}
void Shape::showVector(vector<Point*>* vecPtr)
{
cout<<"==============="<<""<<endl;
cout<<"showVector @"<<vecPtr<<" :"<<endl;
for(auto pptr:*vecPtr)
{
cout<<""<<*pptr<<"\t@"<<pptr<<endl;
}
cout<<"==============="<<""<<endl;
}
void Shape::deleteFromVector(vector<Point*>* vecPtr, Point* item)
{
auto vec=*vecPtr;
int size=vec.size();
int cntr=0;
for (auto iter=vecPtr->begin();iter!=vecPtr->end();)
{
Point* t=*iter; // t is Point*
//int ind=t.transformIsCombined(unit_transforms_wo_zeros);
if (t==item)
{
//cout<<"erase Point: ("<<item->x<<","<<item->y<<")"<<endl;
//vec.erase(iter); // delete the combined transform
vecPtr->erase(iter);
size=vecPtr->size();
}
else
{
iter++;
}
cntr++;
}
}
vector<Point*> Shape::findTheMost(string orientation)
{
//cout<<"calling Shape::findTheMost "<<orientation<<""<<endl;
vector<Point*> r0;
// CACHE:
//if(orientation=="N") {r0=dotsMostN;}
//if(orientation=="E") {r0=dotsMostE;}
//if(orientation=="W") {r0=dotsMostW;}
//if(orientation=="S") {r0=dotsMostS;}
//if(r0.size()!=0) {
// showVector(&r0);
// return r0;
//}
dotsMostN=dots;
dotsMostE=dots;
dotsMostW=dots;
dotsMostS=dots;
for(Point* p1:dots)
{
for(Point* p2:dots)
{
if(p1==p2)
continue;
if(p1->x == p2->x) // same row
{
if(p1->y +1== p2->y )
{
deleteFromVector(&dotsMostE,p1);
deleteFromVector(&dotsMostW,p2);
}
}
if(p1->y == p2->y) // same col
{
if(p1->x +1== p2->x )
{
deleteFromVector(&dotsMostS,p1);
deleteFromVector(&dotsMostN,p2);
}
}
}
}
vector<Point*> r;
if(orientation=="N") {r=dotsMostN;}
if(orientation=="E") {r=dotsMostE;}
if(orientation=="W") {r=dotsMostW;}
if(orientation=="S") {r=dotsMostS;}
//cout<<"Shape::findTheMost "<<orientation<<" return:"<<endl;
//showVector(&r);
return r;
}
bool Shape::hit(string orientation)
{
string to=orientation;
for(auto p:findTheMost(to))
{
if(to=="W"&& p->y==0)
{
cout<<"hit W"<<""<<endl;
//PRINTVAR_hor(p->y);
return true;
}
if(to=="E"&& width_board-p->y==1)
{
//PRINTVAR_hor(width_board);
//PRINTVAR_hor(p->y);
cout<<"hit E"<<""<<endl;
return true;
}
if(to=="S"&& height_board-p->x==1)
{
cout<<"hit S"<<""<<endl;
return true;
}
}
return false;
}
int Shape::hit_depth(string orientation)
{
//PRINT_DEBUG_INFO_PREFIX("HIT ");
//PRINTVAR(orientation);
string to=orientation;
int depth=-1; // means not hit
// depth =0 means touch the border
// depth >0 means out of border
for(auto p:findTheMost(to))
{
if(to=="W"&& p->y<=0)
{
cout<<"hit W"<<""<<endl;
//PRINTVAR_hor(p->y);
depth=-p->y;
//PRINTVAR_hor(depth);
cout<<""<<""<<endl;
return depth;
}
if(to=="E"&& width_board-p->y<=1)
{
//PRINTVAR_hor(width_board);
//PRINTVAR_hor(p->y);
cout<<"hit E"<<""<<endl;
depth=p->y-width_board+1;
//PRINTVAR_hor(depth);
cout<<""<<""<<endl;
return depth;
}
if(to=="S"&& height_board-p->x<=1)
{
cout<<"hit S"<<""<<endl;
depth=p->x-height_board+1;
//PRINTVAR_hor(depth);
cout<<""<<""<<endl;
return depth;
}
}
//PRINTVAR_hor(depth);
cout<<""<<""<<endl;
return depth;
}
bool Shape::hit_bottom()
{
string to="S";
for(auto p:findTheMost(to))
{
int u= height_board-p->x;
if(u ==1)
{
cout<<"hit S"<<""<<endl;
return true;
}
}
return false;
}
bool Shape::contain(Point* pother)
{
//PRINT_DEBUG_INFO();
for(Point* p1:dots)
{
//PRINTVAR_hor(*p1);
//PRINTVAR_hor(*pother);
if(p1->x==pother->x &&
p1->y==pother->y)
{
//PRINT_DEBUG_INFO_PREFIX("TRUE!");
return true;
}
}
//PRINT_DEBUG_INFO_PREFIX("FALSE!");
return false;
}
bool Shape::contain(Shape* other)
{
//PRINT_DEBUG_INFO();
for(Point* pother:other->getDots())
{
if(contain(pother))
return true;
}
return false;
}
bool Shape::contain()
{
//PRINT_DEBUG_INFO();
Matrix* m=(Matrix*)mat;
for(Shape* one_shape:m->getShapeList())
{
if(one_shape==this)
continue;
if(contain(one_shape))
return true;
}
return false;
}
bool Shape::hit(Point* pother,string to)
{
//PRINT_DEBUG_INFO_PREFIX("JUDGE HIT SHAPE VS POINT");
//PRINTVAR_hor(this);
//PRINTVAR_hor(pother);
// foreach dot findTheMost(S), if dot is up neighbor of p, return S
//string to="S";
assert(!contain(pother));
#if 0
for(auto p:findTheMost(to))
{
if(p->y>=height_board)
{
cout<<"hit S"<<""<<endl;
return "S";
}
}
#endif
for(Point* p1:dots)
{
//PRINT_DEBUG_INFO_PREFIX("JUDGE HIT POINTS");
//PRINTVAR_hor(p1);
//PRINTVAR_hor(pother);
//PRINTVAR_hor(*p1);
//PRINTVAR_hor(*pother);
//PRINTVAR(to);
if((to=="E") && (p1->x==pother->x) && (p1->y+1==pother->y))
return true;
if((to=="W") && (p1->x==pother->x) && (p1->y-1==pother->y))
return true;
if((to=="S") && (p1->x+1==pother->x) && (p1->y==pother->y))
return true;
if((to=="N") && (p1->x-1==pother->x) && (p1->y==pother->y))
return true;
}
return false;
// foreach dot findTheMost(W), if dot is up neighbor of p, return W
// foreach dot findTheMost(E), if dot is up neighbor of p, return E
}
bool Shape::hit(Shape* other,string to)
{
//PRINT_DEBUG_INFO_PREFIX("JUDGE HIT SHAPE");
//PRINTVAR_hor(this);
//PRINTVAR_hor(other);
for(Point* pother:other->getDots())
{
assert(!contain(pother));
bool hitOtherShape=hit(pother,to);
//PRINT_DEBUG_INFO_PREFIX("=============================================");
//PRINTVAR_hor(to);
//PRINTVAR(hitOtherShape);
//PRINT_DEBUG_INFO_PREFIX("=============================================");
if(hitOtherShape)
{
return true;
}
}
return false;
}
bool Shape::hitInMatrix(string to)
{
//PRINT_DEBUG_INFO();
Matrix* m=(Matrix*)mat;
for(Shape* one_shape:m->getShapeList())
{
if(one_shape==this)
continue;
if(hit(one_shape,to))
{
PRINT_DEBUG_INFO_PREFIX("HIT IN MAT!!!!!!!!!!!!!!!!!!!!!!!!");
return true;
}
}
PRINT_DEBUG_INFO_PREFIX("NOT HIT----------------------");
return false;
}
void Shape::cleanRow(int row)
{
PRINT_DEBUG_INFO();
PRINTVAR(*this);
if(!steady)
return;
for (auto iter=dots.begin();iter!=dots.end();)
{
Point* p=*iter;
cout<<"Point: ("<<p->x<<","<<p->y<<") is under checking"<<""<<endl;
if(p->x==row)
{
cout<<"Point: ("<<p->x<<","<<p->y<<") is to be deleted!"<<""<<endl;
deleteFromVector(&dots,p);
}
else
{
iter++;
}
}
PRINT_DEBUG_INFO();
}
<file_sep>/cpp/exe_TSP/s.cpp
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define DLOG(a) PRINTVAR(a);
#define DENTER std::cout<<" -->"<<__PRETTY_FUNCTION__<<std::endl;
#define DRETURN std::cout<<"<-- "<<__PRETTY_FUNCTION__<<std::endl;
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<"VEC:\t"<<#a<<"="<<*u<<std::endl;}
#define PRINT_VECTOR_hor(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
//#define PRINT_VECTOR_hor(a)
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define DEBUG_MARK PRINT_DEBUG_INFO()
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
#include <vector>
#include <math.h>
#include <string>
#include <iostream>
#include <deque>
#include <assert.h>
#include <limits>
#include <cstdint>
#include <algorithm>
#include <fstream>
#ifndef INT_MAX
#define INT_MAX 999999
#endif
using namespace std;
typedef pair<int,int> POINT;
ostream & operator<<(ostream &os, POINT p)
{
os<<"("<<p.first<<","<<p.second<<")";
}
class Solver
{
private:
vector<pair<int,int>> mData;
vector<int> mAnsInd;
vector<int> mVisitedInd;
//int startInd;
public:
// FOR Points:
double sqr(double x) {return x*x;};
double getDistance(POINT p1,POINT p2);
double getDistanceSum(vector<POINT> v);
double getDistanceSum(vector<int> v);
//Solver(string fname);
Solver();
friend std::ostream& operator<< (std::ostream& o_os,Solver sol)
{
//cout<<"-----------------------------------"<<endl;
//for(auto p:sol.getData())
//{
// o_os<<p.first<<","<< p.second<<endl;
//}
//cout<<"-----------------------------------"<<endl;
sol.show(sol.getData(),o_os);
return o_os;
};
void dump(string fname);
void read(string fname);
vector<pair<int,int>> getData() {return mData;};
void genRandomData(int cntNodes);
void solveNearest() ;
int getNearestPointInd(POINT p0) ;
void show(vector<pair<int,int>> v,std::ostream& o_os=std::cout)
{
cout<<"-----------------------------------"<<endl;
for(auto p:v)
{
o_os<<p.first<<","<< p.second<<endl;
}
cout<<"-----------------------------------"<<endl;
}
void show(vector<int> vInd,std::ostream& o_os=std::cout) // show by Index
{
cout<<"-----------------------------------"<<endl;
for(auto i:vInd)
{
auto p=mData[i];
o_os<<p.first<<","<< p.second<<endl;
}
cout<<"-----------------------------------"<<endl;
}
};
void Solver::read(string fname)
{
string filename=fname;
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
std::cout << "parsing " << filename << " ...\n";
mData={};
int a, b;
int sum;
while (infile >> a >> b)
{
mData.push_back(make_pair(a,b));
}
}
void Solver::dump(string fname)
{
string filename_out=fname;
std::ofstream outfile(filename_out);
if (!outfile)
std::cerr << "Couldn't open " << filename_out << " for writing\n";
std::cout << "dumping " << filename_out << " ...\n";
for(auto i:mAnsInd)
{
auto p=mData[i];
outfile<<p.first<<" "<< p.second<<endl;
}
}
void Solver::genRandomData(int cntNodes)
{
int i=cntNodes;
while(i>0)
{
srand(time(NULL)+i);
int x=rand()%100;
int y=rand()%100;
auto p=make_pair(x,y);
mData.push_back(p);
//DLOG(x);
//DLOG(y);
i--;
}
}
double Solver::getDistance(POINT p1,POINT p2)
{
//DENTER;
//DLOG(p1);
//DLOG(p2);
double r;
double x1=p1.first;
double x2=p2.first;
double y1=p1.second;
double y2=p2.second;
r=pow((sqr(x1-x2)+sqr(y1-y2)),0.5);
//DLOG(r);
//DRETURN;
return r;
}
double Solver::getDistanceSum(vector<POINT> v)
{
double totalDist=0;
for(int ind=0;ind<v.size();ind++)
{
if(ind==0)
continue;
totalDist+=getDistance(v[ind-1],v[ind]);
}
return totalDist;
}
double Solver::getDistanceSum(vector<int> v)
{
//DENTER;
double totalDist=0;
for(int ind=0;ind<v.size();ind++)
{
if(ind==0)
continue;
//DEBUG_MARK;
totalDist+=getDistance(mData[v[ind-1]],mData[v[ind]]);
}
//DLOG(totalDist);
//DRETURN;
return totalDist;
}
Solver::Solver()
{
int CNT_NODES=10;
genRandomData(CNT_NODES);
//startInd=0;
//for(auto p:mData)
//{
// auto orig=make_pair(0,0);
// DLOG(getDistance(orig,p));
//}
DLOG(getDistanceSum(mData));
}
void Solver::solveNearest()
{
mAnsInd={};
show(mAnsInd);
mAnsInd.push_back(0);
mVisitedInd.push_back(0);
while(mVisitedInd.size()<mData.size())
{
int currInd=mAnsInd.back();
auto nearestInd=getNearestPointInd(mData[currInd]);
mAnsInd.push_back(nearestInd);
mVisitedInd.push_back(nearestInd);
}
show(mAnsInd);
DLOG(getDistanceSum(mAnsInd));
}
int Solver::getNearestPointInd(POINT p0)
{
DENTER;
DLOG(p0);
double minDist=INT_MAX;
int minInd=-1;
int ind=-1;
DLOG(mData.size());
for(auto p:mData)
{
ind++;
auto it=std::find(mVisitedInd.begin(),mVisitedInd.end(),ind);
if(it!=mVisitedInd.end())
continue;
double newDist=getDistance(p0,mData[ind]);
//DLOG(newDist);
if(newDist<minDist)
{
minDist=newDist;
minInd=ind;
}
}
DLOG(minDist);
DLOG(minInd);
return minInd;
}
int main ()
{
Solver sol;
cout<<sol<<endl;
sol.solveNearest();
sol.dump("out.nearest.dat");
return 0;
}
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.2_directed_graph/Digraph.cpp
#include "Digraph.h"
Digraph::Digraph()
{
}
Digraph::Digraph(int v)
{
mV=v;
mE=0;
mAdj={};
}
Digraph::Digraph(string fname){
string filename=fname;
std::ifstream infile(filename);
if (!infile)
std::cerr << "Couldn't open " << filename << " for reading\n";
int a, b;
int sum;
int cntLine=0;
while (infile >> a >> b)
{
cntLine++;
DLOG(cntLine);
DLOG(a);
DLOG(b);
if(cntLine==1)
{
mV=a;
mE=0;
mAdj={};
for(int i=0;i<a;i++)
mAdj.push_back({});
}
else
{
addEdge(a,b);
}
}
}
int Digraph::V() { return mV;}
int Digraph::E() { return mE;}
void Digraph::addEdge(int v,int w)
{
DENTER;
DLOG(mAdj.size());
while(mAdj.size()<v+1)
{
mAdj.push_back({});
}
DLOG(mAdj.size());
mAdj[v].push_back(w);
mE++;
DRETURN;
}
vector<int> Digraph::adj(int v) {
//DENTER;
//DLOG(v);
//DLOG(mAdj.size());
if(mAdj.size()<v+1)
{
//DRETURN;
return {};
}
//DRETURN;
return mAdj[v];
}
string Digraph::toString()
{
DENTER;
string s= "";
s+="\n-----------------------------\n";
s+=to_string(V())+" vertices, "+
to_string(E())+"edges\n";
for(int v=0;v<V();v++)
{
s+=to_string(v)+"\t->\t";
auto vv=adj(v);
auto sz= vv.size();
if(sz!=0)
{
for(int w:adj(v))
{
s+=to_string(w)+" ";
}
}
s+="\n";
}
s+="-----------------------------\n";
DRETURN;
return s;
}
Digraph* Digraph::reverse()
{
DENTER;
auto R=new Digraph(V());
DLOG(R->toString());
//DEBUG_MARK;
for(int v=0;v<mV;v++)
{
//DEBUG_MARK;
for(int w:adj(v))
{
//DEBUG_MARK;
DLOG(R);
//DEBUG_MARK;
R->addEdge(w,v);
}
}
DRETURN;
return R;
}
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN_good/src/2.1_linear_list.cpp
#include "include.top.h"
using namespace std;
//===============================================================================
MyList::MyList()
{
int len=0;
m_name="NA";
m_list_length=len;
//m_heap_length=len*2; // use m_heap_length to give a margin in heap for ListInsert, etc.
m_heap_length=10;
m_list_element=new int[m_heap_length] ;
for(int i=len;i<m_heap_length;i++)
{
*(m_list_element+i)=-1;
}
}
//===============================================================================
MyList::MyList(int a[], int len)
{
m_name="NA";
MyList(a,len,"NA");
}
//===============================================================================
MyList::MyList(int a[], int len, string n)
{
//instanceCounterMyList++;
m_name=n;
m_list_length=len;
m_heap_length=len*2; // use m_heap_length to give a margin in heap for ListInsert, etc.
m_list_element=new int[m_heap_length] ;
printf("DEBUG: INIT MyList, m_list_element=%x\n",m_list_element);
cout<<"name is:"<<m_name<<endl;
for(int i=0;i<len;i++)
{
*(m_list_element+i)=a[i];
cout<<"init MyList:"<<*(m_list_element+i)<<endl;
}
for(int i=len;i<m_heap_length;i++) // it's necessary to init the [m_list_length,m_heap_length), or Valgrind checker will release Error because of mem does not initialised.
{
*(m_list_element+i)=-1;
}
}
//===============================================================================
MyList::MyList(MyList& other) //copying construct func
{
printf("DEBUG: calling copying constructor\n");
m_name="COPY_"+other.m_name;
cout<<"name is:"<<m_name<<endl;
int len=other.ListLength();
m_list_length=len;
m_heap_length=len*2; // use m_heap_length to give a margin in heap for ListInsert, etc.
m_list_element=new int[m_heap_length] ;
//printf("THIS=%d\x",this);
printf("DEBUG: m_list_element=%x\n",m_list_element);
for(int i=0;i<len;i++)
{
*(m_list_element+i)=other.GetElem(i);
cout<<"init MyList copy constructor:"<<*(m_list_element+i)<<endl;
}
for(int i=len;i<m_heap_length;i++)
{
*(m_list_element+i)=-1;
}
}
//===============================================================================
MyList & MyList::operator=(MyList& other) //copying construct func
{
if(this==&other)
return *this;
printf("DEBUG: calling operator =\n");
m_name="EQUAL_"+other.m_name;
cout<<"name is:"<<m_name<<endl;
ClearList();
int len=other.ListLength();
m_list_length=len;
m_heap_length=len*2; // use m_heap_length to give a margin in heap for ListInsert, etc.
m_list_element=new int[m_heap_length] ;
//printf("DEBUG: m_list_element=%x\n",m_list_element);
for(int i=0;i<m_heap_length;i++)
{
if (i<m_list_length) {
*(m_list_element+i)=other.GetElem(i);
cout<<"init MyList copy constructor:"<<*(m_list_element+i)<<endl;
} else {
*(m_list_element+i)=-1;
}
}
}
//===============================================================================
MyList::~MyList()
{
delete [] m_list_element;
m_list_element=NULL;
//printf("DEBUG delete: m_list_element=%x\n",m_list_element);
cout<<"DEBUG delete MyList <"<<m_name<<"> m_list_element="<<m_list_element<<endl;
}
//===============================================================================
void MyList::SetName(string n)
{
m_name=n;
}
//===============================================================================
int MyList::ListLength()
{
return m_list_length;
}
//===============================================================================
void MyList::PrintItem(int ind)
{
cout<<"PrintItem("<<ind<<") = ("<<m_list_element+ind<<") "<<*(m_list_element+ind)<<endl;
}
//===============================================================================
void MyList::PrintList(int printLen,bool detailed) // default value setting is only allowed in declaration(h files)
{
int max;
if (printLen==-1) {
max=m_list_length;
} else {
max=printLen;
}
if (detailed) {
cout<<"PrintList details of <"<<m_name<<"> :"<<endl;
for(int i=0;i<max;i++)
{
PrintItem(i);
}
}else {
cout<<"PrintList of <"<<m_name<<"> :"<<endl;
for(int i=0;i<max;i++)
{
cout<<*(m_list_element+i)<<" ";
}
cout<<endl;
}
}
//===============================================================================
void MyList::ClearList()
{
m_list_length=0;
delete [] m_list_element;
m_list_element=NULL;
//printf("DEBUG clear: m_list_element=%d\n",m_list_element);
}
//===============================================================================
bool MyList::ListEmpty()
{
if (m_list_element==NULL) {
return true;
}
if (m_list_length==0) {
return true;
}
return false;
}
//===============================================================================
int MyList::GetElem(int ind)
{
assert (ind<m_list_length) ;
return *(m_list_element+ind);
}
//===============================================================================
void MyList::SetElem(int ind,int value)
{
assert (ind<m_list_length) ;
*(m_list_element+ind)=value;
}
//===============================================================================
int MyList::LocateElem(int e,bool (*compare)(int a,int b)) // notice: the format of function-pointer
{
for(int i=0;i<m_list_length;i++)
{
cout<<"DEBUG: compare "<<*(m_list_element+i)<<","<<e<<endl;
if(compare(*(m_list_element+i),e)){
return i;
}
}
return -1;
}
//===============================================================================
int MyList::PriorElem(int cur_e)
{
cout<<"DEBUG: calling MyList::PriorElem "<<cur_e<<endl;
int ind=LocateElem(cur_e,compare);
if (ind!=0) {
return GetElem(ind-1);
} else {
return NULL;
}
}
//===============================================================================
int MyList::NextElem(int cur_e)
{
cout<<"DEBUG: calling MyList::NextElem "<<cur_e<<endl;
int ind=LocateElem(cur_e,compare);
if (ind!=m_list_length-1) {
return GetElem(ind+1);
} else {
return NULL;
}
}
//===============================================================================
//int MyList::PriorElem(int cur_e)
//{
// int*pre_e;
// cout<<"DEBUG: calling MyList::PriorElem "<<cur_e<<endl;
// if (ListEmpty()) {
// //pre_e=NULL;
// return NULL;
// }
// for(int i=1;i<m_list_length;i++)
// {
// //cout<<"DEBUG: compare"<<*(m_list_element+i)<<","<<cur_e<<endl;
// cout<<"DEBUG: compare "<<*(m_list_element+i)<<"("<<m_list_element+i<<")"<<","<<cur_e<<endl;
// if(cur_e==*(m_list_element+i)){
// pre_e=m_list_element+i-1;
// return *pre_e;
// }
// }
// pre_e=NULL;
// return NULL;
//}
//===============================================================================
//int MyList::NextElem(int cur_e)
//{
// int*next_e;
// cout<<"DEBUG: calling MyList::NextElem "<<cur_e<<endl;
// if (ListEmpty()) {
// //next_e=NULL;
// return NULL;
// }
// for(int i=0;i<m_list_length-1;i++)
// {
// cout<<"DEBUG: compare"<<*(m_list_element+i)<<"("<<m_list_element+i<<")"<<","<<cur_e<<endl;
// if(cur_e==*(m_list_element+i)){
// next_e=m_list_element+i+1;
// return *next_e;
// }
// }
// next_e=NULL;
// return NULL;
//}
//===============================================================================
//cout<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<<<""<<endl;
void MyList::ListInsert(int ind , int e)
{
if (ind>m_list_length || ind<0) {
printf("MyList::ListInsert fail: index=%d,m_list_length=%d",ind,m_list_length);
return;
}
for(int i=m_list_length;i>=0;i--)
{
int* ind_ptr=m_list_element+i;
if(i>=ind){
printf("DEBUG: move (%x)%d->(%x)\n",m_list_element+i,*(m_list_element+i),m_list_element+i+1);
//cout<<"DEBUG: move ("<<<<""<<<<<<<<<<<<<<endl;
//cout<<"DEBUG: move ("<<m_list_element+i<<")"<<*(m_list_element+i)<<"->("<<m_list_element+i+1<<")"<<endl;
//cout<<"DEBUG: move ("<<ind_ptr<<")"<<*(ind_ptr)<<"->("<<m_list_element+i+1<<")"<<endl;
*(m_list_element+i+1)=*(m_list_element+i);
}
if(i==ind) {
*(m_list_element+i)=e;
}
}
m_list_length++;
}
//===============================================================================
void MyList::ListPush(int e)
{
ListInsert(m_list_length,e);
}
//===============================================================================
int MyList::ListPop()
{
int r =GetElem(m_list_length-1);
m_list_length--;
return r;
}
//===============================================================================
void MyList::ListDelete(int ind )
{
for(int i=0;i<m_list_length;i++)
{
if(i>=ind){
printf("DEBUG: move (%x)%d->(%x)\n",m_list_element+i+1,*(m_list_element+i),m_list_element+i);
*(m_list_element+i)=*(m_list_element+i+1);
}
}
m_list_length--;
}
//===============================================================================
void MyList::ListTraverse(bool (*visit)(int* a), bool pre_order)
{
if (pre_order) {
for(int i=0;i<m_list_length;i++)
{
visit(m_list_element+i);
}
} else {
for(int i=m_list_length-1;i>=0;i--)
{
visit(m_list_element+i);
}
}
}
//===============================================================================
void MyList::ListUnion(MyList& b,MyList & Lunion)
{
cout<<"print b:============================"<<endl;
b.PrintList();
Lunion=b;
Lunion.SetName("Lunion");
//Lunion.PrintList();
for(int i=0;i<m_list_length;i++)
{
if(b.LocateElem(GetElem(i),compare)==-1)
{
Lunion.ListPush(GetElem(i));
}
}
}
//===============================================================================
void MyList::ListSwap(int ind1,int ind2)
{
if ( ind1<0 || ind1>=m_list_length
|| ind2<0 || ind2>=m_list_length
|| ind1==ind2)
{
return ;
}
int tmp=GetElem(ind1);
SetElem(ind1,GetElem(ind2));
SetElem(ind2,tmp);
}
//===============================================================================
void MyList::ListSort()// bubble sort
{
for(int range=m_list_length-1;range>=0;range--)
{
for(int i=0;i<range;i++)
{
if(GetElem(i)>GetElem(i+1))
{
ListSwap(i,i+1);
}
}
}
}
//===============================================================================
void MyList::ListReverse()// Reverse
{
int list_length_bk=m_list_length;
int ll[list_length_bk];
int ind=0;
while (!ListEmpty())
{
ll[ind++]=ListPop();
}
for(int i=0;i<list_length_bk;i++)
{
ListPush(ll[i]);
}
}
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch1_life_game/include/utility.h
bool user_say_yes() ;//FUNC
<file_sep>/cpp/3_BOOK_DATA_STRUCTURE_QIANLIPING/ch1_life_game/src/utility.cpp
#include "utility.h"
#include <iostream>
using namespace std;
bool user_say_yes() {//FUNC
cout<<"do you want update board?"<<endl;
char a;
cin>>a;
if (a=='y' ||a=='Y') {
return true;
} else {
return false;
}
}
<file_sep>/cpp/1_BOOK_DATA_STRUCTURE_C_YANWEIMIN_WUWEIMIN/include/include.top.h
#ifndef INCLUDE_TOP_H
#define INCLUDE_TOP_H
#define VNAME(name) (#name) // a macro that can print var out
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_DEBUG_INFO() \
(::std::cout<<"zjc debug: " \
<<":\tFUNC="<<__PRETTY_FUNCTION__ \
<<":\tFILE=" <<__FILE__<<":\tLINE=" <<__LINE__ \
<<":\tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"\tzjc debug: " \
<<":\tFUNC="<<__PRETTY_FUNCTION__ \
<<":\tFILE=" <<__FILE__<<":\tLINE=" <<__LINE__ \
<<":\tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <string.h>
#include <string>
#include <cstdlib>
#include <time.h>
#include <assert.h>
#include "2.1_linear_list.h"
#include "2.1_func.h"
#include "2.1_MyStack.h"
#include "2.3_link_list.h"
using namespace std;
#endif // INCLUDE_TOP_H
<file_sep>/cpp/POJ/include/include.top.h
#ifndef INCLUDE_TOP_H
#define INCLUDE_TOP_H
//--------------------------------------
// macro
//--------------------------------------
#define PI 3.14159265358
#define GET_VALUE(x) (x)
#define SQUARE_VOLUME(a) (a*a*a)
#define SPHERE_VOLUME(a) (4/3*PI*a*a*a)
//--------------------------------------
// include lib files
//--------------------------------------
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
using namespace std;
//--------------------------------------
// include local files
//--------------------------------------
//#include "include/f13_2.h"
#include "lib.h"
#include "include.top.h"
#include "gnuplot_i.h"
#define PRINTVAR(a) std::cout<<#a<<"\t=\t"<<a<<"\t@"<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINTVAR_hor(a) std::cout<<#a<<"("<<a<<")\t";
#define PRINT_ARRAY(a,len) for(int u=0;u<len;u++) {std::cout<<u<<":\t"<<*a+u<<std::endl;}
#define PRINT_VECTOR(a) for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<std::endl;}
#define PRINT_MAP(a) std::cout<<#a<<":"<<endl;for(auto u:a) {std::cout<<u.first<<"\t->\t"<<u.second<<std::endl;}
#define PRINT_VECTOR_hor(a) std::cout<<#a<<":";for(auto u=a.begin();u!=a.end();u++) {std::cout<<*u<<"\t";};std::cout<<""<<std::endl;
#define PRINT_POINTER1(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER2(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<"\t->\t"<<**a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER3(a) std::cout<<#a; \
std::cout<<"\t= \t"<<a; \
std::cout<<"\t->\t"<<*a; \
std::cout<<"\t->\t"<<**a; \
std::cout<<"\t->\t"<<***a; \
std::cout<<__FILE__<<":"<<__LINE__<<":"<<__FUNCTION__<<"()"<<std::endl;
#define PRINT_POINTER(a) PRINT_POINTER1(a)
#define PRINT_DEBUG_INFO() \
(::std::cout<<"DEBUG: FILE="<<__FILE__<<":LINE=" <<__LINE__<<":FUNC="<<__FUNCTION__<<"() compiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl)
#define PRINT_DEBUG_INFO_PREFIX(p) \
(::std::cout<<p<<"zjc debug: FILE=" <<__FILE__<<":\tLINE=" <<__LINE__<<":\tFUNC="<<__FUNCTION__<<" \tcompiled in " <<__TIME__<<"-" <<__DATE__<<"" <<::std::endl )
//--------------------------------------
//--------------------------------------
#endif
<file_sep>/cpp/6_BOOK_ALGORITHMS_VER4_Robert/ch4/4.1_undirected_graph_Ver1/main.cpp
#include "../../include/include.h"
#include "DepthFirstSearch.h"
#include "DepthFirstPaths.h"
#include "CC.h"
#include "Cycle.h"
#include "TwoColor.h"
#include "SymbolGraph.h"
#include "DegreeOfSeparation.h"
#include "GraphProperties.h"
//void testSearch(Graph* g); // test table 4.1.4
//void testPath(Graph* g); // test table 4.1.5
//void testCC(Graph* g); // test table 4.1.6
//////////////////////////////
// MAIN
//////////////////////////////
int main()
{
//assert(0);
//testGraph(); //table
//testSearch();
//testPath();
//testCC();
//testCycle();
//testTwoColor();
//testSymbolGraph();
//testDegreeOfSeparation();
testGraphProperties();
DPRINT("-------------------------");
return 0;
}
//////////////////////////////
//////////////////////////////
//////////////////////////////
#if 0
void testPath(Graph* g)
{
DENTER;
int SOURCE=1;
bool USE_DFS=1;
//g->search(SOURCE,USE_DFS);
//g->search(SOURCE,!USE_DFS);
DLOG(g->has_path_to(1,-1,9));
//DLOG(g->get_one_path_to(1,-1,6));
//DLOG(g->get_one_path_to(1,-1,2));
//DLOG(g->get_one_path_to(1,-1,3));
//DLOG(g->get_one_path_to(1,-1,8));
auto paths=g->paths(SOURCE);
for(auto one_path:paths)
{
DLOG(one_path );
}
DRETURN;
}
void testCC(Graph* g)
{
DENTER;
int M=g->countCC();
DLOG(M);
vector<vector<int>> components;
for(int v=0;v<g->V();v++)
components[g->id(v)].push_back(v);
for(int i=0;i<M;i++)
{
for(int v:components[i])
cout<<v<<" "<<endl;
cout<<endl;
}
DRETURN;
}
#endif
<file_sep>/cpp/4_BOOK_C_how_to_program_H_M_Deitel/src/main.cpp
#include "include.top.h"
//using namespace std;
using std::string;
using std::stringstream;
namespace rtlgen_debug {
extern stringstream ss;
extern string debug_prompt(string info,
bool echo = 1,
string mode = "",
string file = "",
int line = -1,
int adjust_indent = 0);
}
#define DEBUG_ECHO 1
#define DEBUG_INDENT " > "
#define SS rtlgen_debug::ss
#define DEBUG_PROMPT_old rtlgen_debug::debug_prompt
#define DEBUG_STACK rtlgen_debug::print_stack
#define RtlGen_DEBUG
#define AuxilarySignalGen_DEBUG
#ifdef AuxilarySignalGen_DEBUG
#define AuxilarySignalGen_DEBUG_bool 1
#else
#define AuxilarySignalGen_DEBUG_bool 0
#endif
#ifdef RtlGen_DEBUG
#define PRINT_DEBUG_INFO(msg,enter_or_return) \
SS.str(""); \
SS << msg; \
DEBUG_PROMPT_old(SS.str(), DEBUG_ECHO, enter_or_return, __FILE__, __LINE__);
#else
#define PRINT_DEBUG_INFO(msg,enter_or_return)
#endif
#ifdef RtlGen_DEBUG
#define PRINT_DEBUG_cond(cond,msg,enter_or_return) \
if (cond) { \
SS.str(""); \
SS << msg; \
DEBUG_PROMPT_old(SS.str(), DEBUG_ECHO, enter_or_return, __FILE__, __LINE__); \
}
#else
#define PRINT_DEBUG_cond(cond,msg,enter_or_return)
#endif
#ifdef RtlGen_DEBUG
#define DEBUG_PROMPT_new(cond_def,msg,enter_or_return) \
if (cond_def##_bool) { \
SS.str(""); \
SS << msg; \
SS <<__FUNCTION__; \
SS <<"()"; \
DEBUG_PROMPT_old(SS.str(), DEBUG_ECHO, enter_or_return, __FILE__, __LINE__); \
}
#else
#define DEBUG_PROMPT_new(cond_def,msg,enter_or_return)
#endif
//-----------------------------------------------
#define macro1
#define macro2
#ifdef RtlGen_DEBUG
vector<bool> macro_is_set()
{
vector<bool> r;
#ifdef macro1
r.push_back(1);
#else
r.push_back(0);
#endif
#ifdef macro2
r.push_back(1);
#else
r.push_back(0);
#endif
//cout<<"r size="<<r.size()<<""<<endl;
return r;
}
#else
inline vector<bool> macro_is_set() {}
#endif
//-----------------------------------------------
//-----------------------------------------------
// define in define : wrong
# if 0
#define apply_bool() \
bool macro_value_bool 1
#endif
//-----------------------------------------------
//-----------------------------------------------
// recur define
#define set_recur1(M1,...) \
cout<<"set1 "<<M1<<""<<endl; \
set_recur2(__VA_ARGS__) \
#define set_recur2(M1,...) \
cout<<"set2 "<<M1<<""<<endl; \
set_recur1(__VA_ARGS__) \
//-----------------------------------------------
//\#ifdef cond \
//\#endif
stringstream rtlgen_debug::ss;
string rtlgen_debug::debug_prompt(string info,
bool echo,
string mode,
string file,
int line,
int adjust_indent)
{
cout<<"calling rtlgen_debug::debug_prompt"<<""<<endl;
PRINTVAR(info);
PRINTVAR(echo);
PRINTVAR(mode);
PRINTVAR(file);
PRINTVAR(line);
PRINTVAR(adjust_indent);
return "";
}
int main() {
cout<<"Hello world!"<<endl;
//f13_2();
//f13_3();
//f13_6();
#if 1
cout<<"1--------------------"<<""<<endl;
SS << "AuxilarySignalGen::PipelineEnableSignalGen()";
DEBUG_PROMPT_old(SS.str(), DEBUG_ECHO, "return", __FILE__, __LINE__);
cout<<"2--------------------"<<""<<endl;
PRINT_DEBUG_INFO("AuxilarySignalGen::PipelineEnableSignalGen()","return");
cout<<"3--------------------"<<""<<endl;
PRINT_DEBUG_cond(AuxilarySignalGen_DEBUG_bool,"AuxilarySignalGen::PipelineEnableSignalGen()","return");
cout<<"4--------------------"<<""<<endl;
//DEBUG_PROMPT_new(AuxilarySignalGen_DEBUG,"AuxilarySignalGen::PipelineEnableSignalGen()","return");
DEBUG_PROMPT_new(AuxilarySignalGen_DEBUG,"","return");
vector<bool> r=macro_is_set();
cout<<"r size="<<r.size()<<""<<endl;
for(auto i:r)
{
cout<<"ITER:"<<i<<""<<endl;
}
PRINTVAR(AuxilarySignalGen_DEBUG_bool)
cout<<"end--------------------"<<""<<endl;
set_recur1(1,2,3,4);
#endif
#if 0
int x[10] ;
int y[10][10] ;
cout<<"x:"<<x[3]<<""<<endl;
cout<<"y:"<<y[3][0]<<""<<endl;
cout<<"y count:"<<y.count()<<""<<endl;
#endif
return 0;
}
| f9ea01aa0a109fe9bf50b3e9412b16265943e1c6 | [
"Makefile",
"Java",
"Python",
"C",
"C++",
"Shell"
] | 349 | C++ | sjtusonic/exe | b02e7f6d63da4eab08358ed8bcec8f7c7670b31d | 24ab4ed02a9ab1a3e2f8897004a5e8eec070350c |
refs/heads/master | <file_sep>import scrollRankingBoard1 from './demo1'
import scrollRankingBoard2 from './demo2'
export default {
scrollRankingBoard1,
scrollRankingBoard2
} | 181317301c2e0f611f30ff212c81149bcff3f48e | [
"JavaScript"
] | 1 | JavaScript | ftt1024/datav.jiaminghi.com | 197e9ce3172545e035c15ac66d989f9d6e3f000e | 12ccd64b76b390e47e427d34d0782500032520bc |
refs/heads/master | <repo_name>fenwk0/test-ideas<file_sep>/classes/selfDrivingCarTest.py
from unittest import TestCase
from classes.selfDrivingCar import SelfDrivingCar
class SelfDrivingCarTest(TestCase):
def setUp(self):
self.car = SelfDrivingCar()
def test_stop(self):
self.car.speed = 5
self.car.stop()
# Verify the speed is 0 after stopping
self.assertEqual(0, self.car.speed)
# Verify it is Ok to stop again if the car is already stopped
self.car.stop()
self.assertEqual(0, self.car.speed)
<file_sep>/classes/snake.py
class Snake:
def __init__(self, name):
self.name = name
def change_name(self, new_name):
self.name = new_name
<file_sep>/init-git.sh
#!/usr/bin/env bash
# see https://gist.github.com/adamjohnson/5682757
echo "# test-ideas" >> README.md
#git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/fenwk0/test-ideas.git
git push -u origin master<file_sep>/README.md
# test-ideas
If you can't push to git the read this
https://gist.github.com/fenwk0/ce3101fad3f8336493512bbbd1fe97fa.js
<file_sep>/format/strings.py
def create_command_001():
command_template = "cmd_001 {param1} {param2} {param3}"
return command_template.format(param1="one", param2="two", param3="three")
def create_command_002():
command_template = "cmd_002 "\
+ "{param1} "\
+ "{param2} "\
+ "{param3}"
return command_template.format(param1="one", param2="two", param3="three")
def create_command_003():
command_template = ("cmd_003 "
+ "{param1} "
+ "{param2} "
+ "{param3}")
return command_template.format(param1="one", param2="two", param3="three")
print(create_command_001())
print(create_command_002())
print(create_command_003())
| 256ea0d8370b84ad5517cdc180d2cf34867b10d9 | [
"Markdown",
"Python",
"Shell"
] | 5 | Python | fenwk0/test-ideas | 0f683d93b32b115668b79266a1c527ba24c053f8 | 92d8ef15fad70f5d7bf3fdf6ac0fe879a52df39d |
refs/heads/master | <repo_name>flying-train/flying-train.github.io<file_sep>/games/index.js
$(".game-description, .game-description img").addClass("normal-shadow")
$(".game-description").click(function() {
window.open($("a", this)[0].href)
})<file_sep>/games/shootr/index.js
canvas = document.getElementById('c');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx = canvas.getContext('2d');
var entities = [];
var nemesis = [];
var bullets = [];
var stars = [];
counter = 0;
backgroundSpeed = 5;
baseStarSpeed = 5;
isFocused = true;
running = true;
bulletTokens = 5;
function ctxReset() {
ctx.fillStyle = "white";
ctx.shadowBlur = "0";
ctx.shadowColor = "black";
}
function draw() {
ctx.shadowBlur = 50;
ctx.shadowColor = "white";
for (var i = 0; i < stars.length; i++) {
stars[i].draw();
}
ctx.shadowBlur = 0;
for (var i = 0; i < bullets.length; i++) {
bullets[i].draw();
}
for (var i = 0; i < nemesis.length; i++) {
entities[i].draw();
}
jet.draw();
}
setInterval(ai, 700)
function update() {
if(running) requestAnimationFrame(update)
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < stars.length; i++) {
stars[i].update();
}
for (var i = 0; i < entities.length; i++) {
entities[i].update();
}
draw();
}
var jet = {
x: 40,
y: canvas.height/2,
width: 40,
height: 70,
center: {
x: this.x + this.width/2,
y: this.y + this.height/2
},
draw: function() {
ctxReset();
ctx.fillStyle = "#F2C94C";
ctx.fillRect(this.x + this.width, this.y - this.height/4, this.width, this.height/2);
ctx.fillRect(this.x, this.y - this.height/2, this.width, this.height);
for (var i = 0; i < bullets.length; i++) {
if (!bullets[i].ally && collision(this, bullets[i])) {
running = false;
}
}
}
}
class Star {
constructor(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
this.a = 7/z;
this.speed = baseStarSpeed/z;
stars.push(this);
}
draw(){
ctx.fillStyle = "white";
ctx.fillRect(this.x, this.y, this.a, this.a);
}
update(){
this.x -= this.speed * backgroundSpeed;
if (this.x + this.a < 0) {
stars.splice(stars.indexOf(this), 1)
}
}
}
class JetBullet {
constructor(x, y, ally) {
this.width = 24;
this.height = 24;
this.x = x;
this.y = y;
this.ally = ally;
this.speed = (ally) ? 30 : -30;
this.fillStyle = (ally) ? "#0C0" : "#C00";
bullets.push(this);
entities.push(this);
}
draw(){
ctx.fillStyle = this.fillStyle;
ctx.fillRect(this.x, this.y - this.height/2, this.width, this.height);
}
update(){
this.x += this.speed;
if (!(this.x >= 0 && this.x < canvas.width)) {
entities.splice(entities.indexOf(this), 1)
bullets.splice(bullets.indexOf(this), 1)
}
}
}
class Ship {
constructor(y) {
this.x = canvas.width + 100;
this.y = y;
this.width = 40;
this.height = 70;
this.speed = baseStarSpeed/5 * backgroundSpeed;
this.radius = Math.random() * 50;
this.destination = {
x: canvas.width - 100,
y: 600
}
nemesis.push(this)
entities.push(this)
}
update(){
//move to destination
for (var i = 0; i < bullets.length; i++) {
if (bullets[i].ally && collision(this, bullets[i])) {
entities.splice(entities.indexOf(this), 1);
nemesis.splice(nemesis.indexOf(this), 1);
entities.splice(entities.indexOf(bullets[i]), 1);
bullets.splice(bullets.indexOf(bullets[i]), 1);
}
}
if (this.destination.x < this.x) {
this.x -= distance(this, this.destination)/100;
}
if (this.destination.x > this.x) {
this.x += distance(this, this.destination)/100;
}
if (this.destination.y < this.y) {
this.y -= distance(this, this.destination)/100;
}
if (this.destination.y > this.y) {
this.y += distance(this, this.destination)/100;
}
}
draw(){
ctx.fillStyle = "black";
ctx.strokeStyle = "white";
ctx.fillRect(this.x - this.width, this.y - this.height/4, this.width, this.height/2);
ctx.fillRect(this.x, this.y - this.height/2, this.width, this.height);
ctx.beginPath();
ctx.rect(this.x - this.width, this.y - this.height/4, this.width, this.height/2);
ctx.rect(this.x, this.y - this.height/2, this.width, this.height);
ctx.closePath();
ctx.stroke();
}
}
var starGaze = setInterval(function() {
if (isFocused) {
new Star(canvas.width, 100 + Math.random() * (canvas.height - 100), Math.floor(1 + Math.random() * 5))
}
}, 1000/backgroundSpeed)
window.onfocus = function() {
isFocused = true;
}
window.onblur = function() {
isFocused = false;
}
document.addEventListener("click", function(e) {
if (bulletTokens > 0) {
new JetBullet(50, e.clientY, true);
--bulletTokens;
}
});
document.addEventListener("mousemove", function(e) {
jet.y = e.clientY;
});
for (var i = 0; i < 10; i++) {
new Star(canvas.width * Math.random(), Math.random() * canvas.height, Math.floor(1 + Math.random() * 5))
}
/*class Coin {
constructor(x, y) {
}
// methods
}*/
function ai() {
for (var i = 0; i < nemesis.length; i++) {
if (nemesis[i] instanceof Ship) {
if (Math.random() * 100 < 40) {
if (Math.random() * 100 < 75) {
nemesis[i].destination.y = jet.y;
} else {
nemesis[i].destination.y = 100 + Math.random() * canvas.height - 100;
}
}
if (Math.random() * 100 < 20) {
nemesis[i].destination.x = canvas.width - 500 + Math.random() * 400;
}
if (Math.random() * 100 < 60 && jet.y - 100 < nemesis[i].y && jet.y + 100 > nemesis[i].y) {
new JetBullet(nemesis[i].x, nemesis[i].y, false)
}
}
}
bulletTokens++;
}
setInterval(() => new Ship(Math.random() * canvas.height), 2500)
new Ship(500);
function distance(point1, point2) {
var distX = point1.x - point2.x;
var distY = point1.y - point2.y;
var dist = Math.sqrt((distX * distX) + (distY * distY));
return dist;
}
function collision(obj1, obj2) {
if (obj1.x + obj1.width >= obj2.x && obj1.x <= obj2.x + obj2.width &&
obj1.y + obj1.width >= obj2.y && obj1.y <= obj2.y + obj2.width) {
return true;
}
}
requestAnimationFrame(update)
/*
function gameover() {
for (var i = 0; i < nemesis.length; i++) {
if (nemesis[i].x < 0) {
clearStuff();
document.getElementById('game-over').style.display = 'block';
nemesis = [];
}
}
}
function win() {
if (counter >= 10) {
clearStuff();
document.getElementById('tut').innerHTML = "You win!";
document.getElementById('game-over').style.display = 'block';
}
}
function clearStuff() {
counter = 0;
bullets = [];
nemesis = [];
window.clearInterval(updateInterval);
window.clearInterval(spawnInterval);
}
function init() {
document.getElementById('counter').innerHTML = 0;
speed = 5;
new Nemesis();
updateInterval = setInterval(update, 20);
spawnInterval = setInterval(spawn, 1000);
document.getElementById('game-over').style.display = 'none';
}
*/ | 36050a4df4367ae3f48cca1a91b01379a257fd3e | [
"JavaScript"
] | 2 | JavaScript | flying-train/flying-train.github.io | 3011dca581eb0137af777a52b378198f535150ab | 3da4ee009dfc88fd96ba8f1940a0ba7038d067a3 |
refs/heads/master | <file_sep>var async = require('async'),
fs = require('graceful-fs'),
path = require('path'),
uuid = require('node-uuid'),
mkdirp = require('mkdirp');
module.exports = function(dir) {
dir = dir || path.join(process.cwd(), 'store');
return {
// store in this directory
dir: dir,
// list all stored objects by reading the file system
list: function(cb) {
var self = this;
var action = function(err) {
if (err) return cb(err);
readdir(dir, function(err, files) {
if (err) return cb(err);
files = files.filter(function(f) { return f.substr(-5) === ".json"; });
var fileLoaders = files.map(function(f) {
return function(cb) {
loadFile(f, cb);
};
});
async.parallel(fileLoaders, function(err, objs) {
if (err) return cb(err);
sort(objs, cb);
});
})
};
mkdirp(dir, action);
},
// store an object to file
add: function(obj, cb) {
var action = function(err) {
if (err) return cb(err);
var json;
try {
json = JSON.stringify(obj, null, 2);
}
catch (e) {
return cb(e);
}
obj.id = obj.id || uuid.v4();
fs.writeFile(path.join(dir, obj.id + '.json'), json, 'utf8', function(err) {
if (err) return cb(err);
cb();
});
};
mkdirp(dir, action);
},
// delete an object's file
remove: function(id, cb) {
var action = function(err) {
if (err) return cb(err);
fs.unlink(path.join(dir, id + '.json'), function(err) {
cb(err);
});
}
mkdirp(dir, action);
},
// load an object from file
load: function(id, cb) {
mkdirp(dir, function(err) {
if (err) return cb(err);
loadFile(path.join(dir, id + '.json'), cb);
})
}
}
};
var readdir = function(dir, cb) {
fs.readdir(dir, function(err, files) {
if (err) return cb(err);
files = files.map(function(f) {
return path.join(dir, f);
});
cb(null, files);
});
};
var loadFile = function(f, cb) {
fs.readFile(f, 'utf8', function(err, code) {
if (err) return cb("error loading file" + err);
try {
var jsonObj = JSON.parse(code);
}
catch (e) {
cb("Error parsing " + f + ": " + e);
}
cb(null, jsonObj);
});
};
var sort = function(objs, cb) {
async.sortBy(objs, function(obj, cb) {
cb(null, obj.name || '');
}, cb);
};
| 1d98cb2038740667e0478eaa92fa631a1a96f865 | [
"JavaScript"
] | 1 | JavaScript | alexkwolfe/node-store | 4e75c4fa8cc32fab0fa6665c2d22882711917763 | 6111ca069d1b5e7500f48ef5ce30a1c94968dbb9 |
refs/heads/master | <file_sep>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddEmployeesComponent } from './components/add-employees/add-employees.component';
import { EmployeeDetailsComponent } from './components/employee-details/employee-details.component';
import { EmployeeListComponent } from './components/employee-list/employee-list.component';
import { FileUploadComponent } from './components/file-upload/file-upload.component';
import { HomeComponent } from './components/home/home.component';
import { LoginComponent } from './components/login/login.component';
import { AuthGuardService } from './services/guards/auth-guard.service';
const routes: Routes = [
{ path: '', redirectTo: 'employees', pathMatch: 'full' },
{ path: 'employees', component: EmployeeListComponent , canActivate : [AuthGuardService]},
{ path: 'employees/:id', component: EmployeeDetailsComponent, canActivate : [AuthGuardService] },
{ path: 'file', component: FileUploadComponent , canActivate : [AuthGuardService]},
{ path: 'add', component: AddEmployeesComponent , canActivate : [AuthGuardService] },
{
component : HomeComponent,
path: 'home' ,
canActivate : [AuthGuardService]
},
{
component : LoginComponent,
path: 'login'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { HttpClient, HttpRequest, HttpEvent, HttpHeaders } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { EmployeeDataService } from 'src/app/services/employee/employee-data.service';
@Component({
selector: 'app-add-employees',
templateUrl: './add-employees.component.html',
styleUrls: ['./add-employees.component.css']
})
export class AddEmployeesComponent implements OnInit {
imageSrc: string | undefined;
myForm = new FormGroup({
fullName: new FormControl('', [Validators.required, Validators.minLength(3)]),
dob: new FormControl('', [Validators.required]),
gender: new FormControl('', [Validators.required]),
salary: new FormControl('', [Validators.required]),
designation : new FormControl('', [Validators.required]),
file: new FormControl('', [Validators.required]),
fileSource: new FormControl('', [Validators.required])
});
constructor(private http : HttpClient, private employeeService: EmployeeDataService ) { }
ngOnInit(): void {
}
get f(){
return this.myForm.controls;
}
onFileChange(event:any) {
const reader = new FileReader();
if(event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);
reader.onload = () => {
this.imageSrc = reader.result as string;
this.myForm.patchValue({
fileSource: reader.result
});
};
}
}
submit(){
console.log(this.myForm.value);
this.employeeService.create(this.myForm.value).subscribe(res => {
console.log(res);
alert('Uploaded Successfully.');
})
}
}
<file_sep>import { NgModule } from '@angular/core';
import { AuthGuardService } from './services/guards/auth-guard.service';
import { BrowserModule } from '@angular/platform-browser';
import { JwtModule } from "@auth0/angular-jwt";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http' ;
import { FlexLayoutModule } from '@angular/flex-layout';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule} from '@angular/material/card';
import { MatToolbarModule} from '@angular/material/toolbar';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { Ng2OrderModule } from 'ng2-order-pipe';
import { NgxPaginationModule } from 'ngx-pagination';
import { FileUploadComponent } from './components/file-upload/file-upload.component';
import { MatIconModule} from '@angular/material/icon';
import { EmployeeDetailsComponent } from './components/employee-details/employee-details.component';
import { EmployeeListComponent } from './components/employee-list/employee-list.component';
import { EmployeeDataService } from './services/employee/employee-data.service';
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
import { AddEmployeesComponent } from './components/add-employees/add-employees.component';
import { NavbarComponent } from './components/navbar/navbar.component';
export function tokenGetter() {
return localStorage.getItem("jwt");
}
@NgModule({
declarations: [
AppComponent,
LoginComponent,
HomeComponent,
FileUploadComponent,
EmployeeDetailsComponent,
EmployeeListComponent,
AddEmployeesComponent,
NavbarComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FlexLayoutModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatCardModule,
MatToolbarModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule,
MatIconModule,
BsDatepickerModule.forRoot(),
// RouterModule.forRoot([
// { path: 'home', component: HomeComponent },
// { path: 'employee', service: EmployeeDataService , canActivate :[AuthGuardService] },
// { path: 'login', component: LoginComponent },
// //{ path: 'customers', component: CustomerComponent , canActivate: [ ] },
// ]),
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
allowedDomains: ["localhost:4000"],
disallowedRoutes: []
}
}),
BrowserAnimationsModule,
NgbModule,
Ng2SearchPipeModule,
Ng2OrderModule,
NgxPaginationModule
],
providers: [AuthGuardService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>export class Employee {
id?: any;
fullName?: string;
dob?: string;
gender?:string;
salary?: DoubleRange;
designation?:string;
imageSrc?: string;
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Employee } from 'src/app/models/employee.model';
const baseUrl = "https://localhost:44397/api/employee"
@Injectable({
providedIn: 'root'
})
export class EmployeeDataService {
constructor(private http : HttpClient) {
}
getAll() : Observable<Employee[]>{
var tokenHeader = new HttpHeaders({'Authorization' : 'Bearer ' + localStorage.getItem('jwt')});
console.log(tokenHeader);
return this.http.get<Employee[]>(baseUrl , {headers: tokenHeader} ); };
get(id : number) : Observable<Employee>{
var tokenHeader = new HttpHeaders({'Authorization' : 'Bearer ' + localStorage.getItem('jwt')});
return this.http.get<Employee>(`${baseUrl}/${id}` , {headers: tokenHeader} ); };
create(data: Employee): Observable<any> {
var tokenHeader = new HttpHeaders({'Authorization' : 'Bearer ' + localStorage.getItem('jwt')});
const body=JSON.stringify(data);
return this.http.post(baseUrl, body ,{'headers': tokenHeader});
}
update(id: number, data: any): Observable<any> {
var tokenHeader = new HttpHeaders({'Authorization' : 'Bearer ' + localStorage.getItem('jwt')});
return this.http.put(`${baseUrl}/${id}`, data, {'headers': tokenHeader});
}
delete(id: number): Observable<any> {
var tokenHeader = new HttpHeaders({'Authorization' : 'Bearer ' + localStorage.getItem('jwt')});
return this.http.delete(`${baseUrl}/${id}` , {'headers': tokenHeader} );
}
deleteAll(): Observable<any> {
return this.http.delete(baseUrl);
}
}
<file_sep>import { HttpClient, HttpRequest, HttpEvent, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FileUploadService {
baseUrl ="https://localhost:44397/api/ExcelUpload";
constructor(private http : HttpClient) { }
upload(file: File): Observable<HttpEvent<any>> {
const formData: FormData = new FormData();
var tokenHeader = new HttpHeaders({'Authorization' : 'Bearer ' + localStorage.getItem('jwt')});
formData.append('file', file);
const req = new HttpRequest('POST', `${this.baseUrl}/upload`,
formData, {
reportProgress: true,
responseType: 'json'
});
return this.http.request(req);
}
getFiles(): Observable<any> {
var tokenHeader = new HttpHeaders({'Authorization' : 'Bearer ' + localStorage.getItem('jwt')});
return this.http.get(`${this.baseUrl}/files` , {headers: tokenHeader} );
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Employee } from 'src/app/models/employee.model';
import { EmployeeDataService } from 'src/app/services/employee/employee-data.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-employee-details',
templateUrl: './employee-details.component.html',
styleUrls: ['./employee-details.component.css']
})
export class EmployeeDetailsComponent implements OnInit {
currentEmployee: Employee = {
id:'',
fullName: '',
dob: '',
gender: '',
salary : undefined,
designation : ''
};
imageSrc: string | undefined;
myForm = new FormGroup({
fullName: new FormControl('', [Validators.required, Validators.minLength(3)]),
dob: new FormControl('', [Validators.required]),
gender: new FormControl('', [Validators.required]),
salary: new FormControl('', [Validators.required]),
designation : new FormControl('', [Validators.required]),
file: new FormControl('', [Validators.required]),
fileSource: new FormControl('', [Validators.required])
});
message = '';
baseUrl : string = "https://localhost:44397/api/employee/"+this.route.snapshot.params.id ;
constructor(private employeeService: EmployeeDataService,
private route: ActivatedRoute,
private router: Router,
private http: HttpClient
) { }
ngOnInit(): void {
this.message = '';
this.getEmployee(this.route.snapshot.params.id);
}
get f(){
return this.myForm.controls;
}
onFileChange(event:any) {
const reader = new FileReader();
if(event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);
reader.onload = () => {
this.imageSrc = reader.result as string;
this.myForm.patchValue({
fileSource: reader.result
});
};
}
}
updateEmployee(){
console.log(this.myForm.value);
//this.http.put(this.baseUrl, this.myForm.value)
this.employeeService.update( this.route.snapshot.params.id , this.myForm.value).subscribe(res => {
console.log(res);
alert('Uploaded Successfully.');
})
}
getEmployee(id: number): void {
this.employeeService.get(id)
.subscribe(
(res:Employee) => {
this.myForm.patchValue({
fullName: res.fullName,
dob: res.dob,
gender: res.gender,
salary: res.salary,
designation: res.designation
});
},
error => {
console.log(error);
});
}
deleteEmployee(): void {
this.employeeService.delete(this.currentEmployee.id)
.subscribe(
response => {
console.log(response);
this.router.navigate(['/employees']);
},
error => {
console.log(error);
});
}
}
<file_sep>import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { JwtHelperService } from '@auth0/angular-jwt';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'kiaAngApp';
auth =false;
constructor(private jwtHelper: JwtHelperService , private router : Router) { }
ngOnInit(): void {
this.auth = this.isUserAuthenticated();
if(this.auth ==false )
{
this.router.navigate(["login"]);
}
}
isUserAuthenticated(){
const token : any = localStorage.getItem("jwt");
if (token && !this.jwtHelper.isTokenExpired(token)) {
return true;
}
else{
return false;
}
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { EmployeeDataService } from 'src/app/services/employee/employee-data.service';
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
employees : any ;
fullName : string ="" ;
designation : string ="";
fromDate : string ="" ;
toDate : string ="";
fromSalary : number =0 ;
toSalary : number =0;
gender : string= "";
p: number =1 ;
constructor(private employeeData : EmployeeDataService ) {
}
ngOnInit(): void {
this.employeeData.getAll().subscribe((data: any)=> {
console.log(data);
this.employees = data;
})
}
search(){
if(this.fullName == ""){
this.ngOnInit();
}
else{
this.employees = this.employees.filter((emp: { fullName: string; }) =>
{
return emp.fullName.toLocaleLowerCase().match(this.fullName.toLocaleLowerCase()) ;
})
}
}
searchDOB(){
if(this.fromDate == "" && this.toDate ==""){
alert(1);
this.ngOnInit();
}
else if(this.fromDate != "" && this.toDate !="" ){
this.ngOnInit();
this.employees = this.employees.filter((emp: { dob : string; }) =>
{
return new Date(emp.dob) >= new Date(this.fromDate) && new Date(emp.dob) <= new Date(this.toDate) ;
})
}
else if(this.fromDate != "" && this.toDate =="" )
{
this.ngOnInit();
this.employees = this.employees.filter((emp: { dob : string; }) =>
{
return new Date(emp.dob) >= new Date(this.fromDate) ;
})
}
else {
this.ngOnInit();
this.employees = this.employees.filter((emp: { dob : string; }) =>
{
return new Date(emp.dob) <= new Date(this.toDate) ;
})
}
}
searchSalary(){
alert(this.fromSalary);
alert(this.toSalary);
if((this.fromSalary == 0 || this.fromSalary == null) && (this.toSalary ==0 || this.toSalary ==null)){
this.ngOnInit();
}
else if((this.fromSalary != 0 || this.fromSalary != null) && (this.toSalary !=0 || this.toSalary !=null) ){
this.ngOnInit();
this.employees = this.employees.filter((emp: { salary : number; }) =>
{
return emp.salary >= this.fromSalary && emp.salary <= this.toSalary;
})
}
else if((this.fromSalary != 0 || this.fromSalary != null) && (this.toSalary ==0 || this.toSalary ==null) )
{
this.ngOnInit();
this.employees = this.employees.filter((emp: { salary : number; }) =>
{
return emp.salary >= this.fromSalary ;
})
}
else {
this.ngOnInit();
this.employees = this.employees.filter((emp: { salary : number; }) =>
{
return emp.salary <= this.toSalary ;
})
}
}
searchDesignation(){
if(this.designation == ""){
this.ngOnInit();
}
else{
this.employees = this.employees.filter((emp: { designation: string; }) =>
{
return emp.designation.toLocaleLowerCase().match(this.designation.toLocaleLowerCase()) ;
})
}
}
searchGender(){
if(this.gender == ""){
this.ngOnInit();
}
else{
this.employees = this.employees.filter((emp: { gender: string; }) =>
{
return emp.gender.toLocaleLowerCase().match(this.gender.toLocaleLowerCase()) ;
})
}
}
key : string ='importedDate' ;
reverse: boolean = false ;
sort(key : string){
this.key = key ;
this.reverse = !this.reverse;
}
}
| 86c869193fc681e1358f1d8d5219dc4e35ce155e | [
"TypeScript"
] | 9 | TypeScript | epiyushpant/KIAAng | b27486abb55205a8fa8b6eeae2de524eed8f2d10 | 633b74e25df4352ab3112e2cc0ed9a1a216fe42e |
refs/heads/master | <repo_name>MahmoudAbdelRazik95/WhateverSocial<file_sep>/friends/js/index.js
$(document).ready(function() {
$.ajax({
type: "POST",
url: "../php/friends.php",
cache: false,
success: function (res) {
if(res=='returntoindex'){
window.location.href = "../index.html"
}
var obj=$.parseJSON(res);
console.log(obj)
var users = obj.user;
var $post = $('#main-window').html();
var posts = '';
users.forEach(function (user) {
var single=$post;
posts += single;
});
$('#main-window').html(posts);
var j=0;
$.each($('.post'),function(el){
console.log(users[j]);
var image = ' url("'+users[j].profilepictureURL+'") 50% 50% / cover no-repeat';
$(this).find('.user-img').css('background',image);
$(this).find('.user-name').text(users[j].nickname);
$(this).find('.post-date').text(users[j].hometown);
$(this).find('.user-id').text(users[j].userid);
$(this).find('.content').text("");
$(this).find('.actions').find('.heart').remove();
j++;
});
},
error: function (obj) {
}
});
});
function changeClass(element) {
$(element).toggleClass('heart');
$(element).toggleClass('hearted');
}
function goUser(element) {
var uid="userid="+$(element).parent().find('.user-id').text();
$.ajax({
type: "POST",
data:uid,
url: "../php/parseuser.php",
cache: false,
success: function (res) {
window.location.href = "../php/profiles.php";
},
error: function (obj) {
}
});
}
$("#searchinput").keypress(function (e) {
var datastring ="search="+$("#searchinput").val();
if (e.which == 13) {
$.ajax({
type: "POST",
data:datastring,
url: "../php/parsesearch.php",
cache: false,
success: function (res) {
window.location.href = "../search/"
},
error: function (obj) {
}
});
}});
function goUser(element) {
var uid="userid="+$(element).parent().find('.user-id').text();
$.ajax({
type: "POST",
data:uid,
url: "../php/parseuser.php",
cache: false,
success: function (res) {
window.location.href = "../php/profiles.php";
},
error: function (obj) {
}
});
}<file_sep>/php/getPP.php
<?php
session_start();
include 'dbconnection.php';
$mid = $_SESSION['mainuid'];
$postid= $_POST['postid'];
$sql = "SELECT * FROM `users` WHERE `users`.`userid` = '$postid'";
$result = $connection->query($sql);
$row = mysqli_fetch_assoc($result);
$url = $row['profilepictureURL'];
echo($url);
?><file_sep>/php/search.php
<?php
session_start();
if(!isset($_SESSION['mainuid']))
{
echo('returntoindex');
return;
}
include 'dbconnection.php';
$search=$_SESSION['lastSearch'];
$sql = "SELECT fname,lname,userid,profilepictureURL,hometown FROM `users` WHERE email like '"."$search". "%' OR hometown like '"."$search"."%' OR fname like '"."$search"."%' OR lname like '"."$search"."%' OR CONCAT(fname,' ',lname) like '"."$search"."%' OR CONCAT(fname,lname) like '"."$search"."%'";
$result = $connection->query($sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows['user'][] = $r;
}
$sqls = "SELECT * FROM `post` WHERE caption like '"."$search". "%'";
$result = $connection->query($sqls);
$posts = array();
while($r = mysqli_fetch_assoc($result)) {
$posts['post'][] = $r;
}
echo json_encode(array("posts" => $posts, "users" => $rows));
?><file_sep>/search/js/index.js
$(document).ready(function() {
$.ajax({
type: "POST",
url: "../php/search.php",
cache: false,
success: function (res) {
if(res=='returntoindex'){
window.location.href = "../index.html"
}
console.log(res);
var obj=$.parseJSON(res);
var poss=(obj.posts.post);
var users = obj.users.user;
var pp = obj.pp;
console.log(obj);
if(pp!=undefined){
var image = ' url("'+pp+'") 50% 50% / cover no-repeat';
$(".profile").css('background',image);}
var $post = $('#main-window').html();
var posts = '';
if(poss!=undefined){
poss.forEach(function (user) {
var single=$post;
posts += single;
});}
if(users!=undefined){
users.forEach(function (user) {
var single=$post;
posts += single;
});}
$('#main-window').html(posts);
var i =0;
var j=0;
$.each($('.post'),function(el){
if(poss!=undefined){
if(i<poss.length){
var image = ' url("'+poss[i].profilepictureURL+'") 50% 50% / cover no-repeat';
$(this).find('.user-img').css('background',image);
//Names
$(this).find('.user-name').text(poss[i].postername);
//Dates
$(this).find('.post-date').text(poss[i].posttime);
$(this).find('.post-id').text(poss[i].postid);
$(this).find('.user-id').text(poss[j].userid);
$(this).find('.content').text(poss[i].caption);
if(poss[i].imageurl!=undefined){
$(this).append('<div class="media photo"><img src="'+poss[i].imageurl+'" alt="post-image"/></div>');
}
i++;}}
else{
var image = ' url("'+users[j].profilepictureURL+'") 50% 50% / cover no-repeat';
$(this).find('.user-img').css('background',image);
$(this).find('.user-name').text(users[j].fname+" "+users[j].lname);
$(this).find('.post-date').text(users[j].hometown);
$(this).find('.user-id').text(users[j].userid);
$(this).find('.content').text("");
$(this).find('.actions').find('.heart').remove();
j++;
}
});
},
error: function (obj) {
}
});
});
function changeClass(element) {
$(element).toggleClass('heart');
$(element).toggleClass('hearted');
}
function goUser(element) {
var uid="userid="+$(element).parent().find('.user-id').text();
$.ajax({
type: "POST",
data:uid,
url: "../php/parseuser.php",
cache: false,
success: function (res) {
window.location.href = "../php/profiles.php"
},
error: function (obj) {
}
});
}
$("#searchinput").keypress(function (e) {
var datastring ="search="+$("#searchinput").val();
if (e.which == 13) {
$.ajax({
type: "POST",
data:datastring,
url: "../php/parsesearch.php",
cache: false,
success: function (res) {
window.location.href = "../search/"
},
error: function (obj) {
}
});
}});<file_sep>/php/edit.php
<?php
include 'dbconnection.php';
session_start();
$userid=$_SESSION['mainuid']
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$nickname=$_POST['nickname'];
$Email=$_POST['email'];
$hometown=$_POST['hometown'];
$Marstatus=$_POST['maritalstatus'];
$pp=$_POST['pp'];
$bio=$_POST['bio'];
if (isset($_POST['fname']) && !empty($_POST['fname']))
{
echo "yup";
echo ".$fname";
echo ".$userid";
$sql="UPDATE users set fname = "."'$fname' WHERE userid= "."'$userid'";
$result= mysql_query($sql,$con);
}
if (isset($_POST['lname']) && !empty($_POST['lname']))
{
$sql="UPDATE users set lname = "."'$lname' WHERE userid= "."'$userid'";
mysql_query($sql,$con);
}
if (isset($_POST['nickname']) && !empty($_POST['nickname']))
{
$sql="UPDATE users set nickname = "."'$nickname' WHERE userid= "."'$userid'";
mysql_query($sql,$con);
}
if (isset($_POST['email']) && !empty($_POST['email']))
{
$sql="UPDATE users set email = "."'$Email' WHERE userid= "."'$userid'";
mysql_query($sql,$con);
}
if (isset($_POST['hometown']) && !empty($_POST['hometown']))
{
$sql="UPDATE users set hometown = "."'$hometown' WHERE userid= "."'$userid'";
mysql_query($sql,$con);
}
if (isset($_POST['maritalstatus']) && !empty($_POST['maritalstatus']))
{
$sql="UPDATE users set maritalstatus = "."'$Marstatus' WHERE userid= "."'$userid'";
mysql_query($sql,$con);
}
}
if (isset($_POST['bio']) && !empty($_POST['bio']))
{
$sql="UPDATE users set bio = "."'$bio' WHERE userid= "."'$userid'";
mysql_query($sql,$con);
}
?><file_sep>/notifications/README.txt
A Pen created at CodePen.io. You can find this one at http://codepen.io/keithpickering/pen/ibtEa.
For a Wordpress theme<file_sep>/php/notifications.php
<?php
include 'dbconnection.php';
session_start();
if(!isset($_SESSION['mainuid']))
{
echo('returntoindex');
return;
}
$mid = $_SESSION['mainuid'];
$sql = "SELECT * FROM `notification` WHERE `userid` = '$mid' AND `status` = 0";
$result = $connection->query($sql);
$table ='';
while ($row = $result->fetch_assoc()) {
$type = $row["type"];
$content=$row["content"];
$id=$row["notificationid"];
if($type=="friend"){
$table.='<div id="'.$id.'" class="flag note note--info" onclick="location.href=\'../php/requests.php\'">
<div class="flag__image note__icon">
<i class="fa fa-info"></i>
</div>
<div class="flag__body note__text">
<p>'.$content.'</p>
</div>
<a id="closer" href="javascript:close(this,'.$id.')" class="note__close" onclick="close(this,'.$id.')">
<i class="fa fa-times"></i>
<p class="noti-id" hidden>'.$id.'</p>
</a>
</div>';
}
else{
$table .= '<div id="'.$id.'" class="flag note">
<div class="flag__image note__icon">
<i class="fa fa-heart"></i>
</div>
<div class="flag__body note__text">'
.$content.'
</div>
<a id="closer" href="javascript:close(this,'.$id.')" class="note__close" onclick="close(this,"'.$id.'")">
<i class="fa fa-times"></i>
<p class="noti-id" hidden>'.$id.'</p>
</a>
</div>';
}
}
echo $table;
?><file_sep>/php/parsesearch.php
<?php
session_start();
include 'dbconnection.php';
$search = $_POST['search'];
$_SESSION['lastSearch']=$search;
?><file_sep>/php/friends.php
<?php
session_start();
if(!isset($_SESSION['mainuid']))
{
echo('returntoindex');
return;
}
include 'dbconnection.php';
$mid=$_SESSION['mainuid'];
$uid1 = $_SESSION['uid'];
$friend = "friend";
$sql = "SELECT userid,CONCAT(fname,' ',lname),nickname,profilepictureURL,hometown
FROM users
WHERE userid in (SELECT userid2
FROM users as u
INNER JOIN friend as f on f.userid1 = u.userid
WHERE u.userid = "."'$uid1'"." AND f.status = "."'$friend'"."
UNION
SELECT userid1
FROM users as u
INNER JOIN friend as f on f.userid2 = u.userid
WHERE u.userid = "."'$uid1'"." AND f.status = "."'$friend'".")";
$result = $connection->query($sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows['user'][] = $r;
}
echo json_encode($rows);
?><file_sep>/php/changepw.php
<?php
include 'dbconnection.php';
session_start();
$userid=$_SESSION['mainuid']
$sql= "SELECT * FROM users WHERE userid= "."'$userid' AND pass="."'<PASSWORD>'";
$result= mysql_query($sql,$con);
if(mysql_num_rows($result) > 0)
{
$sql2="UPDATE users set pass = "."'$<PASSWORD>' WHERE userid= "."'$userid'";
mysql_query($sql2,$con);
}
?><file_sep>/php/login.php
<?php
include 'dbconnection.php';
session_start();
$em = $_POST['email'];
$pass = $_POST['password'];
$hashed = md5($pass);
$sql = "SELECT * FROM `users` WHERE email = "."'$em'". "AND pass = "."'$hashed'";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "username not found";
}
else
{
$row = mysqli_fetch_assoc($result);
$_SESSION['mainuid'] = $row['userid'];
echo "gohome";
}
?><file_sep>/php/remove.php
<?php
include 'dbconnection.php';
session_start();
$userid=$_SESSION['mainuid'];
$sql= "SELECT * FROM `users` WHERE `userid`='$userid'";
$result = $connection->query($sql);
$row = $result->fetch_assoc();
$gender = $row["gender"];
$defaulturl="../img/male.png";
if($gender==0){
$defaulturl="../img/female.png";
}
$sql= "Update users set profilepictureURL="."'$defaulturl' WHERE userid= "."'$userid'";
$result = $connection->query($sql);
header( 'Location: ../home' );
?><file_sep>/php/pp.php
<?php
include 'dbconnection.php';
session_start();
$userid=$_SESSION['mainuid'];
$time = time();
$mid = $_SESSION['mainuid'];
$sql = "SELECT * FROM `users` WHERE userid = "."$mid";
$result = $connection->query($sql);
$postdate = date("Y-m-d h:i:sa");
if ($row = $result->fetch_assoc()){
$postername = $row["nickname"];
}
$target_dir = "../img/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["image"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
$imageurl = "";
if($privacy=='public')
{$ispublic=1;
}
else
{$ispublic=0;
}
$imageurl='../img/post_'.$userid.'_'.$time.'.'.$imageFileType;
if (move_uploaded_file($_FILES["image"]["tmp_name"], $imageurl)) {
$sql = "UPDATE `users` SET `profilepictureURL` = '$imageurl' WHERE userid = '$userid'";
$result = $connection->query($sql);
header( 'Location: ../home' );
exit();
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?><file_sep>/php/registration.php
<?php
include 'dbconnection.php';
$fname = $_POST['fn'];
$lname = $_POST['ln'];
$nname = $_POST['nn'];
$gender = $_POST['gender'];
$em = $_POST['email'];
$pass = $_POST['password'];
$pass = md5($pass);
$dob = $_POST['dob'];
$pieces = explode("/", $dob);
$pp='../img/male.png';
if($gender==0){
$pp='../img/female.png';}
$d = date('Y-m-d',mktime(0,0,0,$pieces[0],$pieces[1],$pieces[2]));
$sql = "SELECT * FROM `users` WHERE email = "."'$em'";
$result = $connection->query($sql);
if ($result->num_rows>0)
{
echo ("username found");
die();
}
else
{
$sql = "INSERT INTO `users`(`fname`, `lname`, `nickname`, `pass`, `email`, `gender`, `birthDate`,`profilepictureURL`) VALUES ('$fname','$lname','$nname','$pass','$em',$gender,'$d','$pp')";
$result = $connection->query($sql);
$querys = "SELECT * FROM `users` WHERE `email` = '$em'";
$result = $connection->query($querys);
$row = mysqli_fetch_assoc($result);
$_SESSION['mainuid'] = $row['userid'];
echo ("gohome");
}
$connection->close();
?><file_sep>/php/isLiked.php
<?php
session_start();
include 'dbconnection.php';
$mid = $_SESSION['mainuid'];
$postid= $_POST['postid'];
$sql = "SELECT * FROM `likes` WHERE `likes`.`userid` = '$mid' AND `likes`.`postid` = '$postid'";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "notliked";
}
else
{
echo "liked";
}
?><file_sep>/js/index.js
$(document).ready(function() {
$("body").hide().fadeIn(1000);
$( function() {
$( "#dob" ).datepicker();
} );
}
);
$(".info-item .btns").click(function () {
$(".container").toggleClass("log-in");
});
function showTick() {
$(".container-form").toggleClass('special');
};
function errorFound() {
$(".container").toggleClass('active');
};
$("#regBtn").click(function () {
var fn = $("#first-name").val().trim();
var ln = $("#last-name").val().trim();
fn=fn.replace(" ", "_");
ln=ln.replace(" ", "_");
var nick = fn+ln;
swal({
title: "Psst...",
text: "What's Your Nickname \n We are Currently calling you :\n <strong>"+nick +"</strong><br> \n Leave it empty if you like our Nickname",
type: 'input',
imageUrl: "img/question.svg",
html: true,
animation: "slide-from-top"
}, function(inputValue){
$("#genderblock").hide();
if(inputValue==""){
register(nick);
}
else{
register(inputValue);
}
});
});
var gender;
$("#male").click((function () {
gender = 1;
}));
$("#female").click((function () {
gender = 0;
}));
function register(nickname) {
$(".container").addClass("active");
var fn = $("#first-name").val();
var ln = $("#last-name").val();
var email = $("#email").val();
var password = $("#password").val();
var dob = $("#dob").val();
var dataString = 'fn=' + fn +'&ln='+ln+ '&email=' + email + '&password=' + password+"&dob="+dob+"&gender="+gender+"&nn="+nickname;
if (!validateReg(email, password, fn,ln,dob)) {
return;
}
$.ajax({
type: "POST",
url: "php/registration.php",
data: dataString,
cache: false,
success: function (res) {
if (res == ("username found")) {
swal("Oops...", "Email Already Exists!", "error", errorFound());
}
else {
showTick();
if (res == "gohome") {
setTimeout(function () {
window.location.href = "home/"
}, 1500);
}
}
},
error: function (obj) {
console.log("Heyyy"+res);
}
});
return false;
}
$("#btnsLog").click(function () {
$(".container").addClass("active");
var password = $("#passwordlog").val();
var email = $("#usernamelog").val();
var dataString ='email=' + email + '&password=' + password;
gender=1;
if (!validateReg(email, password, 'dummy','dummy','dummy')) {
return;
}
$.ajax({
type: "POST",
url: "php/login.php",
data: dataString,
cache: false,
success: function (res) {
if (res == ("username not found")) {
swal("Oops...", "User Doesn't Exist", "error", errorFound());
}
else {
showTick();
$(".container").fadeOut(1000);
console.log(res)
if (res == "gohome") {
setTimeout(function () {
window.location.href = "home/index.html"
}, 1500);
}
}
},
error: function (obj) {
}
});
return false;
});
function validateReg(email, password, fn,ln,dob) {
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.trim() == '' || password.trim() == '' || fn.trim() == ''||ln.trim() == ''||dob.trim() == '') {
swal("Oops...", "Something went wrong!\nPlease Fill all the Fields", "error", errorFound());
return false;
}
if (email.search(emailRegEx) == -1) {
swal("Oops...", "Something went wrong!\nPlease Enter a Valid Email Format", "error", errorFound());
return false;
}
if (gender==null){
swal("Oops...", "Something went wrong!\nPlease Fill all the Fields", "error", errorFound());
return false;
}
return true;
}
<file_sep>/php/requests.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style>
body {
background-color: #5256ad;
color: LightSkyBlue;
text-align: center;
font-size: 35px;
}
.name {
font-size: 30px;
color: white;
}
.friends {
border-bottom: 2px double black;
border-width: 10px;
}
</style>
<body>
<h2 class="friends">Friend Request</h2>
<?php
include 'dbconnection.php';
session_start();
$uid = $_SESSION['uid'];
$mid = $_SESSION['mainuid'];
$pending = "pending";
$friend = "friend";
$sql = "SELECT fname,lname,userid FROM users as u
INNER JOIN friend as f on f.userid1 = u.userid
WHERE f.status = "."'$pending'"." AND f.userid2 = "."'$mid'";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "You have no friend request!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$id = $row["userid"];
$fname = $row["fname"];
$lname = $row["lname"];
$name = $fname." ".$lname;
$button1name = "buttona".$id;
$button2name = "buttoni".$id;
?>
<h2 class="name"><?php echo htmlspecialchars($name);?></h2>
<form method="POST" action="">
<input type="submit" name="<?php echo htmlspecialchars($button1name); ?>" value="Accept">
<input type="submit" name="<?php echo htmlspecialchars($button2name); ?>" value="Ignore">
</form>
<?php
}
$i2=1;
while ($i2<=$id) {
$newbutton1 = "buttona".$i2;
$newbutton2 = "buttoni".$i2;
if (isset($_POST[$newbutton1]))
{
$sql = "UPDATE `friend` SET `status`= "."'$friend'"." WHERE userid2 = "."'$mid'"." AND userid1 = "."'$i2'";
$result = $connection->query($sql);
unset($_POST['newbutton1']);
header("Location: requests.php");
}
elseif (isset($_POST[$newbutton2])) {
$sql = "DELETE FROM `friend` WHERE userid1 = "."'$i2'"." and userid2 = "."'$mid'";
$result = $connection->query($sql);
unset($_POST['newbutton2']);
header("Location: requests.php");
}
$i2 = $i2 + 1;
}
}
?>
</body>
</html><file_sep>/php/parseuser.php
<?php
session_start();
include 'dbconnection.php';
$search = $_POST['userid'];
$_SESSION['uid']=$search;
?><file_sep>/php/friend.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function idclicked(clicked_id)
{
c = clicked_id;
document.forms[0].cid.value = c;
document.getElementById('formtosubmit').submit();
}
</script>
<style>
body {
background-color: #5256ad;
color: LightSkyBlue;
text-align: center;
font-size: 35px;
}
.hyperlinks {
font-size: 30px;
color: white;
}
.hyperlinks:hover {
color: #1daf88;
}
.friends {
border-bottom: 2px double black;
border-width: 10px;
}
</style>
</head>
<body>
<form id="formtosubmit" action="profiles-1.php" method="POST" style="display:none;">
<input type="hidden" name="cid" id="cid" value="">
</form>
<h1 class="friends">Friends</h1>
<?php
include 'dbconnection.php';
session_start();
$sql = "SELECT userid,CONCAT(fname,' ',lname),nickname
FROM users
WHERE userid in (SELECT userid2
FROM users as u
INNER JOIN friend as f on f.userid1 = u.userid
WHERE u.userid = "."'$uid1'"." AND f.status = "."'$friend'"."
UNION
SELECT userid1
FROM users as u
INNER JOIN friend as f on f.userid2 = u.userid
WHERE u.userid = "."'$uid1'"." AND f.status = "."'$friend'".")";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "You have no friends yet!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$friend = $row["CONCAT(fname,' ',lname)"];
$id = $row["userid"];
?>
<a class = "hyperlinks" id="<?php echo htmlspecialchars($id); ?>" href = "#" onclick="idclicked(this.id)" > <?php echo "$friend<br>"; ?></a>
<?php
}
}
?>
</body>
</html>
<file_sep>/php/dbconnection.php
<?php
$serverName = 'mysql5006.mywindowshosting.com';
$userName = 'a15748_dbproj';
$password = '<PASSWORD>';
$databaseName = 'db_a15748_dbproj';
//$serverName = 'localhost';
//$userName = 'root';
//$password = '';
//$databaseName = 'db_project';
$connection = new mysqli($serverName,$userName,$password,$databaseName);
?><file_sep>/profiles.php
<?php
include 'dbconnection.php';
session_start();
$uid = $_SESSION['uid'];
$mid = $_SESSION['mainuid'];
if (isset($_POST['cid'])) {
$uid = $_POST['cid'];
$_SESSION['uid'] = $uid;
}
print_r($_SESSION);
$sql = "SELECT * FROM `users` WHERE userid = "."$uid";
$result = $connection->query($sql);
if ($row = $result->fetch_assoc())
{
$em = $row["email"];
$fname = $row["fname"];
$lname = $row["lname"];
$nname = $row["nickname"];
$gender = $row["gender"];
$dob = $row["birthDate"];
$hometown = $row["hometown"];
$mstatus = $row["maritalstatus"];
$bio = $row["bio"];
$ppurl = $row["profilepictureURL"];
if ($gender == 0)
{
$gender = "Male";
}
else
{
$gender = "Female";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1><?php echo "$fname $lname"; ?></h1>
<?php echo "<img src='" . $ppurl . "' alt='error' width='250px' height='250px'>"?>
<h4><?php echo "Nickname: $nname"."<br>"."Email: $em"."<br>"."Gender: $gender"."<br>"."Marital Status: $mstatus"."<br>"."Hometown: $hometown"; ?></h4>
<?php
if($uid==$mid) //dah el user beyefta7 el prfile beta3o
{
?>
<h4><?php echo "Date Of Birth: $dob"."<br>"."Bio:<br>$bio" ?></h4>
<form method="POST" action="editprofile.php">
<input type="submit" name="editprofile" value="Edit Profile">
<a href="friends.php">Friends</a><br><br>
</form>
<form method="POST" action="profiles.php">
<br><textarea name="post" placeholder="Write post" rows="5" cols="40"></textarea>
<select name="ispublic">
<option value="true" selected="selected">Public</option>
<option value="false">Private</option>
</select><br><br>
<input type="submit" name="submit" value="Post"><br><br>
</form>
<form action="requests.php" method="POST">
<input type="submit" name="requests" value="Requests">
</form>
<?php
if (isset($_POST['submit']))
{
unset($_POST['submit']);
$post = $_POST['post'];
$postdate = date("Y-m-d h:i:sa");
$imageurl = "";
$ispublic = $_POST['ispublic'];
$sql = "INSERT INTO `post`(`postername`, `caption`, `posttime`, `imageurl`, `ispublic`, `userid`) VALUES ('$nname','$post','$postdate','imageurl',$ispublic,'$mid')";
$result = $connection->query($sql);
}
$sql = "SELECT * FROM `post` WHERE userid = "."'$uid' ORDER BY posttime DESC";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "You have no posts yet!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$caption = $row["caption"];
$postername = $row["postername"];
$posttime = $row["posttime"];
$numberoflikes = $row["numberoflikes"];
$imageurl = $row["imageurl"];
$public = $row["ispublic"];
echo "-------------------------"."<br>";
echo "$postername"."<br>"."$caption"."<br>"."Likes: $numberoflikes"."<br>"."$posttime"."<br>"."<br>";
}
}
}
else
{
$sql = "SELECT status FROM `friend` WHERE userid1 = "."'$mid'"." AND userid2 = "."'$uid'";
$result = $connection->query($sql);
if ($row = $result->fetch_assoc()) // yeb2a ya friend ya pending
{
$status = $row["status"];
if ($status == "friend")
{
?><h4><?php echo "Date Of Birth: $dob"."<br>"."Bio:<br>$bio" ?></h4>
<form method="POST" action="">
<input type="submit" name="removefriend" value="Remove Friend">
</form>
<a href="friends.php">Friends</a><br><br>
<?php
if (isset($_POST['removefriend'])) {
$sql = "DELETE FROM `friend` WHERE (userid1='$mid' and userid2='$uid' and status='friend') OR (userid1='$uid' and userid2='$mid' and status='friend')";
$result = $connection->query($sql);
header("Location: profiles.php");
}
$sql = "SELECT * FROM `post` WHERE userid = "."'$uid' ORDER BY posttime DESC";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "Friend has no posts yet!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$caption = $row["caption"];
$postername = $row["postername"];
$posttime = $row["posttime"];
$numberoflikes = $row["numberoflikes"];
$imageurl = $row["imageurl"];
$public = $row["ispublic"];
echo "-------------------------"."<br>";
echo "$postername"."<br>"."$caption"."<br>"."Likes: $numberoflikes"."<br>"."$posttime"."<br>"."<br>";
}
}
}
else
{
?> <form method="POST" action="">
<input type="submit" name="pending" value="Pending">
</form>
<?php
if (isset($_POST['pending'])) {
$sql = "DELETE FROM `friend` WHERE userid1 = "."'$mid'"." and userid2 = "."'$uid'";
$result = $connection->query($sql);
header("Location: profiles.php");
}
$sql = "SELECT * FROM `post` WHERE userid = "."'$uid'"." AND ispublic = true ORDER BY posttime DESC";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "User has no posts yet!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$caption = $row["caption"];
$postername = $row["postername"];
$posttime = $row["posttime"];
$numberoflikes = $row["numberoflikes"];
$imageurl = $row["imageurl"];
$public = $row["ispublic"];
echo "-------------------------"."<br>";
echo "$postername"."<br>"."$caption"."<br>"."Likes: $numberoflikes"."<br>"."$posttime"."<br>"."<br>";
}
}
}
}
else // yeb2a dah msh friend
{
?> <form method="POST" action="profiles.php">
<input type="submit" name="add" value="Add friend">
</form>
<?php
if (isset($_POST['add'])) {
$sql = "INSERT INTO `friend`(`userid1`, `userid2`, `status`) VALUES ($mid,$uid,'pending')";
$result = $connection->query($sql);
header("Location: profiles.php");
}
$sql = "SELECT * FROM `post` WHERE userid = "."'$uid'"." AND ispublic = true ORDER BY posttime DESC";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "User has no posts yet!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$caption = $row["caption"];
$postername = $row["postername"];
$posttime = $row["posttime"];
$numberoflikes = $row["numberoflikes"];
$imageurl = $row["imageurl"];
$public = $row["ispublic"];
echo "-------------------------"."<br>";
echo "$postername"."<br>"."$caption"."<br>"."Likes: $numberoflikes"."<br>"."$posttime"."<br>"."<br>";
}
}
}
}
?>
</body>
</html><file_sep>/php/home.php
<?php
include 'dbconnection.php';
session_start();
if(!isset($_SESSION['mainuid']))
{
echo('returntoindex');
return;
}
$mid = $_SESSION['mainuid'];
$sql = "SELECT p.userid, p.caption, p.posttime,p.postid,p.postername,p.imageurl
FROM post p
WHERE ispublic=1 OR p.userid= '$mid'
UNION SELECT DISTINCT p.userid, p.caption, p.posttime,p.postid,p.postername,p.imageurl
FROM post p
INNER JOIN friend f ON p.userid=f.userid2 OR p.userid=f.userid1
INNER JOIN users u ON f.userid1= '$mid' OR f.userid2= '$mid'
WHERE p.ispublic=0 ORDER BY posttime DESC";
$result = $connection->query($sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows['user'][] = $r;
}
$sql="SELECT `profilepictureURL` from `users` WHERE userid =".$mid;
$result = $connection->query($sql);
$row = $result->fetch_assoc();
$sql="SELECT COUNT(userid) as count FROM notification WHERE userid=".$mid." AND `status`=0";
$result = $connection->query($sql);
$rowsa = $result->fetch_assoc();
$count = $rowsa["count"];
echo json_encode(array("posts" => $rows, "pp" => $row["profilepictureURL"],"noti"=>$count));
$connection->close();
?><file_sep>/php/profiles.php
<?php
include 'dbconnection.php';
session_start();
$uid = $_SESSION['uid'];
$mid = $_SESSION['mainuid'];
if (isset($_POST['cid'])) {
$uid = $_POST['cid'];
$_SESSION['uid'] = $uid;
}
$sql = "SELECT * FROM `users` WHERE userid = "."$uid";
$result = $connection->query($sql);
$ppurl = "module_table_bottom";
$em="";
$fname="";
$lnam="";
$gender=0;
$genders="Female";
if ($row = $result->fetch_assoc())
{
$em = $row["email"];
$fname = $row["fname"];
$lname = $row["lname"];
$nname = $row["nickname"];
$gender = $row["gender"];
$dob = $row["birthDate"];
$hometown = $row["hometown"];
$mstatus = $row["maritalstatus"];
$bio = $row["bio"];
$ppurl = $row["profilepictureURL"];
if ($gender == 1)
{
$genders = "Male";
}
else
{
$genders = "Female";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style>
body {
background-color: #5256ad;
color: LightSkyBlue;
text-align: center;
font-size: 35px;
color: white;
}
div.image {
}
.submitbtn{
width: 250px;
height: 30px;
box-sizing: border-box;
border: 3px solid MidnightBlue;
background-color: #1daf88;
}
.submitbtn:hover{
font-weight: bold;
cursor: pointer;
}
.links{
color: #1daf88;
}
.links:hover{
font-weight: bold;
cursor: pointer;
}
</style>
<body>
<div class="image">
<?php echo "<img src='" . $ppurl . "' alt='error' width='250px' height='250px'>"?>
</div>
<h1><?php echo "$fname $lname"; ?></h1>
<h4><?php echo "Nickname: $nname"."<br>"."Email: $em"."<br>"."Gender: $genders"."<br>"."Marital Status: $mstatus"."<br>"."Hometown: $hometown"; ?></h4>
<?php
if($uid==$mid) //dah el user beyefta7 el prfile beta3o
{
?>
<h4><?php echo "Date Of Birth: $dob"."<br>"."Bio:<br>$bio" ?></h4>
<form method="POST" action="../EditProfile.html">
<input class="submitbtn" type="submit" name="editprofile" value="Edit Profile"><br><br>
<a class = "links" href="../friends/">Friends</a><br><br>
</form>
<form action="requests.php" method="POST">
<input class="submitbtn" type="submit" name="requests" value="Requests">
</form>
<?php
if (isset($_POST['submit']))
{
unset($_POST['submit']);
$post = $_POST['post'];
$postdate = date("Y-m-d h:i:sa");
$imageurl = "";
$ispublic = $_POST['ispublic'];
$sql = "INSERT INTO `post`(`postername`, `caption`, `posttime`, `imageurl`, `ispublic`, `userid`) VALUES ('$nname','$post','$postdate','imageurl',$ispublic,'$mid')";
$result = $connection->query($sql);
}
$sql = "SELECT * FROM `post` WHERE userid = "."'$uid' ORDER BY posttime DESC";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "You have no posts yet!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$caption = $row["caption"];
$postername = $row["postername"];
$posttime = $row["posttime"];
$numberoflikes = $row["numberoflikes"];
$imageurl = $row["imageurl"];
$public = $row["ispublic"];
echo "-------------------------"."<br>";
echo "$postername"."<br>"."$caption"."<br>"."$posttime"."<br>"."<br>";
}
}
}
else
{
$sql = "SELECT status FROM `friend` WHERE userid1 = "."'$mid'"." AND userid2 = "."'$uid' OR userid1 = "."'$uid'"." AND userid2 = "."'$mid'";
$result = $connection->query($sql);
if ($row = $result->fetch_assoc()) // yeb2a ya friend ya pending
{
$status = $row["status"];
if ($status == "friend")
{
?><h4><?php echo "Date Of Birth: $dob"."<br>"."Bio:<br>$bio" ?></h4>
<form method="POST" action="">
<input type="submit" name="removefriend" value="Remove Friend">
</form>
<a class="links" href="../friends/">Friends</a><br><br>
<?php
if (isset($_POST['removefriend'])) {
$sql = "DELETE FROM `friend` WHERE (userid1='$mid' and userid2='$uid' and status='friend') OR (userid1='$uid' and userid2='$mid' and status='friend')";
$result = $connection->query($sql);
header("Location: profiles.php");
}
$sql = "SELECT * FROM `post` WHERE userid = "."'$uid' ORDER BY posttime DESC";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "Friend has no posts yet!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$caption = $row["caption"];
$postername = $row["postername"];
$posttime = $row["posttime"];
$numberoflikes = $row["numberoflikes"];
$imageurl = $row["imageurl"];
$public = $row["ispublic"];
echo "-------------------------"."<br>";
echo "$postername"."<br>"."$caption"."<br>"."Likes: $numberoflikes"."<br>"."$posttime"."<br>"."<br>";
}
}
}
else
{
?> <form method="POST" action="">
<input type="submit" name="pending" value="Pending">
</form>
<?php
if (isset($_POST['pending'])) {
$sql = "DELETE FROM `friend` WHERE userid1 = "."'$mid'"." and userid2 = "."'$uid'";
$result = $connection->query($sql);
header("Location: profiles.php");
}
$sql = "SELECT * FROM `post` WHERE userid = "."'$uid'"." AND ispublic = true ORDER BY posttime DESC";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "User has no posts yet!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$caption = $row["caption"];
$postername = $row["postername"];
$posttime = $row["posttime"];
$numberoflikes = $row["numberoflikes"];
$imageurl = $row["imageurl"];
$public = $row["ispublic"];
echo "-------------------------"."<br>";
echo "$postername"."<br>"."$caption"."<br>"."Likes: $numberoflikes"."<br>"."$posttime"."<br>"."<br>";
}
}
}
}
else // yeb2a dah msh friend
{
$sql = "SELECT * FROM `friend` WHERE userid2 ="."'$mid'"."AND userid1 = "."'$uid'";
$result = $connection->query($sql);
if ($result->num_rows>0)
{
?>
<h2><?php echo htmlspecialchars($nname)?> sent you a friend request!</h2>
<?php
$sql = "SELECT * FROM `post` WHERE userid = "."'$uid'"." AND ispublic = true ORDER BY posttime DESC";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "User has no posts yet!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$caption = $row["caption"];
$postername = $row["postername"];
$posttime = $row["posttime"];
$numberoflikes = $row["numberoflikes"];
$imageurl = $row["imageurl"];
$public = $row["ispublic"];
echo "-------------------------"."<br>";
echo "$postername"."<br>"."$caption"."<br>"."Likes: $numberoflikes"."<br>"."$posttime"."<br>"."<br>";
}
}
}
else{
?> <form method="POST" action="profiles.php">
<input type="submit" name="add" value="Add friend">
</form>
<?php
if (isset($_POST['add'])) {
$type = "friend";
$status = 0;
$sql = "INSERT INTO `friend`(`userid1`, `userid2`, `status`) VALUES ($mid,$uid,'pending')";
$result = $connection->query($sql);
$sql = "Select nickname from users where userid = "."$mid";
$result = $connection->query($sql);
if ($result->num_rows>0)
{
while ($row = $result->fetch_assoc())
{
$nname2 = $row['nickname'];
}
}
$content = "$nname2 added you as a friend";
$sql = "INSERT INTO `notification`(`content`, `status`, `type`, `userid`) VALUES ('$content',$status,'$type','$uid')";
$result = $connection->query($sql);
header("Location: profiles.php");
}
$sql = "SELECT * FROM `post` WHERE userid = "."'$uid'"." AND ispublic = true ORDER BY posttime DESC";
$result = $connection->query($sql);
if ($result->num_rows<=0)
{
echo "User has no posts yet!";
die();
}
else
{
while ($row = $result->fetch_assoc())
{
$caption = $row["caption"];
$postername = $row["postername"];
$posttime = $row["posttime"];
$numberoflikes = $row["numberoflikes"];
$imageurl = $row["imageurl"];
$public = $row["ispublic"];
echo "-------------------------"."<br>";
echo "$postername"."<br>"."$caption"."<br>"."Likes: $numberoflikes"."<br>"."$posttime"."<br>"."<br>";
}
}
}}
}
?>
</body>
</html><file_sep>/php/like.php
<?php
session_start();
include 'dbconnection.php';
$mid = $_SESSION['mainuid'];
$postid= $_POST['postid'];
$sql = "INSERT INTO `likes`(`userid`, `postid`) VALUES ('$mid','$postid')";
$result = $connection->query($sql);
$sql = "SELECT * FROM `post` WHERE `postid` = '$postid'";
$result = $connection->query($sql);
$row = mysqli_fetch_assoc($result);
$user = $row['userid'];
$sql = "SELECT * FROM `users` WHERE `userid` = '$mid'";
$result = $connection->query($sql);
$row = mysqli_fetch_assoc($result);
$liker = $row['nickname'];
$content = $liker.' has liked your post';
$status = 0;
$type = 'like';
$userid = $user;
$sql="INSERT INTO `notification`( `content`, `status`, `type`, `userid`) VALUES ('$content',$status,'$type','$userid')";
$result = $connection->query($sql);
?><file_sep>/php/removeNoti.php
<?php
session_start();
include 'dbconnection.php';
$mid = $_SESSION['mainuid'];
$postid= $_POST['noti'];
$sql = "UPDATE `notification` SET `status`=1 WHERE `notificationid`='$postid'";
$result = $connection->query($sql);
?> | 672c37dfa13456a80d50b9fdc273c6c6583a5b24 | [
"JavaScript",
"Text",
"PHP"
] | 25 | JavaScript | MahmoudAbdelRazik95/WhateverSocial | 072679f561f8bc9ba39ab3366e249d628911cb2f | 7ef4fce78751e83f6512d3af064806d43e6f9160 |
refs/heads/master | <file_sep>package com.cathy.customer.api.model;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import com.cathy.customer.domain.Customer;
/**
* API model with details required to create a product.
*
* @author Cathy
*/
public class CreateOrUpdateCustomerPayload {
@NotNull
@NotBlank
private String firstname;
@NotNull
@NotBlank
private String lastname;
@NotNull
@NotBlank
@NumberFormat
private String ssn;
@NotNull
@NotBlank
private String address;
@NumberFormat
private String phone;
@Email
private String email;
@NotNull
@NotBlank
@NumberFormat
private int amount;
@DateTimeFormat
private Date duedate;
@DateTimeFormat
private Date applydate;
private boolean approve;
public String getFirstname() {
return firstname;
}
public CreateOrUpdateCustomerPayload setFirstname(String firstname) {
this.firstname = firstname;
return this;
}
public String getLastname() {
return lastname;
}
public CreateOrUpdateCustomerPayload setLastname(String lastname) {
this.lastname = lastname;
return this;
}
public String getSsn() {
return ssn;
}
public CreateOrUpdateCustomerPayload setSsn(String ssn) {
this.ssn = ssn;
return this;
}
public String getAddress() {
return address;
}
public CreateOrUpdateCustomerPayload setAddress(String address) {
this.address = address;
return this;
}
public String getPhone() {
return phone;
}
public CreateOrUpdateCustomerPayload setPhone(String phone) {
this.phone = phone;
return this;
}
public String getEmail() {
return email;
}
public CreateOrUpdateCustomerPayload setEmail(String email) {
this.email = email;
return this;
}
public int getAmount() {
return amount;
}
public CreateOrUpdateCustomerPayload setAmount(int amount) {
this.amount = amount;
return this;
}
public Date getDuedate() {
return duedate;
}
public CreateOrUpdateCustomerPayload setDuedate(Date duedate) {
this.duedate = duedate;
return this;
}
public Date getApplydate() {
return applydate;
}
public CreateOrUpdateCustomerPayload setApplydate(Date applydate) {
this.applydate = applydate;
return this;
}
public boolean isApprove() {
return approve;
}
public CreateOrUpdateCustomerPayload setApprove(boolean approve) {
this.approve = approve;
return this;
}
}
<file_sep>package com.cathy.customer.api;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.cathy.customer.api.mapper.CustomerMapper;
import com.cathy.customer.api.model.CreateOrUpdateCustomerPayload;
import com.cathy.customer.api.model.QueryCustomerResult;
import com.cathy.customer.domain.Customer;
import com.cathy.customer.service.CustomerService;
@Component
@Path("customers")
public class CustomerResource {
@Context
private UriInfo uriInfo;
@Autowired
private CustomerMapper customerMapper;
@Autowired
private CustomerService customerService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getCustomers() {
List<Customer> customers = customerService.getCustomers();
List<QueryCustomerResult> queryResults = customers.stream().map(customerMapper::toQueryCustomerResult).collect(Collectors.toList());
return Response.ok(queryResults).build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createCustomer(@Valid @NotNull CreateOrUpdateCustomerPayload customerPayload) {
Customer customer = customerMapper.toCustomer(customerPayload);
String id = customerService.createCustomer(customer);
return Response.created(uriInfo.getAbsolutePathBuilder().path(id).build()).build();
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getCustomer(@PathParam("id") String id) {
Customer customer = customerService.getCustomer(id);
QueryCustomerResult queryResult = customerMapper.toQueryCustomerResult(customer);
return Response.ok(queryResult).build();
}
@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateCustomer(@PathParam("id") String id, @Valid @NotNull CreateOrUpdateCustomerPayload payload) {
Customer customer = customerService.getCustomer(id);
customerMapper.updateCustomer(payload, customer);
customerService.updateCustomer(customer);
return Response.noContent().build();
}
@DELETE
@Path("{id}")
public Response deleteCustomer(@PathParam("id") String id) {
customerService.deleteCustomer(id);
return Response.noContent().build();
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.cathy</groupId>
<artifactId>microservice-loan</artifactId>
<version>1.5</version>
</parent>
<groupId>com.cathy.customer</groupId>
<artifactId>customer-service</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring Boot dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- Spring Cloud dependencies -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
<!-- Jackson dependencies -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<!-- MapStruct -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<!-- API Commons -->
<dependency>
<groupId>${parent.groupId}</groupId>
<artifactId>api-commons</artifactId>
<version>${parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
<file_sep># Customer Profile Managment System
This is POC project of **Customer Profile Managment System**. It is a web based appication using **Microservice** architecture with **Spring Boot, Spring Cloud and JMS**. Users can sumbit, manage, check their profile (personal information) through this web system.
This project provide the backend functionality of this system. There are 4 serbices created for accomplish this functionality. They are **_Netflix Eureka Service, API Gateway, Customer Service, Customer Profile Service._**
## Netflix Eureka Service
This service (**service-discovery**) is used to discover and register other services. The annotation:
```
@EnableEurekaServer
```
## Customer Service
This **customer-service** is a **RESTful** web service using **Jersey (JAX-RS)** implementation. This REST API perfomrs CRUD operation on the customer resource to retrieve and return data from database. Users can update and create their own information through **PUT** and **POST** methods and manager or employee can search specified customer based on customer id using **GET** method. This service connected to the **MongoDB** database using Spring Data for persisting the customer data - the personal information of user. Relational annotations:
```
@Component
@Path //specify the relative path of class and methods
@GET
@PUT
@POST
@DELETE
@Produce //states the HTTP response generated by web service
@Consume //states the HTTP request type
```
In order to access the JAX-RS resource from Spring Boot Application, this resource should be registered as **Jersey resource**.
```
@Component
@ApplicationPath("api")
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
registerResources();
registerProviders();
}
private void registerResources() {
register(CustomerResource.class);
}
private void registerProviders() {
register(ObjectMapperContextResolver.class);
register(ConstraintViolationExceptionMapper.class);
register(GenericExceptionMapper.class);
register(JsonMappingExceptionMapper.class, 1);
register(JsonParseExceptionMapper.class, 1);
}
}
```
Register for Eureka Server:
```
@EnableDiscoveryClient //I used
```
Or
```
@EnableEurekaClient
```
## Customer Profile Server
This **customer-profile-server** is also a **RESTful** web service which has same implementation as customer-service. It connected to the **MongoDB** database using Spring Data for persisting customer profile data including profile Id, customer and created date. The customer data are transformed from customer service using Spring Cloud Stream-**Rabbit MQ**, which is a message broker between these 2 services for communication.
Considering the highly demanding of customer data, I configured and enable a data **caching** for customer data to improve application performance. Thus, customer data can be read from cache instead from database which is faster. But cache has a limited memory storage, I **evict** the expired customer data which are not frequently used from cache when the cache is full. Related annotations:
```
@EnableCaching
@CacheEvict(cacheNames = CachingConfiguration.CUSTOMER_CACHE, key="#customer.id")
```
## API Gateway
It consist of **Netflix Zuul Proxy** and **Spring Security JWT**. It works as a single point of interaction for different operations. Spring Security which handles the authentication and authorization at the web request level. It uses JWT for authentication by verifying user’s credentials and generate access token. The Zuul proxy will routing the client business request by communicating to relevant Microservice endpoints.
<file_sep><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cathy</groupId>
<artifactId>microservice-loan</artifactId>
<packaging>pom</packaging>
<version>1.5</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- Spring Boot and Spring Cloud versions must be compatible -->
<!-- See more: http://projects.spring.io/spring-cloud/#release-trains -->
<spring-boot.version>1.5.8.RELEASE</spring-boot.version>
<spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
<mapstruct.version>1.2.0.Final</mapstruct.version>
</properties>
<modules>
<module>service-discovery</module>
<module>api-gateway</module>
<module>api-commons</module>
<module>customer-service</module>
<module>customer-profile-service</module>
</modules>
</project>
<file_sep>package com.cathy.customer.service;
import java.util.List;
import javax.ws.rs.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import org.springframework.stereotype.Service;
import com.cathy.customer.domain.Customer;
import com.cathy.customer.repository.CustomerRepository;
@Service
public class CustomerService {
@Autowired
private CustomerRepository customerRepository;
@Autowired
@Qualifier(CustomerOutputChannel.CUSTOMER_DELETED_OUTPUT)
private MessageChannel customerDeletedMessageChannel;
@Autowired
@Qualifier(CustomerOutputChannel.CUSTOMER_UPDATED_OUTPUT)
private MessageChannel customerUpdatedMessageChannel;
public List<Customer> getCustomers() {
return customerRepository.findAll();
}
public String createCustomer(Customer customer) {
customer = customerRepository.save(customer);
return customer.getId();
}
public void updateCustomer(Customer customer) {
customer = customerRepository.save(customer);
customerUpdatedMessageChannel.send(MessageBuilder.withPayload(customer).build());
}
public Customer getCustomer(String id) {
Customer customer = customerRepository.findOne(id);
if (customer == null) {
throw new NotFoundException();
}
return customer;
}
public void deleteCustomer(String id) {
Customer customer = customerRepository.findOne(id);
if (customer == null) {
throw new NotFoundException();
} else {
customerRepository.delete(id);
customerDeletedMessageChannel.send(MessageBuilder.withPayload(customer).build());
}
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.cathy</groupId>
<artifactId>microservice-loan</artifactId>
<version>1.5</version>
</parent>
<artifactId>api-commons</artifactId>
<dependencyManagement>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring Boot dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<!-- Jackson dependencies -->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| a85631e65ddabea244356bbd830a9c9c5d631c16 | [
"Markdown",
"Java",
"Maven POM"
] | 7 | Java | xinyuanliu-222/microservice-loan-customer-profile | 8ac153c33b6ace0a4732735c2827f2068dcc96d8 | 63be2cc3c8c4468fb78c5ec4f6b0d0d3a1796094 |
refs/heads/master | <repo_name>jsayol/github-issue-labeler<file_sep>/src/util.ts
/**
* Implements a Fisher–Yates shuffling algorithm to shuffle
* in place a set of arrays, while also maintaining the same order
* between all the given arrays.
*/
export function shuffleArrays(arrays: any[][]): any[][] {
let currentIndex = arrays[0].length;
let randomIndex;
let tempValue;
// While there are still elements to shuffle in the arrays
while (currentIndex !== 0) {
// Pick one of the remaining positions at random
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// Swap the elements at that position with the current ones
for (const array of arrays) {
tempValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = tempValue;
}
}
return arrays;
}
<file_sep>/src/index.ts
import { downloadIssues } from './download';
import { buildDictionary, dataStats, saveDictionary } from './dictionary';
import { outputJSON, readJSON } from 'fs-extra';
import { resolve } from 'path';
import { getTrainingData, saveTrainingData, loadTrainingData } from './data';
import { trainModel, testModel } from './train';
// Promise.resolve().then(async () => {
// await downloadIssues('firebase', 'firebase-js-sdk');
// const dict = await buildDictionary();
// await saveDictionary(dict);
// const labels = [
// 'Component-Auth',
// 'Component-Core',
// 'Component-Database',
// 'Component-Firestore',
// 'Component-Functions',
// 'Component-Messaging',
// 'Component-Storage',
// 'feature-request'
// ];
// const data = await getTrainingData(labels);
// await saveTrainingData(data);
// const model = await trainModel(data);
// testModel(model, data);
// });
// downloadIssues('firebase', 'firebase-js-sdk').then(() => process.exit());
// buildDictionary().then(async dict => {
// console.log('Dictionary size:', dict.size);
// await saveDictionary(dict);
// });
// const labels = [
// 'Component-Auth',
// 'Component-Core',
// 'Component-Database',
// 'Component-Firestore',
// 'Component-Functions',
// 'Component-Messaging',
// 'Component-Storage',
// 'feature-request'
// ];
// getTrainingData(labels).then(async data => {
// await saveTrainingData(data);
// const model = await trainModel(data);
// testModel(model, data);
// });
// const data = loadTrainingData();
// trainModel(data).then(model => {
// return testModel(model, data);
// });
<file_sep>/src/dictionary.ts
import { readdir, outputJSON } from 'fs-extra';
import { resolve } from 'path';
import { Issue } from './types';
/**
* The maximum number of words to take into account from
* each issue, including title and description.
*/
export const MAX_WORDS_PER_ENTRY = 1000;
/**
* Dictionary entry corresponding to a padding.
*/
export const DICT_ENTRY_PADDING = 0;
/**
* Dictionary entry corresponding to an unknown word.
*/
export const DICT_ENTRY_UNKNOWN = 1;
const DATA_DIR = '../data';
let dictionary: Map<string, number>;
/**
* Build the dictionary based on the words found in the learning issues.
*/
export async function buildDictionary(): Promise<Map<string, number>> {
const dictWordSet = new Set<string>();
const files = await readdir(resolve(__dirname, DATA_DIR, 'issues'));
for (const file of files) {
const issue: Issue = require(resolve(__dirname, DATA_DIR, 'issues', file));
const text = issue.title + ' ' + issue.body;
for (const word of textToWords(text)) {
dictWordSet.add(word);
}
}
// Once we have a set with all the words, we build a dictionary where
// each word corresponds to an integer.
// Integers 0-4 are reserved for internal use.
let entryNum = 5;
const dict = new Map<string, number>();
for (const word of dictWordSet) {
dict.set(word, entryNum++);
}
if (!dictionary) {
dictionary = dict;
}
return dict;
}
export function saveDictionary(dict: Map<string, number>) {
return outputJSON(resolve(__dirname, DATA_DIR, 'dictionary.json'), [...dict]);
}
/**
* Converts a string of text to an array of words.
* Any code blocks are removed, along with anything that
* doesn't look like a word.
*/
export function textToWords(text: string): string[] {
let words = text
.replace(/```(\w+)([^```]+)```/g, ' ')
.replace(/([^\w]+)/g, ' ')
.toLowerCase()
.split(/\s+/)
.filter(word => !/^(|(#+)|(\*+)|(\d+))$/.test(word));
words.splice(MAX_WORDS_PER_ENTRY);
return words;
}
export function dataStats(data: number[][]) {
const stats = {
min: Number.POSITIVE_INFINITY,
max: Number.NEGATIVE_INFINITY,
len: data.length
};
for (const entry of data) {
const length = entry.length;
stats.min = Math.min(stats.min, length);
stats.max = Math.max(stats.max, length);
}
return stats;
}
export function getDictionary(): Map<string, number> {
if (!dictionary) {
dictionary = new Map<string, number>(
require(resolve(__dirname, DATA_DIR, 'dictionary.json'))
);
}
return dictionary;
}
<file_sep>/src/types.d.ts
export interface Issue {
url: string;
repository_url: string;
labels_url: string;
comments_url: string;
events_url: string;
html_url: string;
id: number;
node_id: string;
number: number;
title: string;
user: User;
labels: Label[];
state: 'open' | 'closed';
locked: boolean;
assignee: User;
assignees: User[];
milestone: null;
comments: number;
created_at: string;
updated_at: string;
closed_at: string | null;
body: string;
score: number;
}
export interface User {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: '';
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: 'User';
site_admin: false;
}
export interface Label {
id: number;
node_id: string;
url: string;
name: string;
color: string;
default: false;
}
export interface PullRequestInfo {
url: string;
html_url: string;
diff_url: string;
patch_url: string;
}
export interface IssueOrPullRequest extends Issue {
pull_request: PullRequestInfo;
author_association?: 'CONTRIBUTOR';
}
<file_sep>/README.md
This was an experiment to see if I could train a neural network to classify GitHub issues and automatically apply the corresponding labels.
The [repo](https://github.com/firebase/firebase-js-sdk/) I've used to test it has about 620 issues, which I'd say is fairly representative of the average GitHub project. Considering some of those need to be set aside as testing and validation datasets, that leaves barely 400 samples to train the network.
I still want to tweak some parameters of the model and play with different layer structures and optimimizers, but for now I'd say the available dataset is just not sufficient to train it successfully.
<file_sep>/src/train.ts
// Choo choo! 🚂 🚆 🚄 🚅 🚉 🚞 🚝 🛤️ 🚈
import * as tf from '@tensorflow/tfjs';
import '@tensorflow/tfjs-node';
import {
dataStats,
MAX_WORDS_PER_ENTRY,
getDictionary,
DICT_ENTRY_PADDING
} from './dictionary';
import { TrainingData } from './data';
import { ModelFitConfig } from '@tensorflow/tfjs';
/**
* Pads the data array in place, adding 0's at the end of each
* entry.
*/
export function padData(data: number[][]): number[][] {
const stats = dataStats(data);
const padLength = Math.min(MAX_WORDS_PER_ENTRY, stats.max);
for (const entry of data) {
const entryLength = entry.length;
if (entryLength < padLength) {
entry.length = padLength;
entry.fill(DICT_ENTRY_PADDING, entryLength);
}
}
return data;
}
/**
* Builds and trains the model with the trainign data.
*/
export async function trainModel(data: TrainingData): Promise<tf.Model> {
const dictionary = getDictionary();
const hiddenUnits = 16 * data.labels.length;
const model = tf.sequential({
layers: [
tf.layers.embedding({
inputDim: dictionary.size + 5, // There's 5 reserved extra positions in the dictionary
outputDim: hiddenUnits
}),
tf.layers.globalAveragePooling1d({}),
tf.layers.dense({ units: hiddenUnits, activation: 'sigmoid' }),
tf.layers.dense({ units: data.labels.length, activation: 'softmax' })
]
});
// Tensors
const xTensor = tf.tensor2d(padData(data.training.inputs), void 0, 'int32');
const yTensor = tf.tensor2d(data.training.outputs, void 0, 'float32');
// Create an optimizer
const learningRate = 0.02;
const optimizer = tf.train.sgd(learningRate);
// Compile the model
model.compile({
optimizer,
loss: 'meanSquaredError'
});
// Train the model
const options: ModelFitConfig = {
epochs: 50,
shuffle: true,
validationSplit: 0.1
};
const result = await model.fit(xTensor, yTensor, options);
console.log(result);
// Dispose of any data we don't need anymore, to free memory up
xTensor.dispose();
yTensor.dispose();
return model;
}
export function testModel(model: tf.Model, data: TrainingData) {
const xTensor = tf.tensor2d(padData(data.test.inputs));
const result = model.predict(xTensor) as tf.Tensor;
xTensor.dispose();
const r = result.dataSync();
let output: number[][] = [];
const [xSize, ySize] = result.shape;
for (let i = 0; i < xSize; i++) {
output[i] = [];
for (let j = 0; j < ySize; j++) {
output[i][j] = r[i * ySize + j];
}
}
console.log(output);
}
<file_sep>/src/download.ts
import rp from 'request-promise-native';
import { outputJSON } from 'fs-extra';
import { IssueOrPullRequest } from './types';
import { resolve } from 'path';
const ISSUES_PER_PAGE = 100;
export async function downloadIssues(repo: string): Promise<void> {
let issues: IssueOrPullRequest[];
let page = 1;
do {
console.log(`Getting page ${page}`);
issues = await getIssues(repo, page);
console.log(`Page ${page} had ${issues.length} issues. Saving...`);
await saveIssues(issues).then(() => console.log(`Saved page ${page}`));
page += 1;
} while (issues.length >= ISSUES_PER_PAGE);
}
function getIssues(
repo: string,
page: number = 1
): Promise<IssueOrPullRequest[]> {
const options = {
uri: `https://api.github.com/repos/${repo}/issues`,
qs: {
state: 'all',
per_page: ISSUES_PER_PAGE,
page
// access_token: '<PASSWORD> x<PASSWORD>' // -> uri + '?access_token=xxxxx%20xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true
};
return rp(options) as any;
}
async function saveIssues(issues: IssueOrPullRequest[]): Promise<void> {
const queue: Promise<void>[] = [];
issues.forEach(issue => {
const type = issue.pull_request ? 'pull-requests' : 'issues';
queue.push(
outputJSON(
resolve(__dirname, `../data/${type}/${issue.number}.json`),
issue,
{
spaces: 2
}
)
);
});
return Promise.all(queue).then(() => void 0);
}
<file_sep>/src/data.ts
import { readdir, readJSON, outputJSON } from 'fs-extra';
import { resolve } from 'path';
import { Issue } from './types';
import { getDictionary, textToWords, DICT_ENTRY_UNKNOWN } from './dictionary';
import { shuffleArrays } from './util';
const DATA_DIR = '../data';
export async function getTrainingData(labels: string[]): Promise<TrainingData> {
const files = await readdir(resolve(__dirname, DATA_DIR, 'issues'));
const dict = getDictionary();
let inputs: number[][] = [];
let outputs: (1 | 0)[][] = [];
for (const file of files) {
const issue: Issue = await readJSON(
resolve(__dirname, DATA_DIR, 'issues', file)
);
const wordIntegers = new Set<number>();
const text = issue.title + ' ' + issue.body;
const words = textToWords(text);
for (const word of words) {
wordIntegers.add(dict.get(word) || DICT_ENTRY_UNKNOWN);
}
const labelTags = labels.map(reqLabel => {
const hasLabel = issue.labels.some(
issueLabel => issueLabel.name === reqLabel
);
return hasLabel ? 1 : 0;
});
inputs.push([...wordIntegers]);
outputs.push(labelTags);
}
// Shuffle the arrays to eliminate any bias (older/newer issues)
// when splitting the data.
[inputs, outputs] = shuffleArrays([inputs, outputs]);
// Split the data between training and test, with 90% for training
// and 10% for testing.
const countForTraining = Math.ceil(0.9 * files.length);
return {
labels,
training: {
inputs: inputs.slice(0, countForTraining),
outputs: outputs.slice(0, countForTraining)
},
test: {
inputs: inputs.slice(countForTraining),
outputs: outputs.slice(countForTraining)
}
};
// return { inputs, inputsTensor, labels, labelsTensor };
}
export function saveTrainingData(data: TrainingData): Promise<any> {
return Promise.all([
outputJSON(resolve(__dirname, DATA_DIR, 'labels.json'), data.labels),
outputJSON(
resolve(__dirname, DATA_DIR, 'training-inputs.json'),
data.training.inputs
),
outputJSON(
resolve(__dirname, DATA_DIR, 'training-outputs.json'),
data.training.outputs
),
outputJSON(
resolve(__dirname, DATA_DIR, 'test-inputs.json'),
data.test.inputs
),
outputJSON(
resolve(__dirname, DATA_DIR, 'test-outputs.json'),
data.test.outputs
)
]);
}
export function loadTrainingData(): TrainingData {
return {
labels: require(resolve(__dirname, DATA_DIR, 'labels.json')),
training: {
inputs: require(resolve(__dirname, DATA_DIR, 'training-inputs.json')),
outputs: require(resolve(__dirname, DATA_DIR, 'training-outputs.json'))
},
test: {
inputs: require(resolve(__dirname, DATA_DIR, 'test-inputs.json')),
outputs: require(resolve(__dirname, DATA_DIR, 'test-outputs.json'))
}
};
}
export interface TrainingData {
labels: string[];
training: {
inputs: number[][];
outputs: (1 | 0)[][];
};
test: {
inputs: number[][];
outputs: (1 | 0)[][];
};
}
| 6120abe0508930e696d3db26a79f3a07eed308e1 | [
"Markdown",
"TypeScript"
] | 8 | TypeScript | jsayol/github-issue-labeler | 670ac2a290f34778206009dfbaba19bc832997f8 | 270768677a770c36005d45240dda922901357e52 |
refs/heads/master | <repo_name>limkokhole/ps_brief<file_sep>/ps_brief.sh
#!/bin/bash
#Please run it as `sudo bash ps_brief`, sudo required to read a lot processes
#You may edit $f, $ext, and $skip_f to your desired output filename, extension(to get pretty syntax highlight), and log.
#1st part: For every package name related to the valid process files, the next line will shows its man, if any.
#2nd part: --- process filename and the next line will shows its man, if any
#3rd part: The last part will be package's description, home page, and maintainer contact.
f=~/Downloads/myps_;
ext='.c'
now="$(date '+%Y_%m_%d_%H:%M:%S')"
#keep in mind since sudo and non-sudo may run this, so once you output to root file, you can't output to the same root file as non-root, so I use datetime to make the file unique.
f="$f"_"$now""$ext"
skip_f='/tmp/myps_skip_processes_'"$now"'.log'
if [ -f "$f" ]; then rm "$f"; fi
if [ -f "$skip_f" ]; then rm "$skip_f"; fi
echo 'Start calculating total, please to be patient...';
#total=0; while IFS='' read -r fn; do fn="$(dpkg -S "$fn" 2>> "$skip_f")"; if [ -z "$fn" ]; then continue; fi; ((total++)); done < <(readlink -f /proc/*/exe 2>>"$skip_f" | sort | uniq)
arr=();
arri=();
#readlink nid -v to report permission denied OR No such file or directory
#can't use this since "pgrep -f command" is merely search and no guarantee produced 100% match #total=0; ti=0; while IFS='' read -r fn; do fn="$(dpkg -S "$fn" 2>> "$skip_f")"; ((ti++)); echo "[$ti] Checking... $fn"; if [ -z "$fn" ]; then continue; fi; arr+=("$fn"); ((total++)); done < <(readlink -v -f /proc/*/exe 2>>"$skip_f" | sort | uniq)
total=0; ti=0; while IFS='' read -r pid; do
((ti++));
echo "[$ti] Checking pid $pid ...";
fn="$(readlink -v -f "/proc/$pid/exe" 2>>"$skip_f")";
if [ -z "$fn" ]; then continue; fi;
fn="$(dpkg -S "$fn" 2>> "$skip_f")";
if [ -z "$fn" ]; then continue; fi;
arr+=("$fn"':'"$pid");
((total++));
done < <(find /proc/ -maxdepth 1 -type d -iregex '/proc/[0-9]+$' -exec basename {} \; | sort -zn );
#arr=( $(printf '%s\n' "${arr[@]}"|sort -n) )
IFS=$'\n' arr=($(sort -n <<<"${arr[*]}"))
unset IFS
fn='';
pkgn='';
n=0;
gn=0;
contains_space=" ";
#dpkg -S produces such special cases output line(s)
#... , only case #2 supported, the rest will ignore and shows 'multi-packages not supported...':
#Special case 1(,): libgl1-mesa-dri:i386, libgl1-mesa-dri:amd64: /etc/drirc
#Special case 2(:): libmagic1:amd64: /etc/magic
#Special case 3: diversion by parallel from: /usr/bin/parallel
#Special case 4: diversion by parallel to: /usr/bin/parallel.moreutils
#Special case 5: parallel, moreutils: /usr/bin/parallel
#while IFS='' read -r f; do echo ----- "$f" -----; dpkg-query -W -f='${Description}\n\n${Homepage}\nMaintainer: ${Maintainer}\n\n' "$(basename "$(dirname "$f")")"; done < <(readlink -f /proc/*/exe)
#find "$d" -maxdepth 1 -name '*parallel*' -type f -exec dpkg -S {} + 2> /dev/null | sort | #if want test custom name #2
#find "$d" -maxdepth 1 -type f -exec dpkg -S {} + 2> /dev/null | sort |
#readlink -f /proc/*/exe 2>/dev/null | sort | uniq |
#while IFS='' read -r fn; do
for i in ${!arr[@]}; do
arrItem="${arr[i]}";
fn="$( echo -n "$arrItem" | awk -F: 'sub(FS $NF,x)' )"
pid="$(echo -n "$arrItem" | awk -F: '{print $NF}' )"
orig_f="$fn";
if [ -z "$fn" ]; then continue; fi;
((pgn=gn+1));
echo "[$pgn/$total] Parsing... $fn";
((gn++));
pkgbp="$(echo -n $fn | cut -f2- -d' ' | awk '{$1=$1}1')"; #awk to strip leading path spaces
if [[ "$(echo $fn | cut -d':' -f1)" =~ $contains_space ]]; then
echo 'multi-packages not supported.';
elif [[ "$pkgbp" =~ $contains_space ]]; then
echo 'multi-packages or path contains space not supported.';
else
pkgp="$pkgn";
pkgn="$(echo $fn | cut -f1 -d' ')";
pkgn="$(echo ${pkgn%:})"; #trim trailing :
pkgn="$(echo ${pkgn%,})"; #trim trailing ,
pkgb="$(basename $pkgbp)"
if [ "$pkgp" == "$pkgn" ]; then
echo -en "\n--- $pkgbp" >> "$f";
ft="$(file -n -b -e elf $pkgbp)";
if [ "${ft#a }" != "${ft}" ]; then #some files return something like 'a /usr/bin/python script', nid split by ',' for this case.
ft="$(echo "$ft" | cut -d',' -f1)"
else #to reduce noise, all split by space and shows 1st word only.
ft="$(echo "$ft" | cut -d' ' -f1)"
fi;
echo -e "\t\t($ft)" >> "$f";
man -f "$pkgb" 2>/dev/null >> "$f";
#must combine both -f + fullpath AND -f + basename, otherwise some processes not able to pgrep
#{ pgrep -f "$pkgbp"; pgrep "$pkgb"; } | sort -n | uniq | while IFS='' read -r pi; do echo -n "$pi " >> "$f"; cat "/proc/$pi/cmdline" | tr '\0' ' ' >> "$f"; echo >> "$f"; done
echo -n "$pid " >> "$f"; cat "/proc/$pid/cmdline" | tr '\0' ' ' >> "$f"; echo >> "$f"
if [ "$total" == "$gn" ]; then
echo -en '\n\n\t\t\t\t' >> "$f";
dpkg-query -W -f='${Description}\n\n${Homepage}\nMaintainer: ${Maintainer}\n\n' "$pkgp" >>"$f";
echo >> "$f";
fi;
continue;
fi;
if [ "$n" != 0 ]; then
echo -en '\n\n\t\t\t\t' >> "$f";
dpkg-query -W -f='${Description}\n\n${Homepage}\nMaintainer: ${Maintainer}\n\n' "$pkgp" >>"$f";
echo >> "$f";
fi;
((n++));
echo -n "[$n] " >> "$f";
echo "$pkgn" >> "$f";
man -f "$pkgn" 2>/dev/null >> "$f";
echo -en "\n--- $pkgbp" >> "$f";
ft="$(file -n -b -e elf $pkgbp)";
if [ "${ft#a }" != "${ft}" ]; then
ft="$(echo "$ft" | cut -d',' -f1)"
else
ft="$(echo "$ft" | cut -d' ' -f1)"
fi;
echo -e "\t\t($ft)" >> "$f";
man -f "$pkgb" 2>/dev/null >> "$f";
echo -n "$pid " >> "$f"; cat "/proc/$pid/cmdline" | tr '\0' ' ' >> "$f"; echo >> "$f"
if [ "$total" == "$gn" ]; then
echo -en '\n\n\t\t\t\t' >> "$f";
dpkg-query -W -f='${Description}\n\n${Homepage}\nMaintainer: ${Maintainer}\n\n' "$pkgn" >>"$f";
echo >> "$f";
fi;
fi;
done;
echo "Skipped Log:"
cat "$skip_f" 2>/dev/null
if [ ! -f "$f" ]; then
echo "Sorry, no file has brief";
else echo "Done ... Please check your file $f";
fi
<file_sep>/README.md
# ps_brief
Understand all running non-kernel processes with manual and package brief.
This script dump all running processes with dpkg description, process name, process id, filetype, manual brief, then saved into a single file.
Processes in the same package will group together.
You should run it as root in bash, i.e. sudo. Support only for dpkg-based systems.
Note that "No such file or directory" for a lot of processes is normal because those are kernel threads.
Also my script don't have to worry about bash dependency which causes exe produces shell path instead of executing fd path, since I noticed there are no single system process except custom process running depends on parent bash. And I also noticed all of this is ELF only.
## Format: ##
[1] package name
package manual(if exist)
--- process executable (file type)
process manual 1(section) - manual brief
process manual 2/3/...(section) - manual brief (if exist)
prcoess id AND process full command
--- process executable 2 (file type) (if exist)
...cont.
package description
package link (if exist)
package contact
[2] package name 2
...cont.
## Demonstration video (Click image to play at YouTube): ##
[](https://www.youtube.com/watch?v=SBKv3_F8VwU "ps brief")
| 432d513953c2ba6eb8651f003ebb04f6322031f8 | [
"Markdown",
"Shell"
] | 2 | Shell | limkokhole/ps_brief | bbe28099beceda2ae423e540404395dd74a4c7f9 | 2646f0c85e6f3e808b5cfbd1edd301a0c0057013 |
refs/heads/master | <file_sep>
# AI Aerobics: Moving with Machines
AI Aerobics is a digital experience where you follow a machine’s instructions on how to move. Sounds simple enough, right? In fact, the poses the computer demands of you reflect what it’s learned about unique movement through reinforcement learning techniques. And not only that: they’ve also been tweaked in response to what CIRG found out about movement through talking to choreographers, yoga teachers and more. In the experiment itself, however, you don’t get that whole backstory. Instead, you get an entertaining experience where you work out like a machine says you should—and then export your routine as a GIF if you wish to.
To learn more about how and why we made this experiment, head over to our [projects page](https://space10.io/project/ai-aerobics/).
## Train your own models
Curious about the technology the drives the experiment? Want to train your own models? Head over to [CIRG's repository](https://github.com/cirg-io/AIAerobics-CodeExamples) to try out some more examples and get accustomed with how we made this experiment.
## Get in touch
Feel free to write to <EMAIL> with any questions, ideas or comments you might have.
<file_sep>
// turn on/off debug prints to the console
var consoleDebug = false;
//Operating System
// options are --> windows, android, iOS, opera, chrome, safari, firefox, edge, IE
// boild down to --> mobile, chrome, safarie, otherBrowser
var OS;
$(document).ready(function () {
if(consoleDebug)console.log("--> document ready");
OS = getBrowserOS();
if(consoleDebug)console.log("OS/Browser: " + OS);
setTimeout(function () {
if( OS =="chrome" || OS =="safari"){
// yes we are right
if(consoleDebug)console.log("--> show welcome screen");
$("#welcome").fadeIn(0);
} else if( OS =="mobile") {
// we don't run on mobile devices, sorry
if(consoleDebug)console.log("--> show mobile screen");
$("#mobile").fadeIn(0);
}
else { // other browsers
// we don't run on other browsers, sorry
if(consoleDebug)console.log("--> show otherBrowser screen");
$("#otherBrowser").fadeIn(0);
}
}, 500);
});
// called by the start button
function startPrototype(){
$("#welcome").fadeOut(1500);
setTimeout(function () {
$("#main").fadeIn(1500);
startP5();
}, 1000);
}
function getBrowserOS() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
var _os;
if (/windows phone/i.test(userAgent)) { // most come bevor other phones
_os = "mobile";
}
else if (/android/i.test(userAgent)) {
_os = "mobile";
}
else if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
_os = "mobile";
}
else if(userAgent. indexOf("Edge") != -1 ) { // most come bevor other browser
_os = 'otherBrowser';
}
else if((userAgent.indexOf("Opera") || userAgent.indexOf('OPR')) != -1 ) {
_os = 'otherBrowser';
}
else if(userAgent.indexOf("Chrome") != -1 ) {
_os = 'chrome';
}
else if(userAgent.indexOf("Safari") != -1) {
_os = 'safari';
}
else if(userAgent.indexOf("Firefox") != -1 ) {
_os = 'otherBrowser';
}
else if((userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) /*IF IE > 10 */ {
_os = 'otherBrowser';
}
else {
_os = 'otherBrowser';
if(consoleDebug)console.log("alert --> couldn't not figure which browser you are using. sorry");
}
return _os;
}
| 0cfe806ef66bf9ace836228e60e81f34cea3693c | [
"Markdown",
"JavaScript"
] | 2 | Markdown | space10-community/ai-aerobics | 45a233281b5375f891f267f78613299f4d24de5f | 7db6cd560e2cadec09856ea5ed2de90925e8315e |
refs/heads/master | <file_sep>package mcc;
import java.util.Scanner;
public class OrthogonalCodes {
Code c1,c2;
Code[] c3;
static OrthogonalCodes oc=new OrthogonalCodes();
public static void main(String args[])
{oc.start();}
void start()
{
Scanner sc=new Scanner(System.in);
// System.out.println("Enter Code 1 length and code 1");
// c1=new Code(sc.nextInt(),sc);
// System.out.println(c1);
// System.out.println("Enter Code 2 length and code 2");
// c2=new Code(sc.nextInt(),sc);
// System.out.println(c2);
// System.out.println(c1.dotProduct(c2));
System.out.println("Enter Length of Code");
int len=sc.nextInt();
c3=Code.createCode(len);
for(Code x:c3)
System.out.println(x);
sc.close();
}
}
class Code{
static int zero=-1;
static int one=1;
int[] n;
Code(){}
Code(Code c1,Code c2)
{
int len=c1.n.length;
n=new int[2*len];
for(int i=0;i<len;i++)
{
this.n[i]=c1.n[i];
this.n[i+len]=c2.n[i];
}
}
Code(int len)
{
n=new int[1];
if(len==0)
n[0]=-1;
else if(len==1)
n[0]=1;
else n=new int[len];
}
Code(int size,Scanner sc)
{
n=new int[size];
try {
for(int i=0;i<size;i++)
{
n[i]=sc.nextInt();
if(n[i]==0)
this.n[i]=zero;
else if(n[i]==1)
this.n[i]=one;
else
throw new OrthogonalCodeException(i);
}
}
catch (OrthogonalCodeException e)
{System.out.println(e);}
}
static Code[] createCode(int n)
{
if(n==1)
{
Code c1=new Code(1);
return new Code[]{c1};
}
Code[] codes=createCode(n>>1);
Code[] newcodes=new Code[n];
for(int i=0;i<newcodes.length;i+=2)
{
newcodes[i]=new Code(codes[i/2],codes[i/2]);
newcodes[i+1]=new Code(codes[i/2],codes[i/2].negate());
}
return newcodes;
}
private Code negate() {
Code temp=new Code(this.n.length);
for(int i=0;i<temp.n.length;i++)
temp.n[i]=-this.n[i];
return temp;
}
String dotProduct(Code c2){
if(n.length!=c2.n.length)
try {throw new OrthogonalCodeException(OrthogonalCodeException.mismatch);}
catch (OrthogonalCodeException e) {System.out.println(e);}
int product=0;
for(int i=0;i<n.length;i++)
product=product+n[i]*c2.n[i];
if(product==0)
return "Codes are Orthogonal";
else return "Codes are Not Orthogonal";
}
int dotProduct1(Code c2){
if(n.length!=c2.n.length)
try {throw new OrthogonalCodeException(OrthogonalCodeException.mismatch);}
catch (OrthogonalCodeException e) {System.out.println(e);}
int product=0;
for(int i=0;i<n.length;i++)
product=product+n[i]*c2.n[i];
return product;
}
Code dotProduct(int n){
Code temp=new Code(this.n.length);
for(int i=0;i<this.n.length;i++)
temp.n[i]=this.n[i]*n;
return temp;
}
@Override
public String toString() {
String s="";
for(int i=0;i<n.length;i++)
s=s+" "+n[i];
s="Code is"+s;
return s;
}
}
class OrthogonalCodeException extends Exception
{
int error;
static int mismatch=-100;
public OrthogonalCodeException(int n)
{error=n;}
private static final long serialVersionUID = 1L;
@Override
public String toString() {
if(error!=mismatch)
return "OrthogonalCodeException [error at position=" + error + "]";
else return "OrthogonalCodeException [unequal code lengths]";
}
} | 5cf1ac75793125902f8d22485103826b2387ad42 | [
"Java"
] | 1 | Java | vivekitis/mcc | 2b532978b4d13e046af0e48d8e073183c350287a | b5b0d03a971c48c7b60084d9f38d74f0a5f871ec |
refs/heads/master | <repo_name>FariaQuitamb/vuejs<file_sep>/js/app.js
var app = new Vue({
el: '#app',
data: {
product:'Ténis Adidas',
image:'./img/black-shoes.jpg',
inStock:true,
details:['80% Algodão', 'Piso ortopédico', 'Apto para caminhadas'],
variants:[
{
variantId:01,
variantColor: 'black',
variantImage: './img/black-shoes.jpg'
},
{
variantId:02,
variantColor: 'blue',
variantImage: './img/blue-shoes.jpg'
}
],
cart: 0,
alert:'',
showAlert: false
},
methods:{
addToCart(){
this.cart += 1
},
removeFromCart(){
this.cart -= 1
},
updateProduct(variantImage){
this.image = variantImage
}
}
})
| f1a51fe390d5e3dd9c2de46d3c95e647613ae263 | [
"JavaScript"
] | 1 | JavaScript | FariaQuitamb/vuejs | faa1e3216b221ae9d7854af6995dca11c9f35180 | 2adb2d0137551e41e58e72ed68f00ef594a8010f |
refs/heads/master | <file_sep>import TaskManagerLib
// Partie 3
print("Ex3: Analyse du probleme" )
let taskManager = createTaskManager()
// Creation des transitions et des places du taskManager
let create = taskManager.transitions.filter{$0.name == "create"}[0]
let spawn = taskManager.transitions.filter{$0.name == "spawn"}[0]
let exec = taskManager.transitions.filter{$0.name == "exec"}[0]
let success = taskManager.transitions.filter{$0.name == "success"}[0]
let fail = taskManager.transitions.filter{$0.name == "fail"}[0]
let taskPool = taskManager.places.filter{$0.name == "taskPool"}[0]
let processPool = taskManager.places.filter{$0.name == "processPool"}[0]
let inProgress = taskManager.places.filter{$0.name == "inProgress"}[0]
// Execution de la gestionnaire des taches
let m1 = create.fire(from: [taskPool: 0, processPool: 0, inProgress: 0])
print("m1 (create) ",m1!)
let m2 = spawn.fire(from: m1!)
print("m2 (spawn) ",m2!)
let m3 = spawn.fire(from: m2!)
print("m3 (spawn)",m3!)
// m1 - m3 : creation d 1 jeton dans taskPool, et 2 jetons dans processPool
let m4 = exec.fire(from: m3!)
print("m4 (exec) ",m4!)
let m5 = exec.fire(from: m4!)
print("m5 (exec)",m5!)
// m4 - m5 : execution deux fois est possible, vu le nombre de jetons
let m6 = success.fire(from: m5!)
print("m6 (success) ",m6!) // Transition: success
// Un jeton est encore dans la place "inProgress" ce qui nous pose un probleme
// Parce que la tache possible c'est "fail", qui a été deja supprimee du taskPool
//Partie 4
print("Ex 4: Correction du probleme")
let correctTaskManager = createCorrectTaskManager()
// Creation des transitions et des places du taskManager
let create2 = correctTaskManager.transitions.filter{$0.name == "create"}[0]
let spawn2 = correctTaskManager.transitions.filter{$0.name == "spawn"}[0]
let exec2 = correctTaskManager.transitions.filter{$0.name == "exec"}[0]
let success2 = correctTaskManager.transitions.filter{$0.name == "success"}[0]
let fail2 = correctTaskManager.transitions.filter{$0.name == "fail"}[0]
let taskPool2 = correctTaskManager.places.filter{$0.name == "taskPool"}[0]
let processPool2 = correctTaskManager.places.filter{$0.name == "processPool"}[0]
let inProgress2 = correctTaskManager.places.filter{$0.name == "inProgress"}[0]
let PlaceSec = correctTaskManager.places.filter{$0.name == "PlaceSec"}[0]
//On ajoute une nouvelle place
// Execution de la gestionnaire des taches
let m21 = create2.fire(from: [taskPool2: 0, processPool2: 0, inProgress2: 0, PlaceSec: 0])
print("m1 (create) ",m21!)
let m22 = spawn2.fire(from: m21!)
print("m2 (spawn) ",m22!)
let m23 = spawn2.fire(from: m22!)
print("m3 (spawn)",m23!) // m1 - m3 : crée 1 jeton dans taskPool et 2 dans processPool comme auparavant
let m24 = exec2.fire(from: m23!)
print("m4 (exec) ",m24!) // m4 : Dans ce nouveau cas, une seule exécution est possible
let m25 = success2.fire(from: m24!)
print("m5 (success) ",m25!) // Transition: success
let m27 = fail2.fire(from: m24!)
print("m5 (fail) ",m27!) // "fail"
// La correction cest par le blocage de l'exécution 1 task/1 process
// et par la creation d'une nouvelle place "PlaceSec"
// Donc au final on envoie qu'un seul jeton a "exec"
<file_sep>import PetriKit
public extension PTNet {
// Turns a mark for the cover graph into a pullable mark
public func convToPT(with marking : CoverabilityMarking, and p : [PTPlace]) -> PTMarking{
var m : PTMarking = [:]
for temp in p
{
let this = correctValue(to : marking[temp]!)!
m[temp] = this
}
return m
}
// Turns a markable mark into a mark for the cover graph
public func ptToConv(with marking: PTMarking, and p : [PTPlace]) ->CoverabilityMarking{
var temp : CoverabilityMarking = [:]
for val in p
{
temp[val] = .some(marking[val]!)
if(500 < temp[val]!)
{
temp[val] = .omega
}
}
return temp
}
//Correct errors that allow the draw (the presence of the omega)
public func correctValue(to t: Token) -> UInt? {
if case .some(let value) = t {
return value
}
else {
return 1000
}
}
//Check if a node is contained in the list
public func verify(at marking : [CoverabilityMarking], to markingToAdd : CoverabilityMarking) -> Int
{
var value = 0
for i in 0...marking.count-1
{
if (marking[i] == markingToAdd)
{
value = 1
}
if (markingToAdd > marking[i])
{
value = i+2}
}
return value
}
// Add omega as a token if necessary
public func convertOmega(from comp : CoverabilityMarking, with marking : CoverabilityMarking, and p : [PTPlace]) -> CoverabilityMarking?
{
var temp = marking
for t in p
{
if (comp[t]! < temp[t]!)
{
temp[t] = .omega
}
}
return temp
}
public func coverabilityGraph(from marking0: CoverabilityMarking) -> CoverabilityGraph? {
// Write here the implementation of the coverability graph generation.
// Note that CoverabilityMarking implements both `==` and `>` operators, meaning that you
// may write `M > N` (with M and N instances of CoverabilityMarking) to check whether `M`
// is a greater marking than `N`.
// IMPORTANT: Your function MUST return a valid instance of CoverabilityGraph! The optional
// print debug information you'll write in that function will NOT be taken into account to
// evaluate your homework.
//// transform into sets array transitions and places
var transitionsC = Array (transitions)
transitionsC.sort{$0.name < $1.name}
let placesC = Array(places)
var markingList : [CoverabilityMarking] = [marking0]
var graphList : [CoverabilityGraph] = []
var this: CoverabilityMarking
let returnedGraph = CoverabilityGraph(marking: marking0, successors: [:])
var count = 0
// Main loop that stops when count is greater than the size of the list of markings
while(count < markingList.count)
{
for tran in transitionsC{
let ptMarking = convToPT(with: markingList[count], and: placesC)
if let firedTran = tran.fire(from: ptMarking){
// Converted to marking for the cover graph
let convMarking = ptToConv(with: firedTran, and: placesC)
// create the marking node
let nouvCouv = CoverabilityGraph(marking: convMarking, successors: [:])
// Add the new node to the successor
returnedGraph.successors[tran] = nouvCouv
}
if(returnedGraph.successors[tran] != nil){
// add his markup to the variable this
this = returnedGraph.successors[tran]!.marking
// We check if it is contained in the list
let cur = verify(at: markingList, to: this)
if (cur != 1)
{
if (cur > 1)
{
this = convertOmega(from : markingList[cur-2], with : this, and : placesC)!
}
// Add node to the list
graphList.append(returnedGraph)
markingList.append(this)
}
}
}
count = count + 1
}
return returnedGraph
}
}<file_sep>import PetriKit
public class MarkingGraph {
public let marking : PTMarking
public var successors: [PTTransition: MarkingGraph]
public init(marking: PTMarking, successors: [PTTransition: MarkingGraph] = [:]) {
self.marking = marking
self.successors = successors
}
// Counts the number of states in a tagging graph from a node
public func countMark(input:MarkingGraph) -> Int{
var visitedNode: [MarkingGraph] = []
var nodeToVisit: [MarkingGraph] = [input]
while let current = nodeToVisit.popLast(){
visitedNode.append(current)
for (_, successor) in current.successors{
if !visitedNode.contains(where: {$0 === successor}) && !nodeToVisit.contains(where: {$0 === successor}){
nodeToVisit.append(successor)
}
}
}
return visitedNode.count
}
// Lets you know if there are two smokers in the graph
public func isTwoSmokers(input:MarkingGraph) -> Bool{
var visitedNode: [MarkingGraph] = []
var nodeToVisit: [MarkingGraph] = [input]
while let current = nodeToVisit.popLast(){
visitedNode.append(current)
for (place, token) in current.marking{
var nbSmoke = 0;
for (place, token) in current.marking {
if (place.name == "s1" || place.name == "s2" || place.name == "s3"){
nbSmoke += Int(token)
}
}
if (nbSmoke > 1) {
return true
}
}
for (_, successor) in current.successors{
if !visitedNode.contains(where: {$0 === successor}) && !nodeToVisit.contains(where: {$0 === successor}){
nodeToVisit.append(successor)
}
}
}
return false
}
// Lets find out if two ingredients are on the table
public func isTwoIng(input:MarkingGraph) -> Bool{
var visitedNode: [MarkingGraph] = []
var nodeToVisit: [MarkingGraph] = [input]
while let current = nodeToVisit.popLast(){
visitedNode.append(current)
for (place, token) in current.marking{
if place.name == "p" || place.name == "m" || place.name == "t"{
if(token > 1){
return true
}
}
}
for (_, successor) in current.successors{
if !visitedNode.contains(where: {$0 === successor}) && !nodeToVisit.contains(where: {$0 === successor}){
nodeToVisit.append(successor)
}
}
}
return false
}
}
public extension PTNet {
public func markingGraph(from marking: PTMarking) -> MarkingGraph? {
// Write here the implementation of the marking graph generation.
// Initialize values
let m0 = MarkingGraph(marking: marking)
var nodeToVisit : [MarkingGraph] = [m0]
var visitedNode : [MarkingGraph] = []
// Close the list to visit
while(!nodeToVisit.isEmpty) {
let cur = nodeToVisit.remove(at:0)
visitedNode.append(cur)
// Loop transitions
for tran in transitions {
if let firedMark = tran.fire(from: cur.marking) {
if let alreadyVisitedNode = visitedNode.first(where: { $0.marking == firedMark }) {
cur.successors[tran] = alreadyVisitedNode
} else {
let temp = MarkingGraph(marking: firedMark)
cur.successors[tran] = temp
if (!nodeToVisit.contains(where: { $0.marking == temp.marking})) {
nodeToVisit.append(temp)
}
}
}
}
}
return m0
} }
| 57f98c08db0fb1dc2a8503f888c6a5fbbd90da57 | [
"Swift"
] | 3 | Swift | trabelsi29/outils-formels-modelisation | 00d7bf2ba0a4f2683292dd197b2e0fb705904f60 | 19bc1a87384725ee1af288e0c17e96e408bf445a |
refs/heads/master | <repo_name>theisolatedisland/getting-started-with-gcp<file_sep>/09_cloud_functions/deploy_function.sh
#!/bin/bash
#you can follow instructions from the following page as well:
#https://cloud.google.com/functions/docs/first-python
#Download the function from here:
#https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/functions/helloworld/main.py
#or clone the entire repo:
#git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
#Modify the function if you want to make it unique, otherwise:
#From the same directory as main.py
#Create a new file requirements.txt with the following:
#Flask==1.0.2
#Then issue the following command:
gcloud functions deploy hello_http --runtime python37 --trigger-http --allow-unauthenticated
#The output of the above command will include the URL of the function, something like this:
#https://us-central1-brightkey-project.cloudfunctions.net/hello_http
#You can also issue a command to describe the function to locate the URL as follows:
gcloud functions describe hello_http
<file_sep>/README.md
# getting-started-with-gcp
Getting Started with Google Cloud Platform links and scripts
<file_sep>/07_loadbalancing_and_dns/create_private_dns_zone.sh
#!/bin/bash
NETWORK=demo-sdk-vpc
gcloud dns managed-zones create testzone --description="this is a test zone" \
--dns-name=brightkeycloud --networks=$NETWORK --visibility=private
<file_sep>/02_iam/project_add_member.sh
#!/bin/bash
PROJECT=brightkey-project
USER='user:<EMAIL>'
ROLE='roles/compute.admin'
gcloud projects add-iam-policy-binding $PROJECT \
--member=$USER --role=$ROLE
<file_sep>/05_stackdriver_and_billing/startup_script.sh
#!/bin/bash
curl -sSO https://dl.google.com/cloudagents/install-monitoring-agent.sh
sudo bash install-monitoring-agent.sh
curl -sSO https://dl.google.com/cloudagents/install-logging-agent.sh
sudo bash install-logging-agent.sh
<file_sep>/06_vpc/deploy_vpc.sh
#!/bin/bash
#this script takes slightly over 1 minute to run from a laptop using Cloud SDK
NETWORK=demo-sdk-vpc
#Create the network
gcloud compute networks create $NETWORK --bgp-routing-mode=global --subnet-mode=custom
#Create the subnets
gcloud compute networks subnets create us-east1 --network=$NETWORK --range=10.0.1.0/24 --region us-east1
gcloud compute networks subnets create us-west1 --network=$NETWORK --range=10.0.2.0/24 --region us-west1
#Create firewall rules
#This rule allows instances to communicate with each other on all protocols/ports
gcloud compute firewall-rules create internal-all-traffic --network $NETWORK --allow tcp,udp,icmp --source-ranges 10.0.1.0/24,10.0.2.0/24
#This rule allows inbound ssh on instances with an ssh tag for use with Cloud Console
gcloud compute firewall-rules create inbound-ssh --network $NETWORK --allow tcp:22 --source-ranges 0.0.0.0/0 --target-tags=ssh
#This rule allows inbound http traffic to instances with a tag of http-server
gcloud compute firewall-rules create inbound-http --network $NETWORK --allow tcp:80 --source-ranges 0.0.0.0/0 --target-tags=http-server
| a146f53ac9aebe38b5422b5772d8a180c9003a24 | [
"Markdown",
"Shell"
] | 6 | Shell | theisolatedisland/getting-started-with-gcp | 0e196b4f21394ad4d0c564fd121aab767977ad68 | 1d70135e569e86764a35cd52244607118f63c064 |
refs/heads/master | <file_sep>$(function(){
$('#movie-button').on('click',function(){
var moviename = $('#moviename').val();
console.log(moviename)
var data = {name:moviename};
console.log(data)
$.ajax({
url: '/similarity',
data: data,
cache: false,
type: 'POST',
success: function(response){
var resp=response.split(",")
$('#results').html('')
$('#results').append('<div class="card-header">Recommendations</div><ul class="list-group list-group-flush" id="result_data">')
$.each(resp,function ( index, repo ) {
console.log(index,repo)
$('#result_data').append('<li class="list-group-item">'+repo+'</li>');
});
$('#results').append('</div')
},
error: function(error){
console.log(error);
}
});
})
});<file_sep>import pandas as pd
import numpy as np
import requests
class Data_Generation:
def __init__(self):
self.tmdbUrl = "https://api.themoviedb.org/3/movie/"
self.apiKey = "?api_key=<KEY>"
def get_movie_details(self,movie_id):
"""
Accepts only tmdb movie id which should be an integer
performs TMDB API call and fetches the data related to the tmdb movie id
:param movie_id:
:return: response in json fromat
"""
url = self.tmdbUrl+str(movie_id)+self.apiKey
response = requests.get(url).json()
return response
def get_movie_reviews(self,movie_id):
"""
Accepts only tmdb movie id which should be an integer
performs TMDB API call and fetches the review data for the movie id
:param movie_id:
:return: response in json format
"""
url=self.tmdbUrl+str(movie_id)+"/reviews"+self.apiKey
response=requests.get(url).json()
total_review = []
for x in range(response['total_results']):
total_review.append(response['results'][x]['content'])
return ",".join(total_review)
def get_movie_ratings(self,movie_id):
"""
Accepts only tmdb movie id which should be an integer
performs TMDB API call and fetches the ratings for a given movie id
:return:
"""
url = self.tmdbUrl+str(movie_id)+"/account_states"+self.apiKey
response = requests.get(url).json()
return response
def get_cast_crew_details(self,movie_id):
"""
Accetps only tmdb movie id which should be an integer
Performs TMDB API Call and fetches the crew and cast details for a given movie id
:param movie_id:
:return:
"""
url = self.tmdbUrl+str(movie_id)+"/credits"+self.apiKey
response = requests.get(url).json()
cast=[]
for x in range(len(response['cast'])):
cast.append(str(response['cast'][x]['name']).replace(" ","_"))
crew = []
for x in range(len(response['crew'])):
if response['crew'][x]['job'] == "Director":
crew.append(str(response['crew'][x]['name']).replace(" ","_"))
return ",".join(crew+cast)
def get_movie_keywords(self,movie_id):
url=self.tmdbUrl+str(movie_id)+"/keywords"+self.apiKey
response = requests.get(url).json()
keywords = []
for x in range(len(response['keywords'])):
keywords.append(str(response['keywords'][x]['name']).replace(" ","_"))
return ",".join(keywords)
def prepare_data(self):
"""
Accepts only integer value to control the number of api calls and number of records
:param limit:
:return:
"""
movies = pd.read_csv("data/ml-latest/movies.csv")
links = pd.read_csv("data/ml-latest/links.csv")
data = pd.merge(movies,links,on="movieId",how="inner")
data['info'] = data['tmdbId'].apply(lambda x: self.get_movie_details(x))
data['overview'] = data['info'].apply(lambda x: x['overview'])
data['popularity'] = data['info'].apply(lambda x: x['popularity'])
data['overview'] = data['info'].apply(lambda x: x['overview'])
data['original_title'] = data['info'].apply(lambda x: x['original_title'])
data['vote_average'] = data['info'].apply(lambda x: x['vote_average'])
data['vote_count'] = data['info'].apply(lambda x: x['vote_count'])
data['tagline'] = data['info'].apply(lambda x: x['tagline'])
data['budget'] = data['info'].apply(lambda x: x['budget'])
data['reviews'] = data['tmdbId'].apply(lambda x: self.get_movie_reviews(x))
data['Crew_Cast'] = data['tmdbId'].apply(lambda x: self.get_cast_crew_details(x))
data['keywords'] = data['tmdbId'].apply(lambda x: self.get_movie_keywords(x))
del data['imdbId']
del data['info']
try:
data.to_csv("data/movie_data.csv")
return "Data Generated Successfully"
except:
return "Failed to Generate Data"
<file_sep>from flask import Flask, redirect, url_for,render_template,request,jsonify,make_response
import Content_based_Recommendation
app = Flask(__name__)
@app.route("/")
@app.route("/home")
def home():
return render_template("index.html")
@app.route("/tv")
def TV():
return render_template("TVSeries.html")
@app.route("/content")
def Content():
return render_template("Contentbased.html")
@app.route("/similarity",methods=["POST"])
def similarity():
movie = request.form['name']
cbr = Content_based_Recommendation.Recommendation()
recommended_movies=cbr.get_recommendation(movie)
return ",".join(recommended_movies)
if __name__ == "__main__":
app.run(debug=True)
<file_sep># TV_Movie_Recommendation_System
This project illustrates about different types of recommendation system implementation on python flask framework.
Types of Recommendation Systems implemented are Collaborative Filtering, Content-Based Filtering and Hybrid Recommendation.
The Movie Data set contains 58095 records of movies
The Content-Based Filtering technqiue uses Movie Overview, Tagline, keywords, Genre, Cast and Crew details for recommending movies.
The Collaborative Filtering technqiue and Hybrid are still in progress.
demo ready<file_sep>import pandas as pd
import gensim
from gensim import models
from gensim.similarities import MatrixSimilarity
def break_to_tokens(text):
result = []
for token in gensim.utils.simple_preprocess(text):
if token not in gensim.parsing.preprocessing.STOPWORDS and len(token) > 3:
result.append(token)
return result
class Recommendation:
def __init__(self):
self.movie_data = "data/movie_data.csv"
self.processed_data = "data/Content_based_recommendation/processed_data.csv"
self.corpus_dictionary = "data/Content_based_recommendation/content_based_corpus_dictionoary.dict"
self.tfidf_model = "data/Content_based_recommendation/tfidf_model.model"
self.matrix_similarity = "data/Content_based_recommendation/similarity.mm"
def testingpath(self):
data=pd.read_csv(self.movie_data)
print(data.columns)
return "done"
def pre_process_data(self):
"""
Reads movie dataset which is created by Data Generation object. Performs data cleaning and returns a data frame
:return: dataframe
"""
data = pd.read_csv(self.movie_data)
data = data[['original_title', 'overview', 'tagline', 'Crew_Cast', 'keywords', 'genres']]
data = data.fillna(" ")
data['description'] = data['overview'] + data['tagline']
del data['overview']
del data['tagline']
data['description'] = data['description'].str.replace(
r"(\.|,|\?|!|@|#|\$|%|\^|&|\*|\(|\)|_|-|\+|=|;|:|~|`|\d+|\[|\]|{|}|\xA9|\\|\/)", " ")
data['genres'] = data['genres'].apply(lambda x: x.replace("|", " "))
data['doc'] = data['description'] + data['genres'] + data['keywords'] + data['Crew_Cast']
data = data.drop(data.columns[[1, 2, 3, 4]], axis=1)
try:
data.to_csv(self.processed_data)
return "Pre Processing Successful"
except:
return "Pre Processing Failed"
def train_model(self):
"""
Read the preprocessed data and generate corpus dictionary, tfidf model and matrix(Cosine) similarity
:return: status of training
"""
try:
data = pd.read_csv(self.processed_data)
del data['Unnamed: 0']
# creating tokens for the doc column
corpus = data['doc'].map(break_to_tokens)
# creating dictionary of words in the movie dataset
dictionary = gensim.corpora.Dictionary(corpus)
dictionary.save(self.corpus_dictionary)
# creating vector with bag of words for the corpus
vector = [dictionary.doc2bow(d) for d in corpus]
# creating tfidf values for the vector
tfidf = models.TfidfModel(vector)
tfidf.save(self.tfidf_model)
corpus_tfidf = tfidf[vector]
# Compute Similarities
similarity = MatrixSimilarity(corpus_tfidf,num_features=len(dictionary))
similarity.save(self.matrix_similarity)
return "Model Trained Successfully"
except:
return "Error While Training Model"
def get_recommendation(self,movie_title:str):
"""
Accepts Movie Name and fetches the list of recommended movie names using matrix(cosine) similarity
:param movie_title:
:return: array of movie names
"""
print("movie : ",movie_title)
dictionary = gensim.corpora.Dictionary.load(self.corpus_dictionary)
tfidf_model = gensim.models.TfidfModel.load(self.tfidf_model)
similarity = MatrixSimilarity.load(self.matrix_similarity)
data = pd.read_csv(self.processed_data)
del data['Unnamed: 0']
data["original_title"]=data["original_title"].str.lower()
movie = data.loc[data.original_title == movie_title]
print(movie)
if movie.shape[0]==0:
status = ["Failed to Recommend Movies with existing movie data."]
return status
else:
movie_doc_bow = dictionary.doc2bow(movie['doc'].map(break_to_tokens)[0])
movie_tfidf = tfidf_model[movie_doc_bow]
movie_recommendations = pd.DataFrame({'Cosine_sim_values':similarity[movie_tfidf],'title':data.original_title.values}).sort_values(by="Cosine_sim_values",ascending=False)
top_recommendations = movie_recommendations['title'].head(11)
return top_recommendations.to_numpy()
| fca847bcd13fcf6dc60f5c8a667ea6f6fc627521 | [
"JavaScript",
"Python",
"Markdown"
] | 5 | JavaScript | litturahul/TV_Movie_Recommendation_System | 0ea3b35829792a3c1d8ee3cac63a94de1f3b9373 | c01c100077ee5a0b49c2b9624cc2589954fb2827 |
refs/heads/master | <repo_name>OPEnSLab-OSU/PNNLFluxV1<file_sep>/firmware/archive/MS5803_MUX_SINGLE_TEST/MS5803_MUX_SINGLE_TEST.ino
/* MS5803_02_MUX.ino
This version *only works* with the MS5803-02BA sensor, not the other
pressure models (like the MS5803-30BA, MS5803-01BA etc). You can find
libraries for those other models at http://github.com/millerlp
*/
// The Wire library carries out I2C communication
#include <Wire.h>
// Place the MS5803_02 library folder in your Arduino 'libraries' directory
#include <MS5803_02.h>
#include "GravityTDS.h" // EC/TDS sensor
#define TCAADDR 0x70 //define MUX Hex address
#define TdsSensorPin A0 //define pin
GravityTDS gravityTds; //create class
#define A 9 //Analog mux A pin
#define B 11 //Analog mux B pin
#define C 13 //Analog mux C pin
// Declare 'sensor' as the object that will refer to your MS5803 in the sketch
// Enter the oversampling value as an argument. Valid choices are
// 256, 512, 1024, 2048, 4096. Library default = 512.
MS_5803 sensor = MS_5803(0x77, 4096);
float tempF, tempC;
float EcValue = 0.0, voltage = 0.0;
int analog = 0;
void tcaselect(uint8_t i) {
if (i > 7) return;
Wire.beginTransmission(TCAADDR);
Wire.write(1 << i);
Wire.endTransmission();
}
void setup() {
pinMode(5, OUTPUT);
digitalWrite(5, LOW); // Sets pin 5, the pin with the 3.3V rail, to output and enables the rail
pinMode(6, OUTPUT);
digitalWrite(6, HIGH); // Sets pin 6, the pin with the 5V rail, to output and enables the rail
// Start the serial ports.
Serial.begin(115200); // other values include 9600, 14400, 57600 etc.
Serial.println("MS5803 MUX and EC Test");
Serial.println("");
analogReadResolution(12);
gravityTds.setPin(TdsSensorPin);
gravityTds.setAref(3.3); //reference voltage on ADC, default 5.0V on Arduino UNO
gravityTds.setAdcRange(4096); //1024 for 10bit ADC;4096 for 12bit ADC
gravityTds.begin(); //initialization
delay(2000);
// Initialize the MS5803 sensor. This will report the
// conversion coefficients to the Serial terminal if present.
// If you don't want all the coefficients printed out,
// set sensor.initializeMS_5803(false).
if (sensor.initializeMS_5803()) {
Serial.println( "MS5803 CRC check OK." );
}
else {
Serial.println( "MS5803 CRC check FAILED!" );
}
delay(3000);
}
void loop() {
// Use readSensor() function to get pressure and temperature reading.
sensor.readSensor();
// Uncomment the print commands below to show the raw D1 and D2 values
//Serial.print("D1 = ");
//Serial.println(sensor.D1val());
//Serial.print("D2 = ");
//Serial.println(sensor.D2val());
// Show pressure
Serial.print("Pressure = ");
Serial.print(sensor.pressure());
Serial.println(" mbar");
Serial.print("Depth = ");
Serial.print((sensor.pressure()-1013)*100/9800*100);
Serial.println(" cm");
// Show temperature
Serial.print("Temperature = ");
tempC = sensor.temperature();
tempF = (tempC * 9/5) + 32;
Serial.print(tempF);
Serial.println("F");
gravityTds.setTemperature(tempC); // set the temperature and execute temperature compensation
gravityTds.update(); //sample and calculate
analog = analogRead(TdsSensorPin);
//Serial.print("Raw Analog = ");
//Serial.println(analog);
//Serial.print("Voltage = ");
voltage = analog/4096.0*3.3;
//Serial.println(voltage);
//Serial.print("Mapped Analog = ");
analog = map(analog, 690, 1400, 0, 4095);
//Serial.println(analog);
//Serial.print("Modified Voltage = ");
voltage = analog/4096.0*3.3;
//Serial.println(voltage);
//Serial.print("My EC = ");
//Serial.println((133.42*voltage*voltage*voltage - 255.86*voltage*voltage + 857.39*voltage)*1.0 - 80);
//Serial.print("K = ");
//Serial.println(gravityTds.getKvalue()); // get kValue of library
EcValue = gravityTds.getEcValue(); // then get the value
Serial.print("EC = ");
Serial.println(EcValue);
Serial.println("---------------------------------------");
delay(1000); // For readability
// for(int index = 0; index < 5; index += 1){
// tcaselect(index);
// sensor.initializeMS_5803(false);
// sensor.readSensor();
// // Show pressure
// Serial.println("---------------------------------------");
// Serial.print("#");
// Serial.print(index);
// Serial.print(" Pressure = ");
// Serial.print(sensor.pressure());
// Serial.print(" mbar ");
//
// // Show temperature
// Serial.print("#");
// Serial.print(index);
// Serial.print(" Temperature = ");
// tempC = sensor.temperature();
// tempF = (sensor.temperature() * 9/5) + 32;
// Serial.print(tempF);
// Serial.println("F");
//
// tcaselect(5);
// gravityTds.setTemperature(tempC); // set the temperature and execute temperature compensation
// gravityTds.update(); //sample and calculate
// switch(index){
// case 0:
// digitalWrite(A,LOW);
// digitalWrite(B,LOW);
// digitalWrite(C,LOW);
//
// EcValue = gravityTds.getEcValue(); // then get the value
// Serial.print("#");
// Serial.print(index);
// Serial.print(" EC = ");
// Serial.print(EcValue, 0);
// Serial.print("ppm | ");
// Serial.print("Analog MUX ");
// Serial.println(index);
// delay(2000); // For readability
// break;
// case 1:
// digitalWrite(A,HIGH);
// digitalWrite(B,LOW);
// digitalWrite(C,LOW);
//
// EcValue = gravityTds.getEcValue(); // then get the value
// Serial.print("#");
// Serial.print(index);
// Serial.print(" EC = ");
// Serial.print(EcValue, 0);
// Serial.print("ppm | ");
// Serial.print("Analog MUX ");
// Serial.println(index);
// delay(2000); // For readability
// break;
// case 2:
// digitalWrite(A,LOW);
// digitalWrite(B,HIGH);
// digitalWrite(C,LOW);
//
// EcValue = gravityTds.getEcValue(); // then get the value
// Serial.print("#");
// Serial.print(index);
// Serial.print(" EC = ");
// Serial.print(EcValue, 0);
// Serial.print("ppm | ");
// Serial.print("Analog MUX ");
// Serial.println(index);
// delay(2000); // For readability
// break;
// case 3:
// digitalWrite(A,HIGH);
// digitalWrite(B,HIGH);
// digitalWrite(C,LOW);
//
// EcValue = gravityTds.getEcValue(); // then get the value
// Serial.print("#");
// Serial.print(index);
// Serial.print(" EC = ");
// Serial.print(EcValue, 0);
// Serial.print("ppm | ");
// Serial.print("Analog MUX ");
// Serial.println(index);
// delay(2000); // For readability
// break;
// case 4:
// digitalWrite(A,LOW);
// digitalWrite(B,LOW);
// digitalWrite(C,HIGH);
//
// EcValue = gravityTds.getEcValue(); // then get the value
// Serial.print("#");
// Serial.print(index);
// Serial.print(" EC = ");
// Serial.print(EcValue, 0);
// Serial.print("ppm | ");
// Serial.print("Analog MUX ");
// Serial.println(index);
// delay(2000); // For readability
// break;
// }
// }
}
<file_sep>/firmware/PNNL/PNNL.ino
#include <Loom.h>
// Include configuration
const char* json_config =
#include "config.h";
// Set enabled modules
;LoomFactory<
Enable::Internet::Disabled,
Enable::Sensors::Enabled,
Enable::Radios::Disabled,
Enable::Actuators::Disabled,
Enable::Max::Disabled
> ModuleFactory{};
LoomManager Loom{ &ModuleFactory };
#include "FeatherFault.h"
#include <Wire.h> // The Wire library carries out I2C communication
#include <MS5803_02.h> // Place the MS5803_02 library folder in your Arduino 'libraries' directory
#include "Adafruit_MCP23008.h"
#define TCAADDR 0x70 //define MUX Hex address
// Declare 'sensor' as the object that will refer to your MS5803 in the sketch
// Enter the oversampling value as an argument. Valid choices are
// 256, 512, 1024, 2048, 4096. Library default = 512.
MS_5803 sensor = MS_5803(0x77, 4096);
Adafruit_ADS1115 ads;
Adafruit_MCP23008 mcp;
#define A 0 //Analog mux A pin
#define B 1 //Analog mux B pin
#define C 2 //Analog mux C pin
#define sensor_cnt 5 // Number of sensors attached
#define samples 16 // Number of samples to gather and average
volatile bool rtc_flag = false;
void wakeISR_RTC() {
// disable the interrupt
detachInterrupt(12);
rtc_flag = true;
}
void tcaselect(uint8_t i) {
if (i > 7){return;}
Wire.beginTransmission(TCAADDR);
Wire.write(1 << i);
Wire.endTransmission();
}
void measure() {
MARK;
for(int index = 0; index < sensor_cnt; index++){ MARK;
Loom.measure(); MARK;
Loom.package(); MARK;
tcaselect(index); MARK;
sensor.initializeMS_5803(false); MARK;
// Set GPIO Extender
mcp.digitalWrite(A,(index & 0b001) >> 0); MARK;
mcp.digitalWrite(B,(index & 0b010) >> 1); MARK;
mcp.digitalWrite(C,(index & 0b100) >> 2); MARK;
double press_mean = 0, press_var = 0, temp_mean = 0, temp_var = 0,
adc_mean = 0, adc_var = 0,
press_samples[samples], temp_samples[samples],
adc_samples[samples],
press_max = 0, press_min = 100000, temp_max = 0, temp_min = 100000,
adc_max = 0, adc_min = 100000;
MARK;
for(int sample = 0; sample < samples; sample++){ MARK;
sensor.readSensor(); MARK;
// Read pressure
double press_val = sensor.pressure(); MARK;
press_mean += press_val;
press_samples[sample] = press_val;
if(press_max < press_val) press_max = press_val;
if(press_min > press_val) press_min = press_val;
// Read temperature
double temp_val = sensor.temperature(); MARK;
temp_mean += temp_val;
temp_samples[sample] = temp_val;
if(temp_max < temp_val) temp_max = temp_val;
if(temp_min > temp_val) temp_min = temp_val;
// Read ADC and calculate ec
double adc_val = ads.readADC_SingleEnded(0); MARK;
adc_mean += adc_val;
adc_samples[sample] = adc_val;
if(adc_max < adc_val) adc_max = adc_val;
if(adc_min > adc_val) adc_min = adc_val;
}
press_mean /= samples;
temp_mean /= samples;
adc_mean /= samples;
MARK;
for(int sample = 0; sample < samples; sample++){ MARK;
press_var += (press_samples[sample] - press_mean)*(press_samples[sample] - press_mean);
temp_var += (temp_samples[sample] - temp_mean)*(temp_samples[sample] - temp_mean);
adc_var += (adc_samples[sample] - adc_mean)*(adc_samples[sample] - adc_mean);
}
press_var /= samples;
temp_var /= samples;
adc_var /= samples;
Loom.add_data("Index", "sensor", index); MARK;
Loom.add_data("Pressure", "mbar", press_mean); MARK;
Loom.add_data("Pressure Variance", "mbar^2", press_var); MARK;
Loom.add_data("Pressure Max", "mbar", press_max); MARK;
Loom.add_data("Pressure Min", "mabr", press_min); MARK;
Loom.add_data("Temperature", "C", temp_mean); MARK;
Loom.add_data("Temperature Variance", "C^2", temp_var); MARK;
Loom.add_data("Temperature Max", "C", temp_max); MARK;
Loom.add_data("Temperature Min", "C", temp_min); MARK;
Loom.add_data("ADC", "digital", adc_mean); MARK;
Loom.add_data("ADC Variance", "digital^2", adc_var); MARK;
Loom.add_data("ADC Max", "digital", adc_max); MARK;
Loom.add_data("ADC Min", "digital", adc_min); MARK;
Loom.display_data(); MARK;
Loom.SDCARD().log(); MARK;
}
}
void setup() {
// Needs to be done for Hypno Board
pinMode(5, OUTPUT); // Enable control of 3.3V rail
pinMode(6, OUTPUT); // Enable control of 5V rail
pinMode(12, INPUT_PULLUP); // Enable waiting for RTC interrupt, MUST use a pullup since signal is active low
pinMode(13, OUTPUT);
//See Above
digitalWrite(5, LOW); // Enable 3.3V rail
digitalWrite(6, HIGH); // Enable 5V rail
digitalWrite(13, LOW);
Wire.begin();
// Setup GPIO extender
mcp.begin(); // use default address 0
mcp.pinMode(A, OUTPUT);
mcp.pinMode(B, OUTPUT);
mcp.pinMode(C, OUTPUT);
// Setup ADC (ADS1115)
ads.setGain(GAIN_TWO);
ads.begin();
Loom.begin_serial(true);
// Get config from SD
// Else use '#include'd json_config above
if ( !Loom.parse_config_SD("config.txt") ) {
Loom.parse_config(json_config);
LPrintln("\n ** Using Hard-Coded Config ** ");
}
else {
LPrintln("\n ** Using SD Card Config (config.txt) ** ");
}
Loom.print_config();
// Register an interrupt on the RTC alarm pin
Loom.InterruptManager().register_ISR(12, wakeISR_RTC, LOW, ISR_Type::IMMEDIATE);
FeatherFault::PrintFault(Serial);
Serial.flush();
FeatherFault::StartWDT(FeatherFault::WDTTimeout::WDT_8S);
LPrintln("\n ** Setup Complete ** ");
}
void loop() {
digitalWrite(5, LOW); // Enable 3.3V rail
digitalWrite(6, HIGH); // Enable 5V rail
digitalWrite(13, HIGH);
// As it turns out, if the SD card is initialized and you change
// the states of the pins to ANY VALUE, the SD card will fail to
// write. As a result, we ensure that the board has been turned
// off at least once before we make any changes to the pin states
if (rtc_flag) { MARK;
pinMode(23, OUTPUT);
pinMode(24, OUTPUT);
pinMode(10, OUTPUT);
Loom.power_up(); MARK;
// Setup GPIO extender
mcp.begin(); MARK; // use default address 0
mcp.pinMode(A, OUTPUT); MARK;
mcp.pinMode(B, OUTPUT); MARK;
mcp.pinMode(C, OUTPUT); MARK;
measure(); MARK;
}
// set the RTC alarm to a duration with TimeSpan
Loom.InterruptManager().RTC_alarm_duration(TimeSpan(0,0,Loom.get_interval(),0)); MARK;
Loom.InterruptManager().reconnect_interrupt(12); MARK;
digitalWrite(13, LOW);
digitalWrite(5, HIGH); // Disable 3.3V rail
digitalWrite(6, LOW); // Disable 5V rail
pinMode(23, INPUT);
pinMode(24, INPUT);
pinMode(10, INPUT);
// Sleep Manager autmatically calls power_down on every sensor before sleeping
// And power_up after waking.
rtc_flag = false;
FeatherFault::StopWDT();
Loom.SleepManager().sleep();
while (!rtc_flag);
FeatherFault::StartWDT(FeatherFault::WDTTimeout::WDT_8S);
}//end of loop
<file_sep>/README.md
# PNNL-Flux
Firmware and embedded hardware for the PNNL-Flux Probe project, designed by OPEnS Lab OSU. Check out the project Wiki [here](https://github.com/OPEnSLab-OSU/OPEnS-Lab-Home/wiki/PNNL-Flux-Tool).
## Firmware
The firmware adapts OPEnS Lab's Loom framework to allow the Feather M0 to store data from five pressure/temperature sensors (MS5803-02BA) and an ADC (ADS1115) that is translating an analog signal from the electrical conductivity (EC) ciruitry.
## Embedded Hardware
The embedded hardware has been divided into three sections: the head, the rod, and the sensors.
### Head Hardware
As the brain of the device the head consists of: the Feather M0, the Hypnos, and the batteries.
### Rod Hardware
As the intermediary component between the head and the sensors the rod hardware consists of: an I2C Multiplexer, the ADS1115, an I2C Digital Potentiometer, an I2C GPIO Extender (that controls the Analog Multiplexer, and the EC circuitry.
### Sensor Hardware
With each sensor having its own PCB there are five mounting points throughout the rod and each consists of: the circuitry for the pressure/temperature sensor, a pressure/temperature sensors (MS5803-02BA), and the probes for tracking electrical conductivity.
<file_sep>/firmware/PNNL_Calibration/config.h
"{\
'general':\
{\
'name':'Device',\
'instance':1,\
'interval':5000,\
'print_verbosity':2\
},\
'components':[\
{\
'name':'Analog',\
'params':'default'\
},\
{\
'name':'SD',\
'params':[false,100,10,'test',true]\
},\
{\
'name':'DS3231',\
'params':'default'\
},\
{\
'name':'Interrupt_Manager',\
'params':[0]\
},\
{\
'name':'Sleep_Manager',\
'params':[true,false,1]\
}\
]\
}"
<file_sep>/firmware/PNNL_Calibration/PNNL_Calibration.ino
#include <Loom.h>
// Include configuration
const char* json_config =
#include "config.h";
// Set enabled modules
;LoomFactory<
Enable::Internet::Disabled,
Enable::Sensors::Enabled,
Enable::Radios::Disabled,
Enable::Actuators::Disabled,
Enable::Max::Disabled
> ModuleFactory{};
LoomManager Loom{ &ModuleFactory };
#include "FeatherFault.h"
#include <Wire.h> // The Wire library carries out I2C communication
#include <MS5803_02.h> // Place the MS5803_02 library folder in your Arduino 'libraries' directory
#include "Adafruit_MCP23008.h"
#define TCAADDR 0x70 //define MUX Hex address
// Declare 'sensor' as the object that will refer to your MS5803 in the sketch
// Enter the oversampling value as an argument. Valid choices are
// 256, 512, 1024, 2048, 4096. Library default = 512.
MS_5803 sensor = MS_5803(0x77, 4096);
Adafruit_ADS1115 ads;
Adafruit_MCP23008 mcp;
#define A 0 //Analog mux A pin
#define B 1 //Analog mux B pin
#define C 2 //Analog mux C pin
#define index 0 // Current sensor being tested
#define sensor_cnt 5 // Number of sensors attached
#define samples 16 // Number of samples to gather and average
#define runs 1000 // Number of runs to calibrate
const double threshold = 30;
double run_val[runs];
double average;
double sample_variance;
double mean_square_error;
double adc_mean = 0;
int curr_run = 0;
double temp;
bool done = false;
void tcaselect(uint8_t i) {
if (i > 7){return;}
Wire.beginTransmission(TCAADDR);
Wire.write(1 << i);
Wire.endTransmission();
}
void measure() {
MARK;
Loom.measure(); MARK;
Loom.package(); MARK;
tcaselect(index); MARK;
sensor.initializeMS_5803(false); MARK;
// Set GPIO Extender
mcp.digitalWrite(A,(index & 0b001) >> 0); MARK;
mcp.digitalWrite(B,(index & 0b010) >> 1); MARK;
mcp.digitalWrite(C,(index & 0b100) >> 2); MARK;
double press_mean = 0, press_var = 0, temp_mean = 0, temp_var = 0, adc_var = 0,
press_samples[samples], temp_samples[samples],
adc_samples[samples],
press_max = 0, press_min = 100000, temp_max = 0, temp_min = 100000,
adc_max = 0, adc_min = 100000;
MARK;
for(int sample = 0; sample < samples; sample++){ MARK;
sensor.readSensor(); MARK;
// Read pressure
double press_val = sensor.pressure(); MARK;
press_mean += press_val;
press_samples[sample] = press_val;
if(press_max < press_val) press_max = press_val;
if(press_min > press_val) press_min = press_val;
// Read temperature
double temp_val = sensor.temperature(); MARK;
temp_mean += temp_val;
temp_samples[sample] = temp_val;
if(temp_max < temp_val) temp_max = temp_val;
if(temp_min > temp_val) temp_min = temp_val;
// Read ADC and calculate ec
double adc_val = ads.readADC_SingleEnded(0); MARK;
adc_mean += adc_val;
adc_samples[sample] = adc_val;
if(adc_max < adc_val) adc_max = adc_val;
if(adc_min > adc_val) adc_min = adc_val;
}
press_mean /= samples;
temp_mean /= samples;
adc_mean /= samples;
MARK;
for(int sample = 0; sample < samples; sample++){ MARK;
press_var += (press_samples[sample] - press_mean)*(press_samples[sample] - press_mean);
temp_var += (temp_samples[sample] - temp_mean)*(temp_samples[sample] - temp_mean);
adc_var += (adc_samples[sample] - adc_mean)*(adc_samples[sample] - adc_mean);
}
press_var /= samples;
temp_var /= samples;
adc_var /= samples;
// Sample Mean Estimator
run_val[curr_run] = adc_mean;
curr_run++;
MARK;
average = 0;
for(int n = 0; n < curr_run; n++){ MARK;
average += 1/double(curr_run) * run_val[n];
}
// Sample Variance
MARK;
if(curr_run > 1){
sample_variance = 0;
for(int n = 0; n < curr_run; n++){ MARK;
sample_variance += 1/(double(curr_run)-1) * (run_val[n]-average) * (run_val[n]-average);
}
}
// Mean Square Error
mean_square_error = sample_variance/double(curr_run);
// Grab final temperature
temp = temp_mean;
Loom.add_data("Index", "sensor", index); MARK;
Loom.add_data("Pressure", "mbar", press_mean); MARK;
Loom.add_data("Pressure Variance", "mbar^2", press_var); MARK;
Loom.add_data("Pressure Max", "mbar", press_max); MARK;
Loom.add_data("Pressure Min", "mabr", press_min); MARK;
Loom.add_data("Temperature", "C", temp_mean); MARK;
Loom.add_data("Temperature Variance", "C^2", temp_var); MARK;
Loom.add_data("Temperature Max", "C", temp_max); MARK;
Loom.add_data("Temperature Min", "C", temp_min); MARK;
Loom.add_data("ADC", "digital", adc_mean); MARK;
Loom.add_data("ADC Variance", "digital^2", adc_var); MARK;
Loom.add_data("ADC Max", "digital", adc_max); MARK;
Loom.add_data("ADC Min", "digital", adc_min); MARK;
Loom.add_data("ADC Estimator", "digital", average); MARK;
Loom.add_data("ADC Sample Variance", "digital^2", sample_variance); MARK;
Loom.add_data("ADC Mean Square Error", "digital", mean_square_error); MARK;
Loom.SDCARD().log(); MARK;
}
void setup() {
// Needs to be done for Hypno Board
pinMode(5, OUTPUT); // Enable control of 3.3V rail
pinMode(6, OUTPUT); // Enable control of 5V rail
pinMode(12, INPUT_PULLUP); // Enable waiting for RTC interrupt, MUST use a pullup since signal is active low
pinMode(13, OUTPUT);
//See Above
digitalWrite(5, LOW); // Enable 3.3V rail
digitalWrite(6, HIGH); // Enable 5V rail
digitalWrite(13, LOW);
Wire.begin();
// Setup GPIO extender
mcp.begin(); // use default address 0
mcp.pinMode(A, OUTPUT);
mcp.pinMode(B, OUTPUT);
mcp.pinMode(C, OUTPUT);
// Setup ADC (ADS1115)
ads.setGain(GAIN_TWO);
ads.begin();
Loom.begin_serial(true);
Loom.parse_config(json_config);
Loom.print_config();
while(!Serial);
FeatherFault::PrintFault(Serial);
Serial.flush();
FeatherFault::StartWDT(FeatherFault::WDTTimeout::WDT_8S);
LPrintln("\n ** Setup Complete ** ");
}
void loop() {
if((curr_run > 100 && mean_square_error < threshold && !done) || (curr_run >= runs && !done)){
Serial.print("FINAL Ave: ");
Serial.println(average);
Serial.print("FINAL C: ");
Serial.println(temp);
done = true;
}
else if(!done){
measure(); MARK;
Serial.print("Run: ");
Serial.println(curr_run);
Serial.print("Lst: ");
Serial.println(adc_mean);
Serial.print("Ave: ");
Serial.println(average);
Serial.print("MSE: ");
Serial.println(mean_square_error);
Serial.print("Thr: ");
Serial.println(threshold);
Serial.println("------------------------------");
delay(1000);
}
}//end of loop
<file_sep>/firmware/archive/MS5803_MUX/MS5803_MUX.ino
/* MS5803_02_MUX.ino
This version *only works* with the MS5803-02BA sensor, not the other
pressure models (like the MS5803-30BA, MS5803-01BA etc). You can find
libraries for those other models at http://github.com/millerlp
*/
// The Wire library carries out I2C communication
#include <Wire.h>
// Place the MS5803_02 library folder in your Arduino 'libraries' directory
#include <MS5803_02.h>
#include "GravityTDS.h" // EC/TDS sensor
#define TCAADDR 0x70 //define MUX Hex address
#define TdsSensorPin A0 //define pin
GravityTDS gravityTds; //create class
#define A 9 //Analog mux A pin
#define B 11 //Analog mux B pin
#define C 13 //Analog mux C pin
// Declare 'sensor' as the object that will refer to your MS5803 in the sketch
// Enter the oversampling value as an argument. Valid choices are
// 256, 512, 1024, 2048, 4096. Library default = 512.
MS_5803 sensor = MS_5803(0x77, 4096);
float tempF, tempC;
float tdsValue = 0;
void tcaselect(uint8_t i) {
if (i > 7) return;
Wire.beginTransmission(TCAADDR);
Wire.write(1 << i);
Wire.endTransmission();
}
void setup() {
pinMode(5, OUTPUT);
digitalWrite(5, LOW); // Sets pin 5, the pin with the 3.3V rail, to output and enables the rail
pinMode(6, OUTPUT);
digitalWrite(6, HIGH); // Sets pin 6, the pin with the 5V rail, to output and enables the rail
// Start the serial ports.
Wire.begin();
Wire.setClock(10000); // Attempt to decrease i2c speed
// Oscilliscope testing shows it has no effect
Serial.begin(115200); // other values include 9600, 14400, 57600 etc.
Serial.println("MS5803 MUX and EC Test"); Serial.println("");
gravityTds.setPin(TdsSensorPin);
gravityTds.setAref(3.3); //reference voltage on ADC, default 5.0V on Arduino UNO
gravityTds.setAdcRange(1024); //1024 for 10bit ADC;4096 for 12bit ADC
gravityTds.begin(); //initialization
delay(1000);
pinMode(A, OUTPUT);
pinMode(B, OUTPUT);
pinMode(C, OUTPUT);
}
void loop() {
for(int index = 0; index < 5; index += 1){
tcaselect(index);
sensor.initializeMS_5803(false);
sensor.readSensor();
// Show pressure
Serial.println("---------------------------------------");
Serial.print("#");
Serial.print(index);
Serial.print(" Pressure = ");
Serial.print(sensor.pressure());
Serial.print(" mbar ");
// Show temperature
Serial.print("#");
Serial.print(index);
Serial.print(" Temperature = ");
tempC = sensor.temperature();
tempF = (sensor.temperature() * 9/5) + 32;
Serial.print(tempF);
Serial.println("F");
tcaselect(5);
gravityTds.setTemperature(tempC); // set the temperature and execute temperature compensation
gravityTds.update(); //sample and calculate
switch(index){
case 0:
digitalWrite(A,LOW);
digitalWrite(B,LOW);
digitalWrite(C,LOW);
tdsValue = gravityTds.getTdsValue(); // then get the value
Serial.print("#");
Serial.print(index);
Serial.print(" EC = ");
Serial.print(tdsValue, 0);
Serial.print("ppm | ");
Serial.print("Analog MUX ");
Serial.println(index);
delay(2000); // For readability
break;
case 1:
digitalWrite(A,HIGH);
digitalWrite(B,LOW);
digitalWrite(C,LOW);
tdsValue = gravityTds.getTdsValue(); // then get the value
Serial.print("#");
Serial.print(index);
Serial.print(" EC = ");
Serial.print(tdsValue, 0);
Serial.print("ppm | ");
Serial.print("Analog MUX ");
Serial.println(index);
delay(2000); // For readability
break;
case 2:
digitalWrite(A,LOW);
digitalWrite(B,HIGH);
digitalWrite(C,LOW);
tdsValue = gravityTds.getTdsValue(); // then get the value
Serial.print("#");
Serial.print(index);
Serial.print(" EC = ");
Serial.print(tdsValue, 0);
Serial.print("ppm | ");
Serial.print("Analog MUX ");
Serial.println(index);
delay(2000); // For readability
break;
case 3:
digitalWrite(A,HIGH);
digitalWrite(B,HIGH);
digitalWrite(C,LOW);
tdsValue = gravityTds.getTdsValue(); // then get the value
Serial.print("#");
Serial.print(index);
Serial.print(" EC = ");
Serial.print(tdsValue, 0);
Serial.print("ppm | ");
Serial.print("Analog MUX ");
Serial.println(index);
delay(2000); // For readability
break;
case 4:
digitalWrite(A,LOW);
digitalWrite(B,LOW);
digitalWrite(C,HIGH);
tdsValue = gravityTds.getTdsValue(); // then get the value
Serial.print("#");
Serial.print(index);
Serial.print(" EC = ");
Serial.print(tdsValue, 0);
Serial.print("ppm | ");
Serial.print("Analog MUX ");
Serial.println(index);
delay(2000); // For readability
break;
}
}
}
| c64a03981b45103ec4ecc0c5102dd3a3214f0d40 | [
"Markdown",
"C",
"C++"
] | 6 | C++ | OPEnSLab-OSU/PNNLFluxV1 | d018ccd39de72acb205d1a293ba5de3ca78edd6b | c999841d04b232c6f0e6402a65616a7091bd7fe0 |
refs/heads/master | <repo_name>krishnasalampuriya/OS-practicals<file_sep>/FCFS.C
#include <stdio.h>
int N; // Number of Processes
int At[100]; //Arrival timr array
int Bt[100]; //Burst Time Array
float Awt,Att; //Average wating time and average turn around time
int TypeOfAlgo; // Type of Algoritm
void inputData();
void calculateFCFS();
void calculateRoundRobin();
void outputData();
void selectAlgo();
/// MAin Function
int main(){
selectAlgo();
// inputData();
// calculateFCFS();
// outputData();
return 0;
}
void inputData(){
printf("Enter the NUmber of processes ");
scanf("%d",&N);
if(TypeOfAlgo ==1){
for(int i=1;i<=N;i++){ // For FCFS
printf("Enter the Arrival Time of Process P%d ",i);
scanf("%d",&At[i]);
printf("Enter the Burst Time of Process P%d ",i);
scanf("%d",&Bt[i]);
}
}
else if(TypeOfAlgo == 2){ // for SJF
}
else { // for RR
for(int i=1;i<=N;i++){
printf("Enter the Burst Time of Process P%d ",i);
scanf("%d",&Bt[i]);
}
}
}
/*
void calculateFCFS(){
int Ttt=0,Twt=0; //Total turnaround and wating time
int Tt=0,Wt=0; // Turn around Time And Wating Time
for(int i=1;i<=N;i++){
Wt = Tt - At[i];
Tt = Tt + Bt[i];
Ttt = Ttt + Tt;
Twt = Wt + Twt;
}
Att = Ttt/N;
Awt = Twt/N;
}
void outputData(){
printf("Average Wating Time is %f ",Awt);
printf("\nAverage Turn Around Time is %f ", Att);
} */
void selectAlgo(){
printf("Enter the type of Algorithm ");
printf("Type 1 for FCFS\nType 2 for SJF\n Type 3 For Round Robin\n");
scanf("%d",&TypeOfAlgo);
if(!(TypeOfAlgo == 1 || TypeOfAlgo == 2 || TypeOfAlgo == 3)){
printf("Select proper Algorithm\n");
selectAlgo();
}
printf("Type = %d",TypeOfAlgo);
}<file_sep>/README.md
# OS-practicals
It contains all OS practicals
Just editing some lines
| 620795aa9fb2448e403f19314655a478ee85c7c8 | [
"Markdown",
"C"
] | 2 | C | krishnasalampuriya/OS-practicals | 6ba768d6d0998cbf6d934f76e891a9ade1955a5b | 96cdaa1830347d4c360ee9eab398e56fbb4fc341 |
refs/heads/master | <repo_name>kaidoj/datatables-examples<file_sep>/sqlite_examples/dataobject/index.php
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>DataTables example</title>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css"/>
<script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable( {
"serverSide": true,
"ajax" : "ajax.php",
"columns": [
{ "data": "id" },
{ "data": "Name" },
{ "data": "UnitPrice" }
]
} );
} );
</script>
</head>
<body id="dt_example">
<div id="container">
<h1>Datatables - An example of using column keys</h1>
<p>Source codes: <a href="https://github.com/n1crack/datatables-examples/tree/master/sqlite_examples/dataobject">https://github.com/n1crack/datatables-examples/tree/master/sqlite_examples/dataobject</a></p>
<table border="0" cellpadding="4" cellspacing="0" class="display" id="example">
<thead>
<tr>
<th width="8%">ID</th>
<th width="32%">Name</th>
<th width="60%">Unit Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>loading...</td>
</tr>
</tbody>
</table>
</div>
<?php include_once("../../analyticstracking.php") ?>
</body>
</html><file_sep>/index.php
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>DataTables examples</title>
</head>
<body id="dt_example">
<h2>Datatables Examples - full list</h2>
<div id="container">
<?php
$files = glob('sqlite_examples/*', GLOB_BRACE);
foreach ($files as $file)
{
?>
<p><a href='/<?php echo $file; ?>/'><?php echo $file; ?></a></p>
<?php
}
?>
</div>
<?php include_once("analyticstracking.php") ?>
</body>
</html><file_sep>/sqlite_examples/individualsearch/index.php
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>DataTables example</title>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css"/>
<script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#example tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
var table = $('#example').DataTable( {
"serverSide": true,
"ajax" : "ajax.php",
"columns": [
null,
null,
null
]
} );
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw(false);
}
} );
} );
} );
</script>
<style>
tfoot input {
width: 100%;
padding: 3px;
box-sizing: border-box;
}
</style>
</head>
<body id="dt_example">
<div id="container">
<h1>Datatables - individual search example</h1>
<p>Source codes: <a href="https://github.com/n1crack/datatables-examples/tree/master/sqlite_examples/individualsearch">https://github.com/n1crack/datatables-examples/tree/master/sqlite_examples/individualsearch</a></p>
<table border="0" cellpadding="4" cellspacing="0" class="display" id="example">
<thead>
<tr>
<th width="8%">ID</th>
<th width="32%">Name</th>
<th width="60%">Unit Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>loading...</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
</tr>
</tfoot>
</table>
</div>
<?php include_once("../../analyticstracking.php") ?>
</body>
</html><file_sep>/README.md
# Datatables examples
[Datatables php libray](https://github.com/n1crack/datatables) examples.
[Online Demo](http://datatables.16mb.com/)
[Issues](https://github.com/n1crack/datatables/issues)
<file_sep>/other_examples/mysql.php
<?php
// add composer autoload.
require '../vendor/autoload.php';
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\MySQL;
// set your database config.
$config = ['host' => 'localhost',
'port' => '3306',
'username' => 'homestead',
'password' => '<PASSWORD>',
'database' => 'sakila'];
// load your library
$dt = new Datatables(new MySQL($config));
// set sql query
$dt->query("Select film_id, title, description from film ;");
// run it.
echo $dt->generate();
// it is super easy.<file_sep>/other_examples/phalcon.php
<?php
// Define route
// ...
$router->add(
"/", [
"controller" => "home",
"action" => "index"
]
);
$router->add(
"/ajax", [
"controller" => "film",
"action" => "ajax"
]
);
// Define film controller
// ...
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\PhalconAdapter;
Class FilmController extends Controller {
// ...
public function AjaxAction() {
$datatables = new Datatables(new PhalconAdapter($this->di, 'db'));
$query = $this->modelsManager->createBuilder()
->columns('film_id, title, description')
->from('App\Models\Film')
->getQuery()
->getSql();
$datatables->query($query['sql']);
return $datatables->generate();
}
}<file_sep>/sqlite_examples/simple/ajax.php
<?php
require '../../vendor/autoload.php';
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\SQLite;
$path = realpath(dirname(__FILE__) . '/../../db/Chinook_Sqlite_AutoIncrementPKs.sqlite');
$dt = new Datatables(new SQLite($path));
$dt->query("Select TrackId, Name, UnitPrice from Track");
echo $dt->generate();
<file_sep>/sqlite_examples/edit/ajax.php
<?php
require '../../vendor/autoload.php';
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\SQLite;
$path = realpath(dirname(__FILE__) . '/../../db/Chinook_Sqlite_AutoIncrementPKs.sqlite');
$dt = new Datatables(new SQLite($path));
$dt->query("Select TrackId as id, Name, UnitPrice from Track");
// edit 'id' column
$dt->edit('id', function ($data){
return editurl($data['id'], 'edit') . '-' . $data['id'];
});
// edit 'UnitPrice' column.
$dt->edit('UnitPrice', function ($data){
return '< ' . $data['UnitPrice'] . ' >';
});
echo $dt->generate();
function editurl($id, $text)
{
return '<a href="#' . $id . '">' . $text .'</a>';
}<file_sep>/sqlite_examples/group_by/ajax.php
<?php
require '../../vendor/autoload.php';
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\SQLite;
$path = realpath(dirname(__FILE__) . '/../../db/Chinook_Sqlite_AutoIncrementPKs.sqlite');
$dt = new Datatables(new SQLite($path));
$dt->query("Select
Genre.Name as genre_name,
sum(Milliseconds)/(1000*60) as total_length
from Genre
join Track on Track.GenreId = Genre.GenreId
group by Genre.GenreId");
$dt->edit('total_length', function ($data){
return $data['total_length'] . ' minutes';
});
echo $dt->generate();
<file_sep>/sqlite_examples/join/ajax.php
<?php
require '../../vendor/autoload.php';
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\SQLite;
$path = realpath(dirname(__FILE__) . '/../../db/Chinook_Sqlite_AutoIncrementPKs.sqlite');
$dt = new Datatables(new SQLite($path));
$dt->query("Select TrackId, Track.Name, Title as Album, MediaType.Name as MediaType,
UnitPrice, Milliseconds, Bytes from Track
JOIN Album ON Album.AlbumId = Track.AlbumId
JOIN MediaType ON MediaType.MediaTypeId = Track.MediaTypeId");
echo $dt->generate();
<file_sep>/other_examples/prestashop.php
<?php
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\PSAdapter;
/**
* Example for Prestashop FrontController
*/
class ModuleNameControllerNameModuleFrontController extends ModuleFrontController
{
public function displayAjaxDatatableResults()
{
$dt = new Datatables(new PSAdapter([]));
$dt->query('SELECT * FROM ' . _DB_PREFIX_ . '_table');
return $dt->generate();
}
} | e606b7ef5a6d22335985c17aa9eae3c41b821c24 | [
"Markdown",
"PHP"
] | 11 | PHP | kaidoj/datatables-examples | 9e14a6e9110ce5491d61fa41c8059839f5888225 | 114c3cbe553034dc3dd0ef49320e8dcff7a2296d |
refs/heads/master | <repo_name>davidliang104/CSIS401_Lab01<file_sep>/app/src/main/java/com/example/csis401lab_1/MainActivity.kt
/*
CSIS-401 Lab-01
by <NAME> (S00049751)
*/
package com.example.csis401lab_1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
var choice: Double? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun setSize(v: View) {
// Choose the size of the photos
choice = when (v) {
option1 -> 0.19
option2 -> 0.49
option3 -> 0.79
else -> 0.0
}
}
fun displayPrice(v:View) {
// Get number entered by user
val num = numOfPrints.text.toString().toDoubleOrNull()
// Check if either the input is invalid, or if no size was selected
if (num == null) {
textResult.text = ""
Toast.makeText(this, "Enter a valid number", Toast.LENGTH_SHORT).show()
} else if (choice == null) {
textResult.text = ""
Toast.makeText(this, "Select a photo size", Toast.LENGTH_SHORT).show()
} else {
val displayText = "The order cost is $ " + String.format("%.2f", num * choice!!)
textResult.text = displayText
}
}
}<file_sep>/settings.gradle
include ':app'
rootProject.name = "CSIS401 Lab-1" | b825de551c866f42e8ad60c0016c0aec6dfbd7ff | [
"Kotlin",
"Gradle"
] | 2 | Kotlin | davidliang104/CSIS401_Lab01 | 144b6cbb361ad809103b337480ba1f91d7cb2374 | 5ef9f070c4478d5ff03507c1c04b7b7196b91ee3 |
refs/heads/master | <repo_name>hikari97/helper<file_sep>/index-file.php
<?php
// you can add to the array
$ext_array = array(".htm", ".php", ".asp", ".js"); //list of extensions not required
$dir1 = ".";
$filecount1 = 0;
$d1 = dir($dir1);
while ($f1 = $d1->read()) {
$fext = substr($f1,strrpos($f1,".")); //gets the file extension
if (in_array($fext, $ext_array)) { //check for file extension in list
continue;
}else{
if(($f1!= '.') && ($f1!= '..')) {
if(!is_dir($f1)) $filecount1++;
$key = filemtime($f1);
$files[$key] = $f1 ;
}
}
}
// use either ksort or krsort => (reverse order)
//ksort($files);
krsort($files);
foreach ($files as $f1) {
$thelist .= '<LI><a href="'.$f1.'">'.$f1.'</a>';
}
?>
<P>Dir:</p>
<UL>
<P><?=$thelist?></p>
</UL> | 30a8b242f871d3a6f1ffe0c16959feba4d6416be | [
"PHP"
] | 1 | PHP | hikari97/helper | a05a945aa36bfd7f9f73c6c3e1131bdf19177bec | 5cd0ef47a5995efc3f1352236126c99483d19871 |
refs/heads/master | <repo_name>nxr08s/json-parser-cpp<file_sep>/src/main.cpp
#include "Parser.h"
static const char exampleJson[] = R"({"web-app": {
"servlet": [
{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "<EMAIL>",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
"templateProcessorClass": "org.cofax.WysiwygTemplate",
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
"templatePath": "templates",
"templateOverridePath": "",
"defaultListTemplate": "listTemplate.htm",
"defaultFileTemplate": "articleTemplate.htm",
"useJSP": false,
"jspListTemplate": "listTemplate.jsp",
"jspFileTemplate": "articleTemplate.jsp",
"cachePackageTagsTrack": 200,
"cachePackageTagsStore": 200,
"cachePackageTagsRefresh": 60,
"cacheTemplatesTrack": 100,
"cacheTemplatesStore": 50,
"cacheTemplatesRefresh": 15,
"cachePagesTrack": 200,
"cachePagesStore": 100,
"cachePagesRefresh": 10,
"cachePagesDirtyRead": 10,
"searchEngineListTemplate": "forSearchEnginesList.htm",
"searchEngineFileTemplate": "forSearchEngines.htm",
"searchEngineRobotsDb": "WEB-INF/robots.db",
"useDataStore": true,
"dataStoreClass": "org.cofax.SqlDataStore",
"redirectionClass": "org.cofax.SqlRedirection",
"dataStoreName": "cofax",
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
"dataStoreUser": "sa",
"dataStorePassword": "<PASSWORD>",
"dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
"dataStoreInitConns": 10,
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "debug",
"maxUrlLength": 500}},
{
"servlet-name": "cofaxEmail",
"servlet-class": "org.cofax.cds.EmailServlet",
"init-param": {
"mailHost": "mail1",
"mailHostOverride": "mail2"}},
{
"servlet-name": "cofaxAdmin",
"servlet-class": "org.cofax.cds.AdminServlet"},
{
"servlet-name": "fileServlet",
"servlet-class": "org.cofax.cds.FileServlet"},
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
"templatePath": "toolstemplates/",
"log": 1,
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
"logMaxSize": "",
"dataLog": 1,
"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
"dataLogMaxSize": "",
"removePageCache": "/content/admin/remove?cache=pages&id=",
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
"lookInContext": 1,
"adminGroupID": 4,
"betaServer": true}}],
"servlet-mapping": {
"cofaxCDS": "/",
"cofaxEmail": "/cofaxutil/aemail/*",
"cofaxAdmin": "/admin/*",
"fileServlet": "/static/*",
"cofaxTools": "/tools/*"},
"taglib": {
"итем": "проверка русского языка"
"taglib-uri": "cofax.tld",
"taglib-location": "/WEB-INF/tlds/cofax.tld"}}})";
void printDataTree(const DataTree* node, const int level = 0);
int main() {
setlocale(LC_ALL, "ru_ru.utf8");
Parser parser(exampleJson);
parser.parse();
if (parser.success())
printDataTree(parser.getData());
else
std::cout << "Error on position " << parser.getPos() << ": " << parser.getError() << std::endl;
system("pause");
return 0;
}
#define OFFSET(x) for (int i = 0; i < x; i++)\
std::cout << "\t"
void printDataTree(const DataTree * node, const int level) {
OFFSET(level);
std::cout << "Имя: " << node->getName() << std::endl;
OFFSET(level);
std::cout << "Тип: " << DataTree::dataTypeStrings[(unsigned int)node->getType()] << std::endl;
OFFSET(level);
std::cout << "Данные: " << node->getData() << std::endl;
for (auto dt = node->getChildren()->begin(); dt != node->getChildren()->end(); dt++) {
printDataTree(*dt, level + 1);
}
std::cout << std::endl;
}<file_sep>/README.md
# Json parser
C++ JSON parser with simple test / example of it's work. To parse and verify JSON data, state machine (sort of) is using. Main idea pretty simple, but main problem here - state machine itself.
Despite several moments, parser meets all (almost) requirements of [RFC JSON standart](https://tools.ietf.org/html/rfc7159).
Data stores in objects in form of strings with its type (to manually convert them to appropriate data type). Data hierarchy is saved.
Main reasons to create this parser is:
- Educational purpose
- Informative errors (if there any)
- To use it in desktop app to visulize process of parsing json strings
- Practice with state machines
### State machine and transition table
Parser parse each char one by one, and because of the type of input data (chars), its hard (and, probably, inefficient) to change states by simply get new state from matrix by index. Whole state machine based on many (realy many) switch-case statements.
This state machine have state stack to remember states (e.g. string in object, and this object in array - we need to remebet that we in array and etc.)
#### Here is transition table:
| id | State | { | } | [ | ] | , | : | " | letter | num +-. | ws char | \ | t | f | n |
| :- | :---------------- | :-------: | :----: | :-------: | :----: | :--: | :--: | :-------: | :--: | :-------: | :-----: | :--------: | :--------: | :--------: | :--------: |
| 2 | **Initial** | 3#push(2) | #2 | 4#push(2) | #2 | #2 | #2 | #2 | #2 | #2 | ## | #2 | #2 | #2 | #2 |
| 3 | **Object** | #3 | #ret | #3 | #3 | | #3 | 5#push(3) | #3 | #3 | ## | #3 | #3 | #3 | #3 |
| 4 | **Array** | 3#push(4) | #4 | 4#push(4) | #ret | | #4 | 9#push(4) | #4 | 9#push(4) | ## | #4 | 12#push(4) | 13#push(4) | 14#push(4) |
| 5 | **Name** | 5 | 5 | 5 | 5 | 5 | 5 | 6 | 5 | 5 | 5 | 11#push(5) | 5 | 5 | 5 |
| 6 | **After name** | #6 | #6 | #6 | #6 | #6 | 7 | #6 | #6 | #6 | ## | #6 | #6 | #6 | #6 |
| 7 | **Before value** | 3 | #7 | 4 | #7 | #7 | #7 | 9 | #7 | 8 | ## | #7 | 12 | 13 | 14 |
| 8 | **Number** | #8 | 2x#ret | #8 | 2x#ret | #ret | #8 | #8 | #8 | 8 | 10 | #8 | #8 | #8 | #8 |
| 9 | **String** | 9 | 9 | 9 | 9 | 9 | 9 | 10 | 9 | 9 | 9 | 11#push(9) | 9 | 9 | 9 |
| 10 | **After Value** | #10 | 2x#ret | #10 | 2x#ret | #ret | #10 | #10 | #10 | #10 | ## | #10 | #10 | #10 | #10 |
| 11 | **Char escape** | #ret | #ret | #ret | #ret | #ret | #ret | #ret | #ret | #ret | #ret | #ret | #ret | #ret | #ret |
| 12 | **True** | #12 | #12 | #12 | #12 | #12 | #12 | #12 | #12 | #12 | ## | #12 | #12 | #12 | #12 |
| 13 | **False** | #13 | #13 | #13 | #13 | #13 | #13 | #13 | #13 | #13 | ## | #13 | #13 | #13 | #13 |
| 14 | **Null** | #13 | #13 | #13 | #13 | #13 | #13 | #13 | #13 | #13 | ## | #13 | #13 | #13 | #13 |
#### And errors:
| Code | Error message |
| :--- | :------------------------------- |
| #2 | Array or object expected |
| #3 | Value's name expected |
| #4 | Value expected |
| #6 | `:` expected |
| #8 | Number, `}`, `]` or `,` expected |
| #12 | `True` expected |
| #13 | `False` expected |
| #14 | `Null` expected |
#### Explanation of "WTF is this?"
Transitions between states implemented in `*State.cpp` files, where each file represents certain row from transition table.
Explanations of statements from table:
- `x#push(y)` - go to state `x` and push state `y` into state stack
- `x` - just go to state `x`
- `#ret` - pop state from state stack
- `2x#ret` - pop 2 states from state stack
- `#x` - error `x` (see error codes) occured
- `##` - ignore char
#### How to use it
To parse string, you need to create object `Parser` with pointer to `const char*` string and size of the string as arguments. If size of string is ommited, parser will stop on `\0` char. Then you can start parse string by call `parse()` method. If you pass `False` to this method, parser will parse only one char and paused. If argument is omitted, parser will parse string till the end (or first error).
You can get error message by calling `getError()` method and error position in string by calling 'getPos()' method.
Method `success()` return state of parser.
Extracted data can be accessed by calling `getData()` method. This method returns `DataTree*` pointer to root of data tree. Suposed, that you know hierachy of data and type of data, and can manualy convert extracted data to needed type.
### Todo:
- [ ] ADD COMMENTS ASAP !!!
- [ ] Make valid only letters in name
- [ ] Somehow make autotype to data (RTTI?)
- [ ] Add `E` notation to numbers
| 2824ed34ca487245fc1c6c7f20bbd70ed73af4b6 | [
"Markdown",
"C++"
] | 2 | C++ | nxr08s/json-parser-cpp | ec2b06287a203ded9935b54aeadf312c1001adb1 | 1a0a1929b9c7243def3c7381fd04342a5cc7cb01 |
refs/heads/master | <file_sep>##
## This function will create/replace a graphic file plot3.png
## showing a plot of the Sub Metering Energy values vs Date
## based on information contained in
## https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip
## The function assumes the text file household_power_consumption.txt
## has been extracted from the .zip file and it's located
## in the working directory.
## The function also uses the package "lubridate", so it assumes
## it is already installed
##
plot3 <- function() {
## Read file
myData <-read.table("household_power_consumption.txt", header= TRUE, sep=";")
## Subset only the two dates to be used in the analysis
z<-myData$Date == "1/2/2007" | myData$Date == "2/2/2007"
myNewData<-myData[z,]
## Remove the original data from memory
rm(myData)
## Reformat date and time columns into one single column
## As suggested in https://class.coursera.org/exdata-034/forum/thread?thread_id=17
library(lubridate)
myNewData$DateFormat<-dmy_hms(paste(myNewData$Date, myNewData$Time))
## Reformat the numeric columns needed for all the plots
## in the analysis
myNewData$GlobalActivePower_num <-as.double(as.character(myNewData$Global_active_power))
myNewData$SubMetering1_num<-as.numeric(as.character(myNewData$Sub_metering_1))
myNewData$SubMetering2_num<-as.numeric(as.character(myNewData$Sub_metering_2))
myNewData$SubMetering3_num<-as.numeric(as.character(myNewData$Sub_metering_3))
myNewData$Voltage_num<-as.numeric(as.character(myNewData$Voltage))
myNewData$GlobalReactivePower_num<-as.numeric(as.character(myNewData$Global_reactive_power))
## Change the local to English, so the names of the days in
## the plot will be in English and not the locale of the
## current installation
## As suggested in https://class.coursera.org/exdata-034/forum/thread?thread_id=33
curr_locale <- Sys.getlocale("LC_TIME")
Sys.setlocale("LC_TIME","en_US.UTF-8")
## Generate plot in the png grahic device
png("plot3.png",width=480,height=480)
par(mar=c(4,6,4,1))
with(myNewData,plot(DateFormat,SubMetering1_num,type="l",ylab="Energy sub metering",xlab=""))
lines(myNewData$DateFormat,myNewData$SubMetering2_num,type="l",col="RED")
lines(myNewData$DateFormat,myNewData$SubMetering3_num,type="l",col="BLUE")
legend(x="topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("BLACK","RED","BLUE"),lty=c(1, 1, 1))
dev.off()
## Change the locale back to the original one
Sys.setlocale("LC_TIME",curr_locale)
}
| 22e0f372110e96b1bb4ddd5c2e5dd40d80e5a219 | [
"R"
] | 1 | R | ciforero/ExData_Plotting1 | 17f30c6e4162005586f91bcbe7ec7c8030b7553d | 282e1afcc6c30c0ef2fb1958d249060a98b85d9c |
refs/heads/main | <file_sep>SELECT * FROM people;
--1. What range of years for baseball games played does the provided database cover?
SELECT MIN(yearid), MAX(yearid)
FROM teams;
-- 1871 - 2016
/* 2. Find the name and height of the shortest player in the database.
How many games did he play in?
What is the name of the team for which he played?*/
WITH shortest_player AS (SELECT *
FROM people
ORDER BY height
LIMIT 1),
sp_total_games AS (SELECT *
FROM shortest_player
LEFT JOIN appearances
USING(playerid))
SELECT DISTINCT(name), namelast, namefirst, height, g_all as games_played, sp_total_games.yearid
FROM sp_total_games
LEFT JOIN teams
USING(teamid);
--
Select namefirst, namelast, height, MIN(appearances.g_all), teams.name
FROM people
JOIN appearances
ON people.playerid = appearances.playerid
JOIN teams
ON teams.teamid = appearances.teamid
WHERE height = 43
GROUP BY people.namefirst, people.namelast, people.height, appearances.teamid, teams.name;
---
SELECT DISTINCT teams.name, namelast, namefirst, height, appearances.g_all as games_played, appearances.yearid as year
FROM people
INNER JOIN appearances
ON people.playerid = appearances.playerid
INNER JOIN teams
ON appearances.teamid = teams.teamid
WHERE height IS NOT null
ORDER BY height, namelast
LIMIT 1;
--St. <NAME>, <NAME>, 43", 1 game play in 1951
/*3. Find all players in the database who played at Vanderbilt University.
Create a list showing each player’s first and last names as well as the total salary they earned in the major leagues.
Sort this list in descending order by the total salary earned.
Which Vanderbilt player earned the most money in the majors?*/
SELECT concat(people.namefirst,' ', people.namelast) as player, CAST(SUM(salaries.salary::numeric) as money)
FROM collegeplaying
INNER JOIN schools on collegeplaying.schoolid = schools.schoolid
INNER JOIN people on people.playerid = collegeplaying.playerid
INNER JOIN salaries on people.playerid = salaries.playerid
WHERE schoolname LIKE 'Vanderbilt%'
GROUP BY player
ORDER BY sum DESC;
--
SELECT distinct concat(p.namefirst, ' ', p.namelast) as name, sc.schoolname,
sum(sa.salary)
OVER (partition by concat(p.namefirst, ' ', p.namelast)) as total_salary
FROM (people p JOIN collegeplaying cp ON p.playerid = cp.playerid)
JOIN schools sc ON cp.schoolid = sc.schoolid
JOIN salaries sa ON p.playerid = sa.playerid
where cp.schoolid = 'vandy'
group by name, schoolname, sa.salary, sa.yearid
ORDER BY total_salary desc
--<NAME>, Vandy, 81,851,296.00
/* Question # 4
Using the fielding table, group players into three groups based on their position:
label players with position OF as "Outfield", those with position "SS", "1B", "2B", and "3B" as "Infield",
and those with position "P" or "C" as "Battery".
Determine the number of putouts made by each of these three groups in 2016.*/
SELECT
CASE WHEN pos LIKE 'OF' THEN 'Outfield'
WHEN pos LIKE 'C' THEN 'Battery'
WHEN pos LIKE 'P' THEN 'Battery'
ELSE 'Infield' END AS fielding_group,
SUM(po) AS putouts
FROM fielding
WHERE yearid = 2016
GROUP BY fielding_group;
--Battery 41424
--Infield 58394
--Outfield 29560
/*5. Find the average number of strikeouts per game by decade since 1920.
Round the numbers you report to 2 decimal places. Do the same for home runs per game.
Do you see any trends?*/
SELECT ROUND(AVG(so/g),2), yearid/10*10 as decade
FROM pitching
WHERE yearid BETWEEN '1920' AND '2016'
GROUP by decade
ORDER BY decade DESC;
SELECT ROUND(AVG(HR/g),2), yearid/10*10 as decade
FROM pitching
WHERE yearid BETWEEN '1920' AND '2016'
GROUP by decade
ORDER BY decade DESC;
--Tonya -- rework to show 2nd part of question regarding HR/g
SELECT yearid/10 * 10 AS decade,
ROUND(((SUM(so)::float/SUM(g))::numeric), 2) AS avg_so_per_game,
ROUND(((SUM(so)::float/SUM(ghome))::numeric), 2) AS avg_so_per_ghome
FROM teams
WHERE yearid >= 1920
GROUP BY decade
--reworked Tonyas to show 2nd part of question WRT HR/g
SELECT yearid/10 * 10 AS decade,
ROUND(((SUM(so)::float/SUM(g))::numeric), 2) AS avg_so_per_game,
ROUND(((SUM(hr)::float/SUM(g))::numeric), 2) AS avg_hr_per_ghome
FROM teams
WHERE yearid >= 1920
GROUP BY decade
ORDER BY decade
--dj
SELECT yearid/10*10 as decade, ROUND(AVG(HR/g), 2) as avg_HR_per_game,ROUND(AVG(so/g), 2) as avg_so_per_game
FROM teams
WHERE yearid>=1920
GROUP BY decade
ORDER BY decade
--mahesh
WITH decades as (
SELECT generate_series(1920,2010,10) as low_b,
generate_series(1929,2019,10) as high_b)
SELECT low_b as decade,
--SUM(so) as strikeouts,
--SUM(g)/2 as games, -- used last 2 lines to check that each step adds correctly
ROUND(SUM(so::numeric)/(sum(g::numeric)/2),2) as SO_per_game, -- note divide by 2, since games are played by 2 teams
ROUND(SUM(hr::numeric)/(sum(g::numeric)/2),2) as hr_per_game
FROM decades LEFT JOIN teams
ON yearid BETWEEN low_b AND high_b
GROUP BY decade
ORDER BY decade
--https://www.postgresql.org/docs/9.1/functions-math.html
-- The avg # of strikeouts increase with each decade.
-- The avg # of Home Runs shows a slight increase across the observation.
/*6. Find the player who had the most success stealing bases in 2016,
where success is measured as the percentage of stolen base attempts which are successful.
(A stolen base attempt results either in a stolen base or being caught stealing.)
Consider only players who attempted at least 20 stolen bases.*/
SELECT concat(people.namefirst,' ', people.namelast) as player, ROUND((SB::decimal/(SB+CS)::decimal)*100) as sb_success
FROM batting
INNER JOIN people on people.playerid = batting.playerid
WHERE yearid = 2016
AND (SB+CS)>20
ORDER BY sb_success DESC;
--<NAME>, 91
/* Question #7
From 1970 – 2016, what is the largest number of wins for a team that did not win the world series?
What is the smallest number of wins for a team that did win the world series?
Doing this will probably result in an unusually small number of wins for a world series champion – determine why this is the case.
Then redo your query, excluding the problem year.
How often from 1970 – 2016 was it the case that a team with the most wins also won the world series? What percentage of the time?*/
SELECT teamid, w, yearid
FROM teams
WHERE yearid BETWEEN 1970 AND 2016
AND wswin = 'N'
GROUP BY teamid, yearid, w
ORDER BY w DESC
LIMIT 1;
-- 116 wins without winning the World Series (Seattle in 2001)
SELECT teamid, w, yearid
FROM teams
WHERE yearid BETWEEN 1970 AND 2016
AND yearid != 1981
AND wswin = 'Y'
GROUP BY teamid, yearid, w
ORDER BY w
LIMIT 1;
-- There was a player's strike in 1981 that shortened the season.
-- The 2006 season had 83 wins for World Series Winner (St Louis).
SELECT yearid,
MAX(w)
FROM teams
WHERE yearid BETWEEN 1970 and 2016
AND wswin = 'Y'
GROUP BY yearid
INTERSECT
SELECT yearid,
MAX(w)
FROM teams
WHERE yearid BETWEEN 1970 and 2016
GROUP BY yearid
ORDER BY yearid;
-- The team with the highest number of wins won the world series 12 times between 1970 and 2016.
WITH ws_winners AS (SELECT yearid,
MAX(w)
FROM teams
WHERE yearid BETWEEN 1970 and 2016
AND wswin = 'Y'
GROUP BY yearid
INTERSECT
SELECT yearid,
MAX(w)
FROM teams
WHERE yearid BETWEEN 1970 and 2016
GROUP BY yearid
ORDER BY yearid)
SELECT (COUNT(ws.yearid)/COUNT(t.yearid)::float) AS percentage
FROM teams as t LEFT JOIN ws_winners AS ws ON t.yearid = ws.yearid
WHERE t.wswin IS NOT NULL
AND t.yearid BETWEEN 1970 AND 2016;
-- The team with the highest number of wins won the World Series 26% of the time between 1970 and 2016.
/*8. Using the attendance figures from the homegames table, find the teams and parks which had the
top 5 average attendance per game in 2016 (where average attendance is defined as total attendance
divided by number of games).
Only consider parks where there were at least 10 games played.
Report the park name, team name, and average attendance.
Repeat for the lowest 5 average attendance.*/
SELECT DISTINCT p.park_name, h.team,
(h.attendance/h.games) as avg_attendance, t.name
FROM homegames as h JOIN parks as p ON h.park = p.park
LEFT JOIN teams as t on h.team = t.teamid AND t.yearid = h.year
WHERE year = 2016
AND games >= 10
ORDER BY avg_attendance DESC
LIMIT 5;
/*9.Which managers have won the TSN Manager of the Year award in both the National League (NL) and the American League (AL)?
Give their full name and the teams that they were managing when they won the award.*/
--https://en.wikipedia.org/wiki/Sporting_News_Manager_of_the_Year_Award - 1936-1985 only one manager in either league was given the award
WITH winners AS (SELECT playerID
FROM awardsmanagers
WHERE awardID LIKE 'TSN Man%'
AND lgID LIKE 'AL'
INTERSECT
SELECT playerID
FROM awardsmanagers
WHERE awardID LIKE 'TSN Man%'
AND lgID LIKE 'NL')
SELECT concat(people.namefirst,' ', people.namelast) as manager, teams.name
FROM awardsmanagers
INNER JOIN winners on awardsmanagers.playerid = winners.playerid
INNER JOIN people on winners.playerid = people.playerid
INNER JOIN managers on winners.playerid = managers.playerid
INNER JOIN teams on managers.teamid = teams.teamid
GROUP BY teams.name, concat(people.namefirst,' ', people.namelast)
ORDER BY manager;
---
WITH manager_both AS (SELECT playerid, al.lgid AS al_lg, nl.lgid AS nl_lg,
al.yearid AS al_year, nl.yearid AS nl_year,
al.awardid AS al_award, nl.awardid AS nl_award
FROM awardsmanagers AS al INNER JOIN awardsmanagers AS nl
USING(playerid)
WHERE al.awardid LIKE 'TSN%'
AND nl.awardid LIKE 'TSN%'
AND al.lgid LIKE 'AL'
AND nl.lgid LIKE 'NL')
SELECT DISTINCT(people.playerid), namefirst, namelast, managers.teamid,
managers.yearid AS year, managers.lgid
FROM manager_both AS mb LEFT JOIN people USING(playerid)
LEFT JOIN salaries USING(playerid)
LEFT JOIN managers USING(playerid)
WHERE managers.yearid = al_year OR managers.yearid = nl_year;
-- mashesh
WITH mngr_list AS (SELECT playerid, awardid, COUNT(DISTINCT lgid) AS lg_count
FROM awardsmanagers
WHERE awardid = ‘TSN Manager of the Year’
AND lgid IN (‘NL’, ‘AL’)
GROUP BY playerid, awardid
HAVING COUNT(DISTINCT lgid) = 2),
mngr_full AS (SELECT playerid, awardid, lg_count, yearid, lgid
FROM mngr_list INNER JOIN awardsmanagers USING(playerid, awardid))
SELECT namegiven, namelast, name AS team_name
FROM mngr_full INNER JOIN people USING(playerid)
INNER JOIN managers USING(playerid, yearid, lgid)
INNER JOIN teams ON mngr_full.yearid = teams.yearid AND mngr_full.lgid = teams.lgid AND managers.teamid = teams.teamid
GROUP BY namegiven, namelast, name;
--Marlins, Pirates, Nationals & Orioles
/*10. Analyze all the colleges in the state of Tennessee.
Which college has had the most success in the major leagues.
Use whatever metric for success you like - number of players, number of games,
salaries, world series wins, etc.*/
/*11. Is there any correlation between number of wins and team salary?
Use data from 2000 and later to answer this question.
As you do this analysis, keep in mind that salaries across the whole league
tend to increase together, so you may want to look on a year-by-year basis.*/
WITH corr_wins_salary AS (SELECT SUM(salaries.salary), SUM(w) as wins, teams
FROM teams
INNER JOIN salaries USING(teamid)
WHERE teams.yearid >= 2000
GROUP BY teams)
SELECT CORR(sum,wins)
FROM corr_wins_salary;
--0.6592409969492645 (a positive relationship)
/*12. In this question, you will explore the connection between number of wins and attendance.
i. Does there appear to be any correlation between attendance at home games and number of wins?
ii. Do teams that win the world series see a boost in attendance the following year? What about
teams that made the playoffs? Making the playoffs means either being a division winner or a wild
card winner.*/
--mahesh opend ended questions:
-- Open-ended questions
-- 10. Analyze all the colleges in the state of Tennessee.
-- Which college has had the most success in the major leagues.
-- Use whatever metric for success you like - number of players, number of games, salaries, world series wins, etc.
WITH tn_schools AS (SELECT schoolname, schoolid
FROM schools
WHERE schoolstate = 'TN'
GROUP BY schoolname, schoolid)
SELECT schoolname, COUNT(DISTINCT playerid) AS player_count, SUM(salary)::text::money AS total_salary, (SUM(salary)/COUNT(DISTINCT playerid))::text::money AS money_per_player
FROM tn_schools INNER JOIN collegeplaying USING(schoolid)
INNER JOIN people USING(playerid)
INNER JOIN salaries USING(playerid)
GROUP BY schoolname
ORDER BY money_per_player DESC;
--11. Is there any correlation between number of wins and team salary?
-- Use data from 2000 and later to answer this question.
-- As you do this analysis, keep in mind that salaries across the whole league tend to increase together, so you may want to look on a year-by-year basis.
WITH team_year_sal_w AS (SELECT teamid, yearid, SUM(salary) AS total_team_sal, AVG(w)::integer AS w
FROM salaries INNER JOIN teams USING(yearid, teamid)
WHERE yearid >= 2000
GROUP BY yearid, teamid)
SELECT yearid, CORR(total_team_sal, w) AS sal_win_corr
FROM team_year_sal_w
GROUP BY yearid
ORDER BY yearid;
-- 12. In this question, you will explore the connection between number of wins and attendance.
-- Does there appear to be any correlation between attendance at home games and number of wins?
-- Do teams that win the world series see a boost in attendance the following year?
-- What about teams that made the playoffs?
-- Making the playoffs means either being a division winner or a wild card winner.
SELECT CORR(homegames.attendance, w) AS corr_attend_w --COUNT(DISTINCT playerid)
FROM teams INNER JOIN homegames ON teamid = team AND yearid = year
WHERE homegames.attendance IS NOT NULL
SELECT AVG(hg_2.attendance - hg_1.attendance) AS avg_attend_inc, stddev_pop(hg_2.attendance - hg_1.attendance) AS stdev_attend_inc
--DISTINCT name, yearid, hg_1.attendance, hg_2.year, hg_2.attendance, hg_2.attendance - hg_1.attendance AS attend_inc
FROM teams INNER JOIN homegames AS hg_1 ON teams.yearid = hg_1.year AND teams.teamid = hg_1.team
INNER JOIN homegames AS hg_2 ON teams.yearid + 1 = hg_2.year AND teams.teamid = hg_2.team
WHERE wswin = 'Y'
AND hg_1.attendance > 0
AND hg_2.attendance > 0;
SELECT AVG(hg_2.attendance - hg_1.attendance) AS avg_attend_inc, stddev_pop(hg_2.attendance - hg_1.attendance) AS stdev_attend_inc
--DISTINCT name, yearid, hg_1.attendance, hg_2.year, hg_2.attendance, hg_2.attendance - hg_1.attendance AS attend_inc
FROM teams INNER JOIN homegames AS hg_1 ON teams.yearid = hg_1.year AND teams.teamid = hg_1.team
INNER JOIN homegames AS hg_2 ON teams.yearid + 1 = hg_2.year AND teams.teamid = hg_2.team
WHERE (divwin = 'Y' OR wcwin = 'Y')
AND hg_1.attendance > 0
AND hg_2.attendance > 0;
-- 13. It is thought that since left-handed pitchers are more rare, causing batters to face them less often, that they are more effective.
-- Investigate this claim and present evidence to either support or dispute this claim.
-- First, determine just how rare left-handed pitchers are compared with right-handed pitchers.
-- Are left-handed pitchers more likely to win the Cy Young Award?
-- Are they more likely to make it into the hall of fame?
SELECT *
FROM halloffame
WITH pitchers AS (SELECT *
FROM people INNER JOIN pitching USING(playerid)
INNER JOIN awardsplayers USING(playerid)
INNER JOIN halloffame USING(playerid))
SELECT (SELECT COUNT(DISTINCT playerid)::float FROM pitchers WHERE throws = 'L')/COUNT(DISTINCT playerid)::float AS pct_left_pitch,
(SELECT COUNT(DISTINCT playerid)::float FROM pitchers WHERE awardid = 'Cy Young Award')/COUNT(DISTINCT playerid)::float AS pct_cy_young,
((SELECT COUNT(DISTINCT playerid)::float FROM pitchers WHERE awardid = 'Cy Young Award')/COUNT(DISTINCT playerid)::float) * ((SELECT COUNT(DISTINCT playerid)::float FROM pitchers WHERE throws = 'L')/COUNT(DISTINCT playerid)::float) AS calc_pct_left_cy_young,
(SELECT COUNT(DISTINCT playerid)::float FROM pitchers WHERE awardid = 'Cy Young Award' AND throws = 'L')/COUNT(DISTINCT playerid)::float AS actual_pct_left_cy_young,
(SELECT COUNT(DISTINCT playerid)::float FROM pitchers WHERE inducted = 'Y')/COUNT(DISTINCT playerid)::float AS pct_hof,
((SELECT COUNT(DISTINCT playerid)::float FROM pitchers WHERE inducted = 'Y')/COUNT(DISTINCT playerid)::float) * ((SELECT COUNT(DISTINCT playerid)::float FROM pitchers WHERE throws = 'L')/COUNT(DISTINCT playerid)::float) AS calc_pct_left_hof,
(SELECT COUNT(DISTINCT playerid)::float FROM pitchers WHERE inducted = 'Y' AND throws = 'L')/COUNT(DISTINCT playerid)::float AS actual_pct_left_hof
FROM pitchers;
Collapse
| 9c1e2a41135bc4e057602bb25222aefd27863edb | [
"SQL"
] | 1 | SQL | dcbgit/baseball-sql | bcd90cbc80ba41ac4f3ee80279af9313ac24dcda | e485ac04908242c50c0c1abdd0adb8d12ff6edf0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.