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>/*eslint no-undef:0 */
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Web3 from 'web3';
import Contract from 'truffle-contract';
import Contact from './Contact.json'
import PhoneBook from './PhoneBook.json'
if(typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider)
}
class App extends Component {
constructor(props) {
super(props)
this.state = {
init: false,
name: ""
}
}
componentDidMount() {
this.PhoneBook = new Contract(PhoneBook)
this.Contact = new Contract(Contact)
this.PhoneBook.setProvider(web3.currentProvider)
this.Contact.setProvider(web3.currentProvider)
web3.eth.getAccounts().then(accounts => {
this.PhoneBook.web3.eth.defaultAccount = accounts[0]
this.Contact.web3.eth.defaultAccount = accounts[0]
})
}
newPhoneBook = async (name) => {
this.currentBook = await this.PhoneBook.new(name)
await this.loadPhoneBook()
this.setState({init:true})
}
loadPhoneBook = async() => {
this.phonebook = {}
this.phonebook.name = await this.currentBook.getName()
this.phonebook.addresses = await this.currentBook.getContacts()
this.phonebook.contacts = []
let promises = []
this.phonebook.addresses.forEach(async address => {
let a = this.loadContact(address)
promises.push(a)
this.phonebook.contacts.push(await a)
})
await Promise.all(promises)
this.setState({phonebook: this.phonebook});
}
loadContact = async(address) => {
let contract = this.Contact.at(address)
let contact = {}
contact.fName = await contract.getFName()
contact.lName = await contract.getLName()
contact.number = await contract.getNumber()
console.log(contact);
return contact
}
addContact = async(fName, lName, number) => {
let lastLength = this.phonebook.addresses.length;
await this.currentBook.addContact(fName, lName, number)
await this.loadPhoneBook()
while (this.phonebook.addresses.length === lastLength) {
await this.loadPhoneBook();
}
}
render() {
if(!this.state.init) {
return(
<AddPhoneBook addBook={this.newPhoneBook}/>
)
}
return (
<div className="App">
<h1>{this.phonebook.name}</h1>
<Contacts phonebook={this.state.phonebook.contacts}/>
<NewContact addContact={this.addContact}/>
</div>
);
}
}
let Contacts = ({phonebook}) => {
console.log(phonebook);
return(
<ul>
{phonebook.map(contact => <li key={contact.fName}>{contact.lName} {contact.fName} {contact.number}</li>)}
</ul>
)
}
class NewContact extends Component {
constructor(props) {
super(props)
this.state = {
fName: "",
lName:"",
number:""
}
}
setFirst = (event) => {
this.setState({fName:event.target.value})
}
setLast = (event) => {
this.setState({lName:event.target.value})
}
setNumber = (event) => {
this.setState({number:event.target.value})
}
submit = (event) => {
event.preventDefault()
this.props.addContact(this.state.fName, this.state.lName, this.state.number)
}
render() {
return(
<form onSubmit={this.submit}>
Etunimi: <input type="text" onChange={this.setFirst}/>
Sukunimi: <input type="text" onChange={this.setLast}/>
Numero: <input type="text" onChange={this.setNumber}/>
<input type="submit"/>
</form>
)
}
}
class AddPhoneBook extends Component {
constructor(props) {
super(props)
this.state = {
name: ""
}
}
setName = (event) => {
this.setState({name:event.target.value})
}
submit = (event) => {
event.preventDefault()
this.props.addBook(this.state.name)
}
render() {
return(
<form onSubmit={this.submit}>
<NAME>: <input type="text" onChange={this.setName} value={this.state.name}/>
<input type="submit" value="Ok"/>
</form>
)
}
}
export default App;
| 68eff4db0d19b5b0414af734c3b4f5d5167f18ce | [
"JavaScript"
] | 1 | JavaScript | AaeeL/Phonebook | e348e72e1a38977748c68b984214c92d3b03204c | 7eee04863a34120a2f16382a23db15812c23d43d |
refs/heads/master | <repo_name>kidGodzilla/webhook-cms<file_sep>/tasks/push-production.js
module.exports = function(grunt) {
var wrench = require('wrench');
var cloudStorage = require('../libs/cloudStorage.js');
var fs = require('fs');
var async = require('async');
var request = require('request');
var productionBucket = 'cms.webhook.com';
var productionVersion = 'v2';
var distDir = 'dist/assets/';
grunt.registerTask('push-prod', function() {
var done = this.async();
var files = wrench.readdirSyncRecursive(distDir);
var uploadFunctions = [];
files.forEach(function(file) {
var source = distDir + file;
if(!fs.lstatSync(source).isDirectory())
{
// fix source map
if(file.indexOf('.min.js.map') !== -1) {
var contents = JSON.parse(fs.readFileSync(source).toString());
var newSources = [];
contents.sources.forEach(function(src) {
var parts = src.split('/');
var newSource = parts[parts.length - 1];
newSources.push(newSource);
});
contents.sources = newSources;
fs.writeFileSync(source, JSON.stringify(contents));
}
if(file.indexOf('.vendor.min.js') !== -1) {
uploadFunctions.push(function(step) {
grunt.log.success('uploading ' + source);
cloudStorage.objects.upload(productionBucket, source, productionVersion + '/assets/vendor.min.js', function() {
step();
});
});
} else if (file.indexOf('.app.min.css') !== -1) {
uploadFunctions.push(function(step) {
grunt.log.success('uploading ' + source);
cloudStorage.objects.upload(productionBucket, source, productionVersion + '/assets/app.min.css', function() {
step();
});
});
} else {
uploadFunctions.push(function(step) {
grunt.log.success('uploading ' + source);
cloudStorage.objects.upload(productionBucket, source, productionVersion + '/assets/' + file, function() {
step();
});
});
}
}
});
async.series(uploadFunctions, function() {
grunt.log.success('Done');
request.post('https://api.hipchat.com/v1/rooms/message',
{
form: {
auth_token: '<PASSWORD>',
room_id: 'webhook',
from: 'WH-Notifier',
message: 'A new version of the CMS has been deployed. (' + productionVersion + ')',
color: 'green'
}
}, function(err ,data, body) {
done();
}
);
});
});
};
<file_sep>/app/views/fluidbox.js
export default Ember.View.extend({
tagName: 'a',
attributeBindings: ['href'],
href: function () {
return this.get('image.resize_url') + '=s' + Math.max($(window).height(), $(window).width());
}.property(),
didInsertElement: function () {
this.$().fluidbox({
stackIndex: 301
});
}
});
| 36e972dfb2e22001cdd6ab418648825549105fd5 | [
"JavaScript"
] | 2 | JavaScript | kidGodzilla/webhook-cms | 21e89eee6267f1764a989aae84bad3379995b66e | bc91f5fc2ff717f01b0fae0869caaca030678704 |
refs/heads/master | <repo_name>maryroseblim/AmazonAutomation<file_sep>/Cucumber-Tutorial/src/main/java/com/vikas/fw/TestRunnerwithTestNG.java
package com.vikas.fw;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
@CucumberOptions(features="classpath:Amazon.feature", glue="stefdefinition")
public class TestRunnerwithTestNG extends AbstractTestNGCucumberTests{
}
<file_sep>/Cucumber-Tutorial/src/test/java/stefdefinition/SortItem.java
package stefdefinition;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class SortItem {
By searchBox = By.id("twotabsearchtextbox");
By searchBtn = By.className("nav-input");
By CPdept =By.linkText("Cell Phones");
By lowPrice = By.id("low-price");
By highPrice = By.id("high-price");
By priceBtn = By.xpath("(//input[@type='submit'])[2]");
By Result = By.xpath("//span[@class='a-price-whole']");
By nameResult = By.xpath("//span[@cel_widget_id='SEARCH_RESULTS-SEARCH_RESULTS']//h2//span");
WebDriver driver;
// For Amazon Feature
@Given("^Open URl \"([^\"]*)\"$")
public void open_URl(String URL) throws Throwable {
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(URL);
}
@When("^user search for \"([^\"]*)\"$")
public void user_search_for(String Item) throws Throwable {
driver.findElement(searchBox).sendKeys(Item);
driver.findElement(searchBtn).click();
}
@When("^Refine the results to show only items under the Cell Phones department$")
public void refine_the_results_to_show_only_items_under_the_Cell_Phones_department() throws Throwable {
driver.findElement(CPdept).click();
}
@When("^Refine results to show only items ranging from \"([^\"]*)\" to \"([^\"]*)\"$")
public void refine_results_to_show_only_items_ranging_from_to(String lowprice, String highprice) throws Throwable {
driver.findElement(lowPrice).sendKeys(lowprice);
driver.findElement(highPrice).sendKeys(highprice);
driver.findElement(priceBtn).click();
}
@Then("^Take the first (\\d+) results then sort their prices by highest to lowest in Java, without using Sort by Price feature on Amazon's website\\.$")
public void take_the_first_results_then_sort_their_prices_by_highest_to_lowest_in_Java_without_using_Sort_by_Price_feature_on_Amazon_s_website(int arg1) throws Throwable {
System.out.println("sort item");
List<WebElement> pResult = driver.findElements(Result);
ArrayList<String> priceList = new ArrayList<String>();
System.out.println("price: " + pResult.size());
for (WebElement result : pResult) {
priceList.add(result.getText());
System.out.println(result.getText());
}
Collections.sort(priceList.subList(0, 5));
System.out.println(priceList.subList(0, 5));
}
@Then("^Print all the product names after sorting\\.$")
public void print_all_the_product_names_after_sorting() throws Throwable {
System.out.println("print item");
List<WebElement> nResult = driver.findElements(nameResult);
System.out.println("name: " + nResult.size());
ArrayList<String> nameList = new ArrayList<String>();
for (WebElement result : nResult) {
nameList.add(result.getText());
System.out.println(result.getText());
}
}
}
| 61b990b3ff529956458333d28d1a22c3e83159d7 | [
"Java"
] | 2 | Java | maryroseblim/AmazonAutomation | 30752d2bfefce874f9ec004dcf7ecaccb029e654 | 3b0102a34aa5dcf61958b9d6c1638452b923960f |
refs/heads/master | <file_sep>package wendy
import (
"encoding/json"
"errors"
"io"
"log"
"net"
"os"
"strconv"
"strings"
"time"
)
// Cluster holds the information about the state of the network. It is the main interface to the distributed network of Nodes.
type Cluster struct {
self *Node
table *routingTable
leafset *leafSet
kill chan bool
lastStateUpdate time.Time
applications []Application
log *log.Logger
logLevel int
heartbeatFrequency int
networkTimeout int
credentials Credentials
}
// ID returns an identifier for the Cluster. It uses the ID of the current Node.
func (c *Cluster) ID() NodeID {
return c.self.ID
}
// String returns a string representation of the Cluster, in the form of its ID.
func (c *Cluster) String() string {
return c.ID().String()
}
// SetLogger sets the log.Logger that the Cluster, along with its child routingTable and leafSet, will write to.
func (c *Cluster) SetLogger(l *log.Logger) {
c.log = l
c.table.log = l
c.leafset.log = l
}
// SetLogLevel sets the level of logging that will be written to the Logger. It will be mirrored to the child routingTable and leafSet.
//
// Use wendy.LogLevelDebug to write to the most verbose level of logging, helpful for debugging.
//
// Use wendy.LogLevelWarn (the default) to write on events that may, but do not necessarily, indicate an error.
//
// Use wendy.LogLevelError to write only when an event occurs that is undoubtedly an error.
func (c *Cluster) SetLogLevel(level int) {
c.logLevel = level
c.table.logLevel = level
c.leafset.logLevel = level
}
// SetHeartbeatFrequency sets the frequency in seconds with which heartbeats will be sent from this Node to test the health of other Nodes in the Cluster.
func (c *Cluster) SetHeartbeatFrequency(freq int) {
c.heartbeatFrequency = freq
}
// SetNetworkTimeout sets the number of seconds before which network requests will be considered timed out and killed.
func (c *Cluster) SetNetworkTimeout(timeout int) {
c.networkTimeout = timeout
}
// SetChannelTimeouts sets the number of seconds before which channel requests will be considered timed out and return an error for the Cluster's leafSet and routingTable.
func (c *Cluster) SetChannelTimeouts(timeout int) {
c.table.timeout = timeout
c.leafset.timeout = timeout
}
// NewCluster creates a new instance of a connection to the network and intialises the state tables and channels it requires.
func NewCluster(self *Node, credentials Credentials) *Cluster {
return &Cluster{
self: self,
table: newRoutingTable(self),
leafset: newLeafSet(self),
kill: make(chan bool),
lastStateUpdate: time.Now(),
applications: []Application{},
log: log.New(os.Stdout, "wendy("+self.ID.String()+") ", log.LstdFlags),
logLevel: LogLevelWarn,
heartbeatFrequency: 300,
networkTimeout: 10,
credentials: credentials,
}
}
// Stop gracefully shuts down the local connection to the Cluster, removing the local Node from the Cluster and preventing it from receiving or sending further messages.
//
// Before it disconnects the Node, Stop contacts every Node it knows of to warn them of its departure. If a graceful disconnect is not necessary, Kill should be used instead. Nodes will remove the Node from their state tables next time they attempt to contact it.
func (c *Cluster) Stop() {
c.debug("Sending graceful exit message.")
msg := c.NewMessage(NODE_EXIT, c.self.ID, []byte{})
nodes, err := c.table.export()
if err != nil {
c.fanOutError(err)
}
for _, node := range nodes {
err = c.send(msg, node)
if err != nil {
c.fanOutError(err)
}
}
c.Kill()
}
// Kill shuts down the local connection to the Cluster, removing the local Node from the Cluster and preventing it from receiving or sending further messages.
//
// Unlike Stop, Kill immediately disconnects the Node without sending a message to let other Nodes know of its exit.
func (c *Cluster) Kill() {
c.debug("Exiting the cluster.")
c.table.stop()
c.leafset.stop()
c.kill <- true
}
// RegisterCallback allows anything that fulfills the Application interface to be hooked into the Wendy's callbacks.
func (c *Cluster) RegisterCallback(app Application) {
c.applications = append(c.applications, app)
}
// Listen starts the Cluster listening for events, including all the individual listeners for each state sub-object.
//
// Note that Listen does *not* join a Node to the Cluster. The Node must announce its presence before the Node is considered active in the Cluster.
func (c *Cluster) Listen() error {
portstr := strconv.Itoa(c.self.Port)
c.debug("Listening on port %d", c.self.Port)
go c.table.listen()
go c.leafset.listen()
ln, err := net.Listen("tcp", ":"+portstr)
if err != nil {
c.table.stop()
c.leafset.stop()
return err
}
defer ln.Close()
// save bound port back to Node in case where port is autoconfigured by OS
if c.self.Port == 0 {
addr_info := strings.Split(ln.Addr().String(), ":")
port, err := strconv.ParseInt(addr_info[len(addr_info)-1], 10, 32)
if err != nil {
c.log.Println("Couldn't record autoconfigured port:", err)
}
c.self.Port = int(port)
}
connections := make(chan net.Conn)
go func(ln net.Listener, ch chan net.Conn) {
for {
conn, err := ln.Accept()
if err != nil {
c.fanOutError(err)
return
}
c.debug("Connection received.")
ch <- conn
}
}(ln, connections)
for {
select {
case <-c.kill:
return nil
case <-time.After(time.Duration(c.heartbeatFrequency) * time.Second):
c.debug("Sending heartbeats.")
go c.sendHeartbeats()
break
case conn := <-connections:
c.debug("Handling connection.")
c.handleClient(conn)
break
}
}
return nil
}
// Send routes a message through the Cluster.
func (c *Cluster) Send(msg Message) error {
c.debug("Getting target for message %s", msg.Key)
target, err := c.Route(msg.Key)
if err != nil {
return err
}
if target == nil {
c.debug("Couldn't find a target. Delivering message %s", msg.Key)
c.deliver(msg)
return nil
}
forward := true
for _, app := range c.applications {
f := app.OnForward(&msg, target.ID)
if forward {
forward = f
}
}
if forward {
err = c.send(msg, target)
if err == deadNodeError {
c.remove(target.ID)
}
}
c.debug("Message %s wasn't forwarded because callback terminated it.", msg.Key)
return nil
}
// Route checks the leafSet and routingTable to see if there's an appropriate match for the NodeID. If there is a better match than the current Node, a pointer to that Node is returned. Otherwise, nil is returned (and the message should be delivered).
func (c *Cluster) Route(key NodeID) (*Node, error) {
target, err := c.leafset.route(key)
if err != nil {
if _, ok := err.(IdentityError); ok {
c.debug("I'm the target. Delivering message %s", key)
return nil, nil
}
if err != nodeNotFoundError {
return nil, err
}
if target != nil {
c.debug("Target acquired in leafset.")
return target, nil
}
}
c.debug("Target not found in leaf set, checking routing table.")
target, err = c.table.route(key)
if err != nil {
if _, ok := err.(IdentityError); ok {
c.debug("I'm the target. Delivering message %s", key)
return nil, nil
}
if err != nodeNotFoundError {
return nil, err
}
}
if target != nil {
c.debug("Target acquired in routing table.")
return target, nil
}
return nil, nil
}
// Join announces a Node's presence to the Cluster, kicking off a process that will populate its child leafSet and routingTable. Once that process is complete, the Node can be said to be fully participating in the Cluster.
//
// The IP and port passed to Join should be those of a known Node in the Cluster. The algorithm assumes that the known Node is close in proximity to the current Node, but that is not a hard requirement.
func (c *Cluster) Join(ip string, port int) error {
credentials := c.credentials.Marshal()
c.debug("Sending join message to %s:%d", ip, port)
msg := c.NewMessage(NODE_JOIN, c.self.ID, credentials)
address := ip + ":" + strconv.Itoa(port)
return c.sendToIP(msg, address)
}
func (c *Cluster) fanOutError(err error) {
c.err(err.Error())
for _, app := range c.applications {
app.OnError(err)
}
}
func (c *Cluster) sendHeartbeats() {
msg := c.NewMessage(HEARTBEAT, c.self.ID, []byte{})
nodes, err := c.table.export()
if err != nil {
c.fanOutError(err)
}
for _, node := range nodes {
c.debug("Sending heartbeat to %s", node.ID)
err = c.send(msg, node)
if err == deadNodeError {
c.remove(node.ID)
continue
}
}
}
func (c *Cluster) deliver(msg Message) {
if msg.Purpose == NODE_JOIN || msg.Purpose == NODE_EXIT || msg.Purpose == HEARTBEAT || msg.Purpose == STAT_DATA || msg.Purpose == STAT_REQ || msg.Purpose == NODE_RACE || msg.Purpose == NODE_REPR {
c.warn("Received utility message %s to the deliver function. Purpose was %d.", msg.Key, msg.Purpose)
return
}
for _, app := range c.applications {
app.OnDeliver(msg)
}
}
func (c *Cluster) handleClient(conn net.Conn) {
defer conn.Close()
var msg Message
decoder := json.NewDecoder(conn)
err := decoder.Decode(&msg)
if err != nil {
c.fanOutError(err)
return
}
valid := c.credentials == nil
if !valid {
valid = c.credentials.Valid(msg.Credentials)
}
if !valid {
c.warn("Credentials did not match. Supplied credentials: %s", msg.Credentials)
return
}
if msg.Purpose != NODE_JOIN {
node, err := c.table.getNode(msg.Sender.ID)
if err == nodeNotFoundError {
_, node = c.insert(msg.Sender)
}
if node != nil {
node.updateLastHeardFrom()
node.setProximity(time.Since(msg.Sent).Nanoseconds())
}
}
conn.Write([]byte(`{"status": "Received."}`))
c.debug("Got message with purpose %v", msg.Purpose)
switch msg.Purpose {
case NODE_JOIN:
c.onNodeJoin(msg)
break
case NODE_EXIT:
c.onNodeExit(msg.Sender)
break
case HEARTBEAT:
for _, app := range c.applications {
app.OnHeartbeat(msg.Sender)
}
break
case STAT_DATA:
c.onStateReceived(msg)
break
case STAT_REQ:
c.onStateRequested(msg.Sender)
break
case NODE_RACE:
c.onRaceCondition(msg.Sender)
break
case NODE_REPR:
c.onRepairRequest(msg.Sender)
break
default:
c.onMessageReceived(msg)
}
}
func (c *Cluster) send(msg Message, destination *Node) error {
if c.self == nil || destination == nil {
return errors.New("Can't send to or from a nil node.")
}
var address string
if destination.Region == c.self.Region {
address = destination.LocalIP + ":" + strconv.Itoa(destination.Port)
} else {
address = destination.GlobalIP + ":" + strconv.Itoa(destination.Port)
}
c.debug("Sending message %s to %s", msg.Key, address)
err := c.sendToIP(msg, address)
if err == nil {
destination.updateLastHeardFrom()
}
return err
}
func (c *Cluster) sendToIP(msg Message, address string) error {
c.debug("Sending message %s", string(msg.Value))
conn, err := net.DialTimeout("tcp", address, time.Duration(c.networkTimeout)*time.Second)
if err != nil {
c.debug(err.Error())
return deadNodeError
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(time.Duration(c.networkTimeout) * time.Second))
encoder := json.NewEncoder(conn)
err = encoder.Encode(msg)
if err != nil {
return err
}
c.debug("Sent message %s to %s", msg.Key, address)
_, err = conn.Read(nil)
if err != nil {
if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
return deadNodeError
}
if err == io.EOF {
err = nil
}
}
return err
}
// Our message handlers!
func (c *Cluster) onNodeJoin(msg Message) {
c.debug("\033[4;31mNode %s joined!\033[0m", msg.Key)
err := c.Send(msg)
if err != nil {
c.fanOutError(err)
}
c.insert(msg.Sender)
err = c.sendStateTables(msg.Sender, true, true)
if err != nil {
if err == deadNodeError {
c.remove(msg.Sender.ID)
} else {
c.fanOutError(err)
}
}
}
func (c *Cluster) onNodeExit(node Node) {
c.debug("Node %s left. :(", node.ID)
c.remove(node.ID)
}
// BUG(<EMAIL>): If the Nodes don't agree on the time, Wendy can create an infinite loop of sending state information, detecting an erroneous race condition, and requesting state information. For the love of God, use NTP.
func (c *Cluster) onStateReceived(msg Message) {
c.debug("Got state information!")
if c.lastStateUpdate.After(msg.Sent) {
c.warn("Detected race condition. %s sent the message at %s, but we last updated our state tables at %s. Notifying %s.", msg.Sender.ID, msg.Sent, c.lastStateUpdate, msg.Sender.ID)
message := c.NewMessage(NODE_RACE, msg.Sender.ID, []byte{})
target, err := c.table.getNode(msg.Sender.ID)
if err != nil {
if err == nodeNotFoundError {
target, _ = c.insert(msg.Sender)
} else if _, ok := err.(IdentityError); ok {
c.warn("Apparently received state information from myself...?")
return
} else {
c.fanOutError(err)
}
}
if target != nil {
err = c.send(message, target)
if err != nil {
c.fanOutError(err)
}
} else {
c.warn("Node ended up being nil (probably due to errors) when trying to respond to a race condition message.")
}
return
}
var state []Node
err := json.Unmarshal(msg.Value, &state)
if err != nil {
c.fanOutError(err)
return
}
for _, node := range state {
c.debug("Inserting %s", node.ID)
c.insert(node)
}
c.debug("Inserting %s", msg.Sender.ID)
c.insert(msg.Sender)
}
func (c *Cluster) onStateRequested(node Node) {
c.debug("%s wants to know about my state tables!", node.ID)
c.sendStateTables(node, true, true)
}
func (c *Cluster) onRaceCondition(node Node) {
c.debug("Race condition. Awkward.")
c.sendStateTables(node, true, true)
}
func (c *Cluster) onRepairRequest(node Node) {
c.debug("Helping to repair %s", node.ID)
c.sendStateTables(node, false, true)
}
func (c *Cluster) onMessageReceived(msg Message) {
c.debug("Received message %s", msg.Key)
err := c.Send(msg)
if err != nil {
c.fanOutError(err)
}
c.insert(msg.Sender)
}
func (c *Cluster) sendStateTables(node Node, table, leafset bool) error {
var state []*Node
if table {
dump, err := c.table.export()
if err != nil {
return err
}
state = append(state, dump...)
}
if leafset {
dump, err := c.table.export()
if err != nil {
return err
}
state = append(state, dump...)
}
data, err := json.Marshal(state)
if err != nil {
return err
}
msg := c.NewMessage(STAT_DATA, c.self.ID, data)
target, err := c.table.getNode(node.ID)
if err != nil {
if err == nodeNotFoundError {
c.insert(node)
} else if _, ok := err.(IdentityError); !ok {
return err
}
}
c.debug("Sending state tables to %s", node.ID)
return c.send(msg, target)
}
func (c *Cluster) insert(node Node) (leafset, rt *Node) {
resp, err := c.table.insertNode(node)
if err != nil {
if _, ok := err.(IdentityError); !ok {
c.fanOutError(err)
}
}
if resp != nil {
c.debug("Inserted node %s into the routing table.", node.ID)
}
c.debug("Trying to insert %s into the leaf set.", node.ID)
resp2, err := c.leafset.insertNode(node)
if err != nil {
if _, ok := err.(IdentityError); !ok {
c.fanOutError(err)
}
}
c.debug("Finished trying to insert %s into the leaf set.", node.ID)
if resp2 != nil {
c.debug("Inserted node %s into the leaf set.", node.ID)
leaves, err := c.leafset.export()
if err != nil {
c.fanOutError(err)
}
for _, app := range c.applications {
app.OnNewLeaves(leaves)
}
}
if resp != nil || resp2 != nil {
for _, app := range c.applications {
app.OnNodeJoin(node)
}
}
c.lastStateUpdate = time.Now()
return resp, resp2
}
// BUG(<EMAIL>): If we happen to remove one of our two neighbours in the leaf set, we will wind up with a hole in the leaf set until we next get a state update. The only fix for this that I can think of involves retrieving results by position from the leaf set, and I'm not eager to complicate things with that if I can avoid it.
func (c *Cluster) remove(id NodeID) {
resp, err := c.table.removeNode(id)
if err != nil && err != nodeNotFoundError {
if _, ok := err.(IdentityError); !ok {
c.fanOutError(err)
}
}
resp2, err := c.leafset.removeNode(id)
if err != nil && err != nodeNotFoundError {
if _, ok := err.(IdentityError); !ok {
c.fanOutError(err)
}
}
if resp2 != nil {
leaves, err := c.leafset.export()
if err != nil {
c.fanOutError(err)
}
for _, app := range c.applications {
app.OnNewLeaves(leaves)
}
msg := c.NewMessage(NODE_REPR, resp2.ID, []byte{})
err = c.Send(msg)
if err != nil {
c.fanOutError(err)
}
}
if resp != nil {
for _, app := range c.applications {
app.OnNodeExit(*resp)
}
} else if resp2 != nil {
for _, app := range c.applications {
app.OnNodeExit(*resp2)
}
}
c.lastStateUpdate = time.Now()
}
func (c *Cluster) debug(format string, v ...interface{}) {
if c.logLevel <= LogLevelDebug {
c.log.Printf(format, v...)
}
}
func (c *Cluster) warn(format string, v ...interface{}) {
if c.logLevel <= LogLevelWarn {
c.log.Printf(format, v...)
}
}
func (c *Cluster) err(format string, v ...interface{}) {
if c.logLevel <= LogLevelError {
c.log.Printf(format, v...)
}
}
<file_sep>package wendy
import (
"sync"
"time"
)
// Node represents a specific machine in the cluster.
type Node struct {
LocalIP string // The IP through which the Node should be accessed by other Nodes with an identical Region
GlobalIP string // The IP through which the Node should be accessed by other Nodes whose Region differs
Port int // The port the Node is listening on
Region string // A string that allows you to intelligently route between local and global requests for, e.g., EC2 regions
ID NodeID
proximity int64 // The raw proximity score for the Node, not adjusted for Region
mutex *sync.Mutex // lock and unlock a Node for concurrency safety
lastHeardFrom time.Time // The last time we heard from this node
}
// NewNode initialises a new Node and its associated mutexes. It does *not* update the proximity of the Node.
func NewNode(id NodeID, local, global, region string, port int) *Node {
return &Node{
ID: id,
LocalIP: local,
GlobalIP: global,
Port: port,
Region: region,
proximity: 0,
mutex: new(sync.Mutex),
lastHeardFrom: time.Now(),
}
}
// Proximity returns the proximity score for the Node, adjusted for the Region. The proximity score of a Node reflects how close it is to the current Node; a lower proximity score means a closer Node. Nodes outside the current Region are penalised by a multiplier.
func (self *Node) Proximity(n *Node) int64 {
if n == nil {
return -1
}
n.mutex.Lock()
defer n.mutex.Unlock()
multiplier := int64(1)
if n.Region != self.Region {
multiplier = 5
}
score := n.proximity * multiplier
return score
}
func (self *Node) setProximity(proximity int64) {
self.mutex.Lock()
defer self.mutex.Unlock()
self.proximity = proximity
}
func (self *Node) updateLastHeardFrom() {
self.mutex.Lock()
defer self.mutex.Unlock()
self.lastHeardFrom = time.Now()
}
func (self *Node) LastHeardFrom() time.Time {
self.mutex.Lock()
self.mutex.Unlock()
return self.lastHeardFrom
}
<file_sep>package wendy
import (
"log"
"os"
"time"
)
type routingTablePosition struct {
row int
col int
entry int
inserted bool
}
type routingTable struct {
self *Node
nodes [32][16][]*Node
kill chan bool
log *log.Logger
logLevel int
timeout int
request chan interface{}
}
func newRoutingTable(self *Node) *routingTable {
return &routingTable{
self: self,
nodes: [32][16][]*Node{},
kill: make(chan bool),
log: log.New(os.Stdout, "wendy#routingTable("+self.ID.String()+")", log.LstdFlags),
logLevel: LogLevelWarn,
timeout: 1,
request: make(chan interface{}),
}
}
func (t *routingTable) stop() {
t.kill <- true
}
func (t *routingTable) listen() {
for {
select {
case request := <-t.request:
switch r := request.(type) {
case getRequest:
if r.strict {
t.get(r.id, r.response, r.err)
} else {
t.scan(r.id, r.response, r.err)
}
break
case dumpRequest:
t.dump(r.response)
break
case insertRequest:
t.insert(r.node, r.tablePos, r.err)
break
case removeRequest:
t.remove(r.id, r.response, r.err)
break
}
break
case <-t.kill:
return
}
}
}
func (t *routingTable) insertNode(node Node) (*Node, error) {
return t.insertValues(node.ID, node.LocalIP, node.GlobalIP, node.Region, node.Port)
}
func (t *routingTable) insertValues(id NodeID, localIP, globalIP, region string, port int) (*Node, error) {
node := NewNode(id, localIP, globalIP, region, port)
pos := make(chan routingTablePosition)
err := make(chan error)
t.request <- insertRequest{
node: node,
err: err,
tablePos: pos,
}
select {
case p := <-pos:
if !p.inserted {
return nil, nil
}
return node, nil
case e := <-err:
return nil, e
case <-time.After(time.Duration(t.timeout) * time.Second):
return nil, throwTimeout("Table insertion", t.timeout)
}
panic("Should not be reached")
return nil, nil
}
func (t *routingTable) insert(node *Node, poschan chan routingTablePosition, errchan chan error) {
if node == nil {
errchan <- throwInvalidArgumentError("Can't insert a nil Node into the routing table.")
return
}
row := t.self.ID.CommonPrefixLen(node.ID)
if row >= len(t.nodes) {
errchan <- throwIdentityError("insert", "into", "routing table")
return
}
col := int(node.ID.Digit(row))
if col >= len(t.nodes[row]) {
errchan <- impossibleError
return
}
if t.nodes[row][col] == nil {
t.nodes[row][col] = []*Node{}
}
for i, n := range t.nodes[row][col] {
if node.ID.Equals(n.ID) {
t.nodes[row][col][i] = node
poschan <- routingTablePosition{
row: row,
col: col,
entry: i,
inserted: false,
}
return
}
}
t.nodes[row][col] = append(t.nodes[row][col], node)
poschan <- routingTablePosition{
row: row,
col: col,
entry: len(t.nodes[row][col]) - 1,
inserted: true,
}
return
}
func (t *routingTable) getNode(id NodeID) (*Node, error) {
resp := make(chan *Node)
err := make(chan error)
t.request <- getRequest{
id: id,
strict: true,
err: err,
response: resp,
}
select {
case node := <-resp:
return node, nil
case e := <-err:
return nil, e
case <-time.After(time.Duration(t.timeout) * time.Second):
return nil, throwTimeout("Table retrieval", t.timeout)
}
panic("Should not be reached")
return nil, nil
}
func (t *routingTable) route(key NodeID) (*Node, error) {
resp := make(chan *Node)
err := make(chan error)
t.request <- getRequest{
id: key,
strict: false,
err: err,
response: resp,
}
select {
case node := <-resp:
return node, nil
case e := <-err:
return nil, e
case <-time.After(time.Duration(t.timeout) * time.Second):
return nil, throwTimeout("Table routing", t.timeout)
}
panic("Should not be reached")
return nil, nil
}
func (t *routingTable) get(id NodeID, resp chan *Node, err chan error) {
row := t.self.ID.CommonPrefixLen(id)
if row >= idLen {
err <- throwIdentityError("get", "from", "routing table")
return
}
col := int(id.Digit(row))
if col >= len(t.nodes[row]) {
err <- impossibleError
return
}
entry := -1
for i, n := range t.nodes[row][col] {
if n.ID.Equals(id) {
entry = i
}
}
if entry < 0 {
err <- nodeNotFoundError
return
}
if entry > len(t.nodes[row][col]) {
err <- impossibleError
return
}
resp <- t.nodes[row][col][entry]
return
}
func (t *routingTable) scan(id NodeID, resp chan *Node, err chan error) {
var node *Node
row := t.self.ID.CommonPrefixLen(id)
if row >= idLen {
err <- throwIdentityError("route to", "in", "routing table")
return
}
col := int(id.Digit(row))
if col >= len(t.nodes[row]) {
err <- impossibleError
return
}
if len(t.nodes[row][col]) > 0 {
proximity := int64(-1)
for _, entry := range t.nodes[row][col] {
if proximity == -1 || t.self.Proximity(entry) < proximity {
node = entry
proximity = t.self.Proximity(entry)
}
}
if proximity > -1 {
resp <- node
return
}
}
diff := t.self.ID.Diff(id)
for scan_row := row; scan_row < len(t.nodes); scan_row++ {
for c, n := range t.nodes[scan_row] {
if c == int(t.self.ID.Digit(row)) {
continue
}
if n == nil || len(n) < 1 {
continue
}
proximity := int64(-1)
for _, entry := range n {
if entry == nil {
continue
}
if entry.LocalIP == "" && entry.GlobalIP == "" {
continue
}
entry_diff := entry.ID.Diff(id).Cmp(diff)
if entry_diff == -1 || (entry_diff == 0 && !t.self.ID.Less(entry.ID)) {
if proximity == -1 || proximity > t.self.Proximity(entry) {
node = entry
proximity = t.self.Proximity(entry)
}
}
}
if node != nil {
if proximity == -1 {
err <- nodeNotFoundError
return
}
resp <- node
return
}
}
}
err <- nodeNotFoundError
return
}
func (t *routingTable) removeNode(id NodeID) (*Node, error) {
resp := make(chan *Node)
err := make(chan error)
t.request <- removeRequest{
id: id,
err: err,
response: resp,
}
select {
case node := <-resp:
return node, nil
case e := <-err:
return nil, e
case <-time.After(time.Duration(t.timeout) * time.Second):
return nil, throwTimeout("Table removal", t.timeout)
}
panic("Should not be reached")
return nil, nil
}
func (t *routingTable) remove(id NodeID, resp chan *Node, err chan error) {
var row, col, entry int
entry = -1
row = t.self.ID.CommonPrefixLen(id)
if row >= idLen {
err <- throwIdentityError("remove", "from", "routing table")
return
}
col = int(id.Digit(row))
if col > len(t.nodes[row]) {
err <- impossibleError
}
for i, n := range t.nodes[row][col] {
if n.ID.Equals(id) {
entry = i
}
}
if entry < 0 {
err <- nodeNotFoundError
return
}
resp <- t.nodes[row][col][entry]
if len(t.nodes[row][col]) == 1 {
t.nodes[row][col] = []*Node{}
return
}
if len(t.nodes[row][col]) == entry+1 {
t.nodes[row][col] = t.nodes[row][col][:entry]
return
}
if entry == 0 {
t.nodes[row][col] = t.nodes[row][col][1:]
return
}
t.nodes[row][col] = append(t.nodes[row][col][:entry], t.nodes[row][col][entry+1:]...)
return
}
func (t *routingTable) export() ([]*Node, error) {
resp := make(chan []*Node)
err := make(chan error)
t.request <- dumpRequest{
response: resp,
}
select {
case nodes := <-resp:
return nodes, nil
case e := <-err:
return nil, e
case <-time.After(time.Duration(t.timeout) * time.Second):
return nil, throwTimeout("Table dump", t.timeout)
}
panic("Should not be reached")
return nil, nil
}
func (t *routingTable) dump(resp chan []*Node) {
nodes := []*Node{}
for _, row := range t.nodes {
for _, col := range row {
for _, entry := range col {
if entry != nil {
nodes = append(nodes, entry)
}
}
}
}
resp <- nodes
}
<file_sep>package wendy
import (
"log"
"os"
"runtime"
"time"
)
type leafSetPosition struct {
left bool
pos int
inserted bool
}
type leafSet struct {
self *Node
left [16]*Node
right [16]*Node
kill chan bool
log *log.Logger
logLevel int
timeout int
request chan interface{}
}
func newLeafSet(self *Node) *leafSet {
return &leafSet{
self: self,
left: [16]*Node{},
right: [16]*Node{},
kill: make(chan bool),
log: log.New(os.Stdout, "wendy#leafSet("+self.ID.String()+")", log.LstdFlags),
logLevel: LogLevelWarn,
timeout: 1,
request: make(chan interface{}),
}
}
func (l *leafSet) stop() {
l.kill <- true
}
func (l *leafSet) listen() {
for {
runtime.Gosched()
select {
case request, ok := <-l.request:
if !ok {
panic("Listen channel closed?")
}
switch r := request.(type) {
case getRequest:
if r.strict {
l.get(r.id, r.response, r.err)
} else {
l.scan(r.id, r.response, r.err)
}
break
case dumpRequest:
l.dump(r.response)
break
case insertRequest:
l.debug("Insert request routed.")
l.insert(r.node, r.leafPos, r.err)
break
case removeRequest:
l.remove(r.id, r.response, r.err)
break
}
break
case _, ok := <-l.kill:
if !ok {
panic("kill channel closed?")
}
return
}
}
}
func (l *leafSet) insertNode(node Node) (*Node, error) {
return l.insertValues(node.ID, node.LocalIP, node.GlobalIP, node.Region, node.Port)
}
func (l *leafSet) insertValues(id NodeID, localIP, globalIP, region string, port int) (*Node, error) {
l.debug("Insert request received.")
node := NewNode(id, localIP, globalIP, region, port)
pos := make(chan leafSetPosition)
err := make(chan error)
l.request <- insertRequest{
node: node,
err: err,
leafPos: pos,
}
l.debug("Request sent.")
select {
case p := <-pos:
l.debug("Response received.")
if !p.inserted {
return nil, nil
}
return node, nil
case e := <-err:
l.debug("Error received.")
return nil, e
case <-time.After(time.Duration(l.timeout) * time.Second):
l.debug("Timeout received.")
return nil, throwTimeout("LeafSet insertion", l.timeout)
}
panic("Should not be reached")
return nil, nil
}
func (l *leafSet) insert(node *Node, poschan chan leafSetPosition, errchan chan error) {
l.debug("Inserting...")
if node == nil {
l.debug("Node is nil. Throwing invalid argument error.")
errchan <- throwInvalidArgumentError("Can't insert a nil Node into the leaf set.")
return
}
var pos int
var inserted bool
side := l.self.ID.RelPos(node.ID)
if side == -1 {
l.debug("Node goes on the left.")
l.left, pos, inserted = node.insertIntoArray(l.left, l.self)
if pos > -1 {
l.debug("Replying to request...")
poschan <- leafSetPosition{
pos: pos,
left: true,
inserted: inserted,
}
l.debug("Replied to request.")
return
}
} else if side == 1 {
l.debug("Node goes on the right.")
l.right, pos, inserted = node.insertIntoArray(l.right, l.self)
if pos > -1 {
l.debug("Replying to request...")
poschan <- leafSetPosition{
pos: pos,
left: false,
inserted: inserted,
}
l.debug("Replied to request")
return
}
}
l.debug("Oops, tried to insert myself in my own leafset. Throwing IdentityError.")
errchan <- throwIdentityError("insert", "into", "leaf set")
return
}
func (l *leafSet) getNode(id NodeID) (*Node, error) {
resp := make(chan *Node)
err := make(chan error)
l.request <- getRequest{
id: id,
strict: true,
err: err,
response: resp,
}
select {
case node := <-resp:
return node, nil
case e := <-err:
return nil, e
case <-time.After(time.Duration(l.timeout) * time.Second):
return nil, throwTimeout("LeafSet retrieval", l.timeout)
}
panic("Should not be reached")
return nil, nil
}
func (l *leafSet) route(key NodeID) (*Node, error) {
resp := make(chan *Node)
err := make(chan error)
l.request <- getRequest{
id: key,
strict: false,
err: err,
response: resp,
}
select {
case node := <-resp:
return node, nil
case e := <-err:
return nil, e
case <-time.After(time.Duration(l.timeout) * time.Second):
return nil, throwTimeout("LeafSet routing", l.timeout)
}
panic("Should not be reached")
return nil, nil
}
func (l *leafSet) get(id NodeID, resp chan *Node, err chan error) {
side := l.self.ID.RelPos(id)
if side == -1 {
for _, node := range l.left {
if node == nil {
break
}
if id.Equals(node.ID) {
resp <- node
return
}
}
} else if side == 1 {
for _, node := range l.right {
if node == nil {
break
}
if id.Equals(node.ID) {
resp <- node
return
}
}
} else {
err <- throwIdentityError("get", "from", "leaf set")
return
}
err <- nodeNotFoundError
return
}
func (l *leafSet) scan(key NodeID, resp chan *Node, err chan error) {
defer close(resp)
defer close(err)
side := l.self.ID.RelPos(key)
best_score := l.self.ID.Diff(key)
best := l.self
biggest := l.self.ID
if side == -1 {
for _, node := range l.left {
if node == nil {
break
}
diff := key.Diff(node.ID)
if diff.Cmp(best_score) == -1 || (diff.Cmp(best_score) == 0 && node.ID.Less(best.ID)) {
best = node
best_score = diff
}
biggest = node.ID
}
} else {
for _, node := range l.right {
if node == nil {
break
}
diff := key.Diff(node.ID)
if diff.Cmp(best_score) == -1 || (diff.Cmp(best_score) == 0 && node.ID.Less(best.ID)) {
best = node
best_score = diff
}
biggest = node.ID
}
}
if biggest.Less(key) {
err <- nodeNotFoundError
return
}
if !best.ID.Equals(l.self.ID) {
resp <- best
return
} else {
err <- throwIdentityError("route to", "in", "leaf set")
return
}
err <- nodeNotFoundError
return
}
func (l *leafSet) export() ([]*Node, error) {
resp := make(chan []*Node)
err := make(chan error)
l.request <- dumpRequest{
response: resp,
}
select {
case nodes := <-resp:
return nodes, nil
case e := <-err:
return nil, e
case <-time.After(time.Duration(l.timeout) * time.Second):
return nil, throwTimeout("LeafSet dump", l.timeout)
}
panic("Should not be reached")
return nil, nil
}
func (l *leafSet) dump(resp chan []*Node) {
nodes := []*Node{}
for _, node := range l.left {
if node != nil {
nodes = append(nodes, node)
}
}
for _, node := range l.right {
if node != nil {
nodes = append(nodes, node)
}
}
resp <- nodes
}
func (node *Node) insertIntoArray(array [16]*Node, center *Node) ([16]*Node, int, bool) {
var result [16]*Node
result_index := 0
src_index := 0
pos := -1
inserted := false
for result_index < len(result) {
result[result_index] = array[src_index]
if array[src_index] == nil {
if pos < 0 {
result[result_index] = node
pos = result_index
inserted = true
}
break
}
if node.ID.Equals(array[src_index].ID) {
pos = result_index
result_index += 1
src_index += 1
continue
}
if center.ID.Diff(node.ID).Cmp(center.ID.Diff(result[result_index].ID)) < 0 && pos < 0 {
result[result_index] = node
pos = result_index
inserted = true
} else {
src_index += 1
}
result_index += 1
}
return result, pos, inserted
}
func (l *leafSet) removeNode(id NodeID) (*Node, error) {
resp := make(chan *Node)
err := make(chan error)
l.request <- removeRequest{
id: id,
err: err,
response: resp,
}
select {
case node := <-resp:
return node, nil
case e := <-err:
return nil, e
case <-time.After(time.Duration(l.timeout) * time.Second):
return nil, throwTimeout("LeafSet removal", l.timeout)
}
panic("Should not be reached")
return nil, nil
}
func (l *leafSet) remove(id NodeID, resp chan *Node, err chan error) {
side := l.self.ID.RelPos(id)
if side == 0 {
err <- throwIdentityError("remove", "from", "leaf set")
return
}
pos := -1
var n *Node
if side == -1 {
for index, node := range l.left {
if node == nil || node.ID.Equals(id) {
pos = index
n = node
break
}
}
} else {
for index, node := range l.right {
if node == nil || node.ID.Equals(id) {
pos = index
n = node
break
}
}
}
if pos == -1 || (side == -1 && pos > len(l.left)) || (side == 1 && pos > len(l.right)) {
err <- nodeNotFoundError
return
}
var slice []*Node
if side == -1 {
if len(l.left) == 1 {
slice = []*Node{}
} else if pos+1 == len(l.left) {
slice = l.left[:pos]
} else if pos == 0 {
slice = l.left[1:]
} else {
slice = append(l.left[:pos], l.left[pos+1:]...)
}
for i, _ := range l.left {
if i < len(slice) {
l.left[i] = slice[i]
} else {
l.left[i] = nil
}
}
} else {
if len(l.right) == 1 {
slice = []*Node{}
} else if pos+1 == len(l.right) {
slice = l.right[:pos]
} else if pos == 0 {
slice = l.right[1:]
} else {
slice = append(l.right[:pos], l.right[pos+1:]...)
}
for i, _ := range l.right {
if i < len(slice) {
l.right[i] = slice[i]
} else {
l.right[i] = nil
}
}
}
resp <- n
return
}
func (l *leafSet) debug(format string, v ...interface{}) {
if l.logLevel <= LogLevelDebug {
l.log.Printf(format, v...)
}
}
func (l *leafSet) warn(format string, v ...interface{}) {
if l.logLevel <= LogLevelWarn {
l.log.Printf(format, v...)
}
}
func (l *leafSet) err(format string, v ...interface{}) {
if l.logLevel <= LogLevelError {
l.log.Printf(format, v...)
}
}
<file_sep>package wendy
import (
"errors"
"fmt"
)
type reqMode int
const (
mode_set = reqMode(iota)
mode_get
mode_del
mode_prx
mode_scan
mode_dump
mode_beat // For getting the nodes that need a heartbeat
)
const (
LogLevelDebug = iota
LogLevelWarn
LogLevelError
)
// Application is an interface that other packages can fulfill to hook into Wendy.
//
// OnError is called on errors that are even remotely recoverable, passing the error that was raised.
//
// OnDeliver is called when the current Node is determined to be the final destination of a Message. It passes the Message that was received.
//
// OnForward is called immediately before a Message is forwarded to the next Node in its route through the Cluster. The function receives a pointer to the Message, which can be modified before it is sent, and the ID of the next step in the Message's route. The function must return a boolean; true if the Message should continue its way through the Cluster, false if the Message should be prematurely terminated instead of forwarded.
//
// OnNewLeaves is called when the current Node's leafSet is updated. The function receives a dump of the leafSet.
//
// OnNodeJoin is called when the current Node learns of a new Node in the Cluster. It receives the Node that just joined.
//
// OnNodeExit is called when a Node is discovered to no longer be participating in the Cluster. It is passed the Node that just left the Cluster. Note that by the time this method is called, the Node is no longer reachable.
//
// OnHeartbeat is called when the current Node receives a heartbeat from another Node. Heartbeats are sent at a configurable interval, if no messages have been sent between the Nodes, and serve the purpose of a health check.
type Application interface {
OnError(err error)
OnDeliver(msg Message)
OnForward(msg *Message, nextId NodeID) bool // return False if Wendy should not forward
OnNewLeaves(leafset []*Node)
OnNodeJoin(node Node)
OnNodeExit(node Node)
OnHeartbeat(node Node)
}
// Credentials is an interface that can be fulfilled to limit access to the Cluster.
type Credentials interface {
Valid([]byte) bool
Marshal() []byte
}
// Passphrase is an implementation of Credentials that grants access to the Cluster if the Node has the same Passphrase set
type Passphrase string
func (p Passphrase) Valid(supplied []byte) bool {
return string(supplied) == string(p)
}
func (p Passphrase) Marshal() []byte {
return []byte(p)
}
// The below types are used in ensuring concurrency safety within the state tables
type getRequest struct {
id NodeID
strict bool
err chan error
response chan *Node
}
type dumpRequest struct {
response chan []*Node
}
type removeRequest struct {
id NodeID
err chan error
response chan *Node
}
type insertRequest struct {
node *Node
err chan error
tablePos chan routingTablePosition
leafPos chan leafSetPosition
}
// Errors!
var deadNodeError = errors.New("Node did not respond to heartbeat.")
var nodeNotFoundError = errors.New("Node not found.")
var impossibleError = errors.New("This error should never be reached. It's logically impossible.")
// TimeoutError represents an error that was raised when a call has taken too long. It is its own type for the purposes of handling the error.
type TimeoutError struct {
Action string
Timeout int
}
// Error returns the TimeoutError as a string and fulfills the error interface.
func (t TimeoutError) Error() string {
return fmt.Sprintf("Timeout error: %s took more than %v seconds.", t.Action, t.Timeout)
}
// throwTimeout creates a new TimeoutError from the action and timeout specified.
func throwTimeout(action string, timeout int) TimeoutError {
return TimeoutError{
Action: action,
Timeout: timeout,
}
}
// IdentityError represents an error that was raised when a Node attempted to perform actions on its state tables using its own ID, which is problematic. It is its own type for the purposes of handling the error.
type IdentityError struct {
Action string
Preposition string
Container string
}
// Error returns the IdentityError as a string and fulfills the error interface.
func (e IdentityError) Error() string {
return fmt.Sprintf("IdentityError: Tried to %s myself %s the %s.", e.Action, e.Preposition, e.Container)
}
func throwIdentityError(action, prep, container string) IdentityError {
return IdentityError{
Action: action,
Preposition: prep,
Container: container,
}
}
// InvalidArgumentError represents an error that is raised when arguments that are invalid are passed to a function that depends on those arguments. It is its own type for the purposes of handling the error.
type InvalidArgumentError string
func (e InvalidArgumentError) Error() string {
return fmt.Sprintf("InvalidArgumentError: %s", e)
}
func throwInvalidArgumentError(msg string) InvalidArgumentError {
return InvalidArgumentError(msg)
}
| 46320769bd4efdcbdd97d73bba18bb25a6348255 | [
"Go"
] | 5 | Go | nergdron/wendy | a8222bc11d5c26e9d65f0703230ecfc6577ff6de | 74bf668752ec00e5432e2beded71c8791e37f348 |
refs/heads/main | <repo_name>adrian18lifepro/firstCITest<file_sep>/test.js
const supertest = require("supertest");
const server = supertest.agent("http://localhost:5000");
describe("Sample unit test", () => {
it("should return home page", done => {
server
.get("/")
.expect("Content-type", /text/)
.expect(200)
.end(function(err, res) {
done();
});
});
});
| 6b62d2a27c3a9cb7fdffe92b323198e8430037f1 | [
"JavaScript"
] | 1 | JavaScript | adrian18lifepro/firstCITest | 092cafd79d2a10a16cdc07000c481916a2f40910 | 1f505aca293ff32065d722e5f1ae8f3eb260541d |
refs/heads/master | <file_sep>require 'rspec'
require './lib/connection.rb'
require './spec/mock/mock_tcp_socket.rb'
describe 'IRConnect::Connection' do
before(:each) do
@connection = IRConnect::Connection.new('irc.fake.net', socket_class: MockTCPSocket)
end
it 'creates an instance of IRCConnector' do
expect(@connection.nil?).to be(false)
expect(@connection).to be_a(IRConnect::Connection)
end
describe 'nick' do
it 'sets the NICK' do
expect { @connection.nick('fakename') }.to_not raise_error
expect(@connection.socket.client_output).to eq("NICK fakename\r\n")
end
it 'raises an error when given an invalid IRC nick or < 2 characters' do
expect { @connection.nick('X') }.to raise_error(RuntimeError)
expect { @connection.nick('$$$$') }.to raise_error(RuntimeError)
end
end
describe 'user' do
it 'sets the USER' do
expect { @connection.user('nick', 'h', 's', 'bot') }.to_not raise_error
expect(@connection.socket.client_output).to eq("USER nick h s :bot\r\n")
end
end
describe 'receiving commands' do
it 'receives and parses commands' do
@connection.socket.server_responses << ':irc.fakenode.net 001 bot ' \
':Welcome to fakenode IRC bot'
cmd = @connection.receive
expect(cmd.nil?).to be(false)
expect(cmd).to be_an_instance_of(IRConnect::Command)
end
it 'waits for a specific command' do
login_commands = {
'001' => 'RPL_WELCOME',
'431' => 'ERR_NONICKNAMEGIVEN',
'432' => 'ERR_ERRONEUSNICKNAME',
'433' => 'ERR_NICKNAMEINUSE',
'436' => 'ERR_NICKCOLLISION',
'461' => 'ERR_NEEDMOREPARAMS',
'462' => 'ERR_ALREADYREGISTERED'
}
@connection.socket.server_responses += [
'NOTICE AUTH :*** Looking up your hostname...',
'NOTICE AUTH :*** Found your hostname, welcome back',
'NOTICE AUTH :*** Checking ident',
'NOTICE AUTH :*** No identd (auth) response',
':irc.fakenode.net 001 bot :Welcome to the fakenode IRC Network bot'
]
cmd = @connection.receive_until { |c| login_commands.include?(c.command) }
expect(cmd).to_not be(nil)
expect(cmd).to be_an_instance_of(IRConnect::Command)
expect(cmd.prefix).to eq('irc.fakenode.net')
expect(cmd.command).to eq('001')
expect(cmd.params).to eq([
'bot', 'Welcome to the fakenode IRC Network bot'
])
expect(cmd.last_param).to eq('Welcome to the fakenode IRC Network bot')
cmd = @connection.receive_until { |c| c.last_param.include?('welcome') }
expect(cmd).to_not be(nil)
expect(cmd).to be_an_instance_of(IRConnect::Command)
expect(cmd.prefix).to be(nil)
expect(cmd.command).to eq('NOTICE')
expect(cmd.params).to eq(
['AUTH', '*** Found your hostname, welcome back']
)
expect(cmd.last_param).to eq('*** Found your hostname, welcome back')
[
'NOTICE AUTH :*** Looking up your hostname...',
'NOTICE AUTH :*** Checking ident',
'NOTICE AUTH :*** No identd (auth) response'
].each { |r| expect(@connection.receive).to eq(IRConnect::Command.new(r)) }
expect { @connection.receive }.to raise_error(RuntimeError)
end
end
describe 'logging in' do
it 'logs in to a server' do
@connection.socket.server_responses += [
'NOTICE AUTH :*** Looking up your hostname...',
'NOTICE AUTH :*** Found your hostname, welcome back',
'NOTICE AUTH :*** Checking ident',
'NOTICE AUTH :*** No identd (auth) response',
':irc.fakenode.net 001 bot :Welcome to the fakenode IRC Network bot'
]
expect { @connection.login('bot', '127.0.0.1', '127.0.0.1', 'IRC bot') }
.to_not raise_error
expect("NICK bot\r\nUSER bot 127.0.0.1 127.0.0.1 :IRC bot\r\n")
.to eq(@connection.socket.client_output)
[
'NOTICE AUTH :*** Looking up your hostname...',
'NOTICE AUTH :*** Found your hostname, welcome back',
'NOTICE AUTH :*** Checking ident',
'NOTICE AUTH :*** No identd (auth) response'
].each { |r| expect(@connection.receive).to eq(IRConnect::Command.new(r)) }
expect { @connection.receive }.to raise_error(RuntimeError)
@connection.socket.server_responses += [
'NOTICE AUTH :*** Looking up your hostname...',
'NOTICE AUTH :*** Found your hostname, welcome back',
'NOTICE AUTH :*** Checking ident',
'NOTICE AUTH :*** No identd (auth) response',
':irc.fakenode.net 001 bot :Welcome to the fakenode IRC Network bot',
':irc.fakenode.net 431 :No nickname given'
]
end
end
describe 'ping / pong' do
it 'responds to server pings with pong to keep connection alive' do
commands = [
'NOTICE AUTH :*** Looking up your hostname...',
'NOTICE AUTH :*** Found your hostname, welcome back',
'NOTICE AUTH :*** Checking ident',
'NOTICE AUTH :*** No identd (auth) response'
]
commands.each do |cmd|
@connection.socket.server_responses << "NOTICE AUTH :#{cmd}"
end
response_size = @connection.socket.server_responses.size
@connection.socket.server_responses.insert(
rand(response_size), 'PING :irc.fakenode.net'
)
commands.each do |c|
command = @connection.receive
expect(command).to_not be(nil)
expect(command).to be_an_instance_of(IRConnect::Command)
expect(command.prefix).to be(nil)
expect(command.command).to eq('NOTICE')
expect(command.params).to eq(['AUTH', c])
end
expect { @connection.receive }.to raise_error(RuntimeError)
expect(@connection.socket.client_output)
.to eq("PONG :irc.fakenode.net\r\n")
end
end
describe 'joining channels' do
it 'raises an error when attempting to join an invalid channel' do
@connection.socket.server_responses <<
":irc.fakenode.net 403 bot imaginary :That channel doesn't exist"
expect { @connection.join_channel('imaginary') }
.to raise_error(RuntimeError)
end
it 'receives a positive response when joining a valid channel' do
@connection.socket.server_responses <<
':irc.fakenode.net 332 bot #beer :everyone loves beer!'
expect { @connection.join_channel('#beer') }.to_not raise_error
end
end
describe 'sending messages' do
it 'sends a message to a channel' do
@connection.privmsg('#fakechannel', 'Hello, World!')
expect(@connection.socket.client_output)
.to eq("PRIVMSG \#fakechannel :Hello, World!\r\n")
end
end
end
<file_sep>require 'socket'
require './lib/command'
module IRConnect
# Simple wrapper around common IRC commands
class Connection
DEFAULT_OPTIONS = { port: 6667, socket_class: TCPSocket }
attr_reader :socket, :port, :connected, :nick, :server, :command_buffer
LOGIN_COMMANDS = {
'001' => 'RPL_WELCOME',
'431' => 'ERR_NONICKNAMEGIVEN',
'432' => 'ERR_ERRONEUSNICKNAME',
'433' => 'ERR_NICKNAMEINUSE',
'436' => 'ERR_NICKCOLLISION',
'461' => 'ERR_NEEDMOREPARAMS',
'462' => 'ERR_ALREADYREGISTERED'
}
JOIN_COMMANDS = {
'461' => 'ERR_NEEDMOREPARAMS',
'471' => 'ERR_CHANNELISFULL',
'473' => 'ERR_INVITEONLYCHAN',
'474' => 'ERR_BANNEDFROMCHAN',
'475' => 'ERR_BADCHANNELKEY',
'476' => 'ERR_BADCHANMASK',
'403' => 'ERR_NOSUCHCHANNEL',
'405' => 'ERR_TOOMANYCHANNELS',
'332' => 'RPL_TOPIC',
'353' => 'RPL_NAMREPLY'
}
def initialize(server, options = {})
options = DEFAULT_OPTIONS.merge(options)
@server = server
@port = options[:port]
@nick = options[:nick]
@socket = options[:socket_class].new(@server, @port)
@command_buffer = []
end
def nick(name)
unless name =~ /\A[a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]+\z/i
fail 'Invalid NICK'
end
send("NICK #{name}")
end
# host and server are typically ignored by servers
# for security reasons
def user(nickname, hostname, servername, fullname)
send("USER #{nickname} #{hostname} #{servername} :#{fullname}")
end
def login(nickname, hostname, servername, fullname)
nick(nickname)
user(nickname, hostname, servername, fullname)
reply = receive_until { |c| LOGIN_COMMANDS.include?(c.command) }
fail 'Login error, no response from server' if reply.nil?
if reply.command != '001'
fail "Login error: #{reply.last_param}\n" \
"Received: #{reply.command} -> #{LOGIN_COMMANDS[reply.command]}"
end
end
def join_channel(chan)
send("JOIN #{chan}")
reply = receive_until { |c| JOIN_COMMANDS.include?(c.command) }
fail 'Unable to join channel, unknown error' if reply.nil?
unless reply.command == '332' || reply.command == '353'
fail "Error joining #{chan}: #{reply.last_param} \n" \
"Received: #{reply.command} -> #{JOIN_COMMANDS[reply.command]}"
end
end
def privmsg(target, message)
send("PRIVMSG #{target} :#{message}")
end
def pong(target)
send(format('PONG %s', target))
end
def receive(ignore_ping: true)
return command_buffer.shift unless command_buffer.empty?
command = receive_command(ignore_ping: ignore_ping)
command.nil? ? nil : IRConnect::Command.new(command)
end
def receive_until
skip_commands = []
while (command = receive)
if yield(command)
command_buffer.unshift(*skip_commands)
return command
else
skip_commands << command
end
end
end
private
def receive_command(ignore_ping: true)
loop do
command = socket.gets
return nil if command.nil?
if ignore_ping && command =~ /\APING (.*?)\r\n\Z/
pong($1)
else
return command.sub(/\r\n\Z/, '')
end
end
end
def send(cmd)
socket.print("#{cmd}\r\n")
rescue IOError
raise
end
end
end
<file_sep>irconnect
============
Provides basic IRC client functionality.
###Author
<NAME> <<EMAIL>>
<file_sep>Gem::Specification.new do |spec|
spec.name = 'irconnect'
spec.version = '0.0.32'
spec.date = '2015-05-25'
spec.summary = "irconnect"
spec.description = "Wrapper around basic IRC Client functionality"
spec.authors = ["<NAME>"]
spec.email = '<EMAIL>'
spec.files = ['./lib/irconnect.rb', './lib/command.rb', './lib/connection.rb']
spec.homepage = 'https://github.com/jaspeers/irconnect'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.0'
end
<file_sep>require './lib/command.rb'
require './lib/connection.rb'
<file_sep>require 'rspec'
describe 'IRConnect::Command' do
it 'parses commands' do
fake_response = ':irc.fakenode.net 001 bot :Welcome to fakenode IRC bot'
cmd = IRConnect::Command.new(fake_response)
expect(cmd.nil?).to be(false)
expect(cmd).to be_an_instance_of(IRConnect::Command)
expect(cmd.prefix).to eq('irc.fakenode.net')
expect(cmd.command).to eq('001')
expect(cmd.params).to eq(['bot', 'Welcome to fakenode IRC bot'])
expect(cmd.last_param).to eq('Welcome to fakenode IRC bot')
end
it 'sets values to nil when appropriate' do
cmd = IRConnect::Command.new('PING')
expect(cmd.nil?).to be(false)
expect(cmd).to be_an_instance_of(IRConnect::Command)
expect(cmd.prefix).to be(nil)
expect(cmd.command).to eq('PING')
expect(cmd.params).to eq([])
expect(cmd.last_param).to be(nil)
end
end
<file_sep>
module IRConnect
# represents an IRC Command received from the server
class Command
attr_reader :prefix, :command, :params, :last_param
# IRC message format:
# :<prefix> <command> <params> :<trailing>
# info on parsing commands:
# http://goo.gl/N3YGLq
def initialize(command_string)
fail 'Bad IRC command format' unless command_string =~ /
\A (?::([^\040]+)\040)? # prefix
([A-Za-z]+|\d{3}) # command
((?:\040[^:][^\040]+)*) # all but the last param
(?:\040:?(.*))? # last param
\Z
/x
@prefix, @command = Regexp.last_match(1), Regexp.last_match(2)
parse_params(Regexp.last_match(3), Regexp.last_match(4))
end
def ==(other)
prefix == other.prefix &&
command == other.command &&
params == other.params
end
private
def parse_params(param, param_last)
if param.empty?
@params = []
else
@params = param.split
@params << param_last unless param_last.nil?
end
@last_param = params.last
end
end
end
<file_sep># phony TCPSocket for testing purposes
class MockTCPSocket
attr_reader :client_output
attr_accessor :server_responses
def initialize(*)
@server_responses = []
@client_output = ''
end
def gets
fail 'No response from server' if @server_responses.empty?
@server_responses.shift + "\r\n"
end
def print(output)
@client_output << output
end
end
<file_sep>require 'rspec'
require './spec/mock/mock_tcp_socket'
describe 'MockTCPSocket' do
before(:each) do
@mock_socket = MockTCPSocket.new
end
it 'creates an instance of MockTCPSocket' do
expect(@mock_socket).to_not be(nil)
expect(@mock_socket).to be_an_instance_of(MockTCPSocket)
end
it 'responds like a server' do
expect(@mock_socket).to respond_to(:server_responses)
end
it 'provides fake client output' do
expect(@mock_socket).to respond_to(:client_output)
end
describe 'gets' do
it 'responds to requests' do
expect(@mock_socket).to respond_to(:gets)
end
it 'returns fake server messages' do
@mock_socket.server_responses << 'Test Message'
expect(@mock_socket.gets).to eq("Test Message\r\n")
end
it 'fails when out of server responses' do
expect { @mock_socket.gets }.to raise_error
end
end
describe 'print' do
it 'exists' do
expect(@mock_socket).to respond_to(:print)
end
it 'adds a message to fake client output' do
@mock_socket.print('Test Message')
expect(@mock_socket.client_output).to eq('Test Message')
end
end
end
| a6ad7a76080f42f993eea24c8c256ed59575fc80 | [
"Markdown",
"Ruby"
] | 9 | Ruby | jaspeers/irconnect | e2a585e109d4d3dd5ff7c69e9ea2a6bcffc2a7ad | 00ba4cadb342eb3ecdf77810f1231df30e3f61f1 |
refs/heads/master | <file_sep>package cn.itdan.booksystem.controller;
import cn.itdan.booksystem.pojo.Article;
import cn.itdan.booksystem.pojo.PageInfo;
import cn.itdan.booksystem.service.ArticleService;
import cn.itdan.booksystem.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
public class IndexController {
private Logger logger=LoggerFactory.getLogger(IndexController.class);
@Autowired
private ArticleService articleService;
/**
* 进入博客系统主页
* @param page
* @param pageSize
* @return
*/
@RequestMapping({"/","/index"})
public ModelAndView showIndex(@RequestParam(required=true,defaultValue="1") Integer page,
@RequestParam(required=false,defaultValue="5")Integer pageSize ){
logger.info("进入博客系统主页:/index");
ModelAndView modelAndView =new ModelAndView("index");
PageInfo<Article> pageInfo =articleService.selectAllArticle(page,pageSize);
modelAndView.addObject("articles",pageInfo.getRecords());
modelAndView.addObject("pageInfo",pageInfo);
// logger.info("articles:"+pageInfo.getRecords());
return modelAndView;
}
@GetMapping(value = "/queryAllArticle")
@ResponseBody
public String queryAllArticle(){
logger.info("获取所有文章操作:/queryAllArticle");
List<Article> list=articleService.queryAllArticle();
return JsonUtils.objectToJson(list);
}
@RequestMapping("/about")
public String about(){
return "about";
}
}
<file_sep>package cn.itdan.booksystem.service.impl;
import cn.itdan.booksystem.mapper.ArticleMapper;
import cn.itdan.booksystem.pojo.Article;
import cn.itdan.booksystem.pojo.PageInfo;
import cn.itdan.booksystem.service.ArticleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@Transactional
@Service
public class ArticleServiceImpl extends BaseServiceImpl<Article>
implements ArticleService {
@Autowired
private ArticleMapper articleMapper;
private Logger logger=LoggerFactory.getLogger(ArticleServiceImpl.class);
@Override
public Article selectById(Integer id) {
logger.info("根据ID获取文章操作id为:"+id);
Article article=super.queryById(Long.valueOf(id));
if(null==article){
logger.info("根据ID获取文章操作,结果为null");
return article;
}
logger.info("根据ID获取文章操作成功");
return article;
}
@Override
public List<Article> queryAllArticle() {
logger.info("获取所有文章操作");
List<Article> list= super.queryAll();
logger.info("获取所有文章操作成功");
return list;
}
@Override
public Article selectLastArticle(Integer id) {
logger.info("获取下一篇文章操作,参数id为:"+id);
Article article=articleMapper.selectLastArticle(id);
if(null==article){
logger.info("根据ID获取文章操作,结果为null");
return article;
}
logger.info("根据ID获取文章操作成功");
return article;
}
@Override
public Article selectNextArticle(Integer id) {
logger.info("获取下一篇文章操作,参数id为:"+id);
Article article=articleMapper.selectNextArticle(id);
if(null==article){
logger.info("根据ID获取文章操作,结果为null");
return article;
}
logger.info("根据ID获取文章操作,结果:"+article.toString());
return article;
}
@Override
public Integer countAllNum() {
logger.info("获取所有文章操作");
Integer row= articleMapper.countAllNum();
if(null==row){
logger.info("获取所有文章操作,总篇数为0");
return 0;
}
logger.info("获取所有文章操作,总篇数为:"+row);
return row;
}
@Override
public boolean updateArticle(Article article) {
logger.info("更新文章操作");
//判断文章对象字段是否为空
if(StringUtils.isBlank(article.getTitle())){
logger.error("更新文章操作失败,传入的文章getTitle参数为null");
return false;
}
if(StringUtils.isBlank(article.getKeywords())){
logger.error("更新文章操作失败,传入的文章getKeywords参数为null");
return false;
}
if(StringUtils.isBlank(article.getDesci())){
logger.error("更新文章操作失败,传入的文章getDesci参数为null");
return false;
}
if(StringUtils.isBlank(article.getContent())){
logger.error("更新文章操作失败,传入的文章getContent参数为null");
return false;
}
if(null==article.getClick()){
logger.error("更新文章操作失败,传入的文章getClick参数为null");
return false;
}
if (null==article.getTime()){
logger.error("更新文章操作失败,传入的文章getTime参数为null");
return false;
}
if (null==article.getCatalogId()){
logger.error("更新文章操作失败,传入的文章getCatalogId参数为null");
return false;
}
super.update(article);
logger.info("更新文章操作成功");
return true;
}
@Override
public Integer deleteById(Integer id) {
logger.info("删除文章操作,参数id为:"+id);
Integer row= articleMapper.deleteById(id);
logger.info("删除文章操作成功,删除条数:"+row);
return row;
}
@Override
public List<Article> selectByWord(String word) {
logger.info("根据关键词查询文章操作,参数:"+word);
List<Article> list=articleMapper.selectByWord(word);
logger.info("根据关键词查询文章操作,操作成功");
return list;
}
@Override
public boolean addArticle(Article article) {
logger.info("添加文章操作");
//判断文章对象字段是否为空
if(StringUtils.isBlank(article.getTitle())){
logger.error("添加文章操作失败,传入的文章Title参数为null");
return false;
}
if(StringUtils.isBlank(article.getKeywords())){
logger.error("添加文章操作失败,传入的文章Keywords参数为null");
return false;
}
if(StringUtils.isBlank(article.getDesci())){
logger.error("添加文章操作失败,传入的文章Desci参数为null");
return false;
}
if(StringUtils.isBlank(article.getContent())){
logger.error("添加文章操作失败,传入的文章Content参数为null");
return false;
}
if (null==article.getCatalogId()){
logger.error("添加文章操作失败,传入的文章CatalogId参数为null");
return false;
}
article.setTime(new Date());
super.save(article);
logger.info("添加文章成功");
return true;
}
@Override
public PageInfo<Article> selectAllArticle(Integer star, Integer size) {
logger.info("分页查询操作");
// QueryWrapper queryWrapper=new QueryWrapper();
//queryWrapper.orderByDesc("updated");
// IPage<Article> iPage= super.queryPageList(queryWrapper,star,size);
Integer page=(star-1)*size;
List<Article> list=articleMapper.pageList(page,size);
logger.info("分页查询操作成功");
return new PageInfo<>(Long.valueOf(countAllNum()).intValue(),star,size,list);
}
}
<file_sep>package cn.itdan.booksystem.api;
import cn.itdan.booksystem.pojo.Comment;
import cn.itdan.booksystem.pojo.PageInfo;
import cn.itdan.booksystem.pojo.Reslut;
import java.util.List;
/**
* 评论dubbo接口
*/
public interface ApiCommentService {
/**
* 获取所有评论
* @param article_id
* @param offset
* @param limit
* @return
*/
PageInfo<Comment> allComments(Integer article_id, Integer offset, Integer limit);
/**
* 添加评论
* @param comment
* @return
*/
Reslut addComment(Comment comment);
/**
* 获取所有评论数
* @return
*/
Integer countAllNum();
/**
* 删除评论
* @param id
* @return
*/
Reslut delById(Long id);
}
<file_sep>package cn.itdan.booksystem.pojo;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class BasePojo implements Serializable {
private Date created;//表格创建时间
private Date updated;//更新时间
}
<file_sep>package cn.itdan.booksystem.mapper;
import cn.itdan.booksystem.pojo.Book;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface BookMapper extends BaseMapper<Book> {
}
<file_sep>package cn.itdan.booksystem.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* 书籍类
*/
@Data
@TableName("book")
public class Book extends BasePojo implements Serializable {
private static final long serialVersionUID = -1290192553261494686L;
@TableId(value = "id",type = IdType.AUTO)
private String id;
private String name;//书名
private String author;//作者
private String description;//描述
private double price;//价格
//记住图片的名称,后面就可以根据名字的名称来查看图片了
private String image;
//记住分类的id
private String category_id;
}
<file_sep>package cn.itdan.booksystem.listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.TimerTask;
/**
* session清理任务器
*/
public class MySessionTask extends TimerTask {
private Logger logger=LoggerFactory.getLogger(MySessionTask.class);
private List<HttpSession> sessions;
private Object lock;
public MySessionTask(List<HttpSession> sessions, Object lock){
this.sessions=sessions;
this.lock=lock;
}
@Override
public void run() {
synchronized (lock){
//遍历容器
//只要session大于1800秒没人用就清理掉
for (HttpSession session:sessions){
if(System.currentTimeMillis() - session.getLastAccessedTime()>(1000*1800)){}
session.invalidate();
sessions.remove(session);
logger.info("清理session");
}
}
}
}
<file_sep>package cn.itdan.booksystem.api;
import cn.itdan.booksystem.pojo.Book;
import java.util.List;
/**
* 定义图书dubbo api操作接口
*/
public interface ApiBookService {
/**
* 添加图书
* @param book 图书对象
*/
void addBook(Book book);
/**
* 根据图书ID查询图书
* @param id 图书ID
* @return
*/
Book QueryBookById(String id);
/**
* 获取全部图书并且进行分页操作
* @param start 起始页
* @param size 大小
* @return
*/
List<Book> getPageData(int start, int size);
/**
* 根据图书类型查询图书集合
* @param start
* @param size
* @param category_id 图书类型ID
* @return
*/
List<Book> getPageData(int start, int size, String category_id);
/**
* 获取总数
* @return
*/
long getTotalRecord();
/**
* 获取类型总记录
* @param category_id
* @return
*/
long getCategoryTotalRecord(String category_id);
}
<file_sep>package cn.itdan.booksystem.service;
import cn.itdan.booksystem.api.ApiArticleService;
import cn.itdan.booksystem.pojo.Article;
import cn.itdan.booksystem.pojo.Comment;
import cn.itdan.booksystem.pojo.PageInfo;
import cn.itdan.booksystem.pojo.Reslut;
import cn.itdan.booksystem.utils.JsonUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ArticleService {
@Reference(version = "${dubbo.service.version}")
private ApiArticleService apiArticleService;
@Autowired
private CommentService commentService;
/**
* 查询所有文章
* @return
*/
public List<Article> queryAllArticle(){
return apiArticleService.queryAllArticle();
}
/**
* 获取所有文章并且分页
* @param star
* @param size
* @return
*/
public PageInfo<Article> selectAllArticle(Integer star,Integer size){
return apiArticleService.selectAllArticle(star,size);
}
/**
* 根据ID查询文章内容
* @param id
* @return
*/
public Article selectById(Integer id){
return apiArticleService.selectById(id);
}
/**
* 根据文章ID查询最后的文章
* @param id
* @return
*/
public Article selectLastArticle(Integer id){
return apiArticleService.selectLastArticle(id);
}
/**
* 查询下一篇文章
* @param id
* @return
*/
public Article selectNextArticle(Integer id){
return apiArticleService.selectNextArticle(id);
}
/**
* 更新文章信息
* @param article
* @return
*/
public Reslut updateArticle(Article article) {
return apiArticleService.updateArticle(article);
}
/**
* 文章展示
* @param id
* @return
*/
public Map<String ,Object> detail(Integer id){
HashMap<String,Object> map=new HashMap<>();
PageInfo <Comment> pageInfo =commentService.allComments(id,0,10);
Article article = apiArticleService.selectById(id);
Article lastArticle = apiArticleService.selectLastArticle(id);
Article nextArticle = apiArticleService.selectNextArticle(id);
Integer clickNum=article.getClick();
article.setClick(clickNum+1);
apiArticleService.updateArticle(article);
map.put("article",article);
map.put("lastArticle",lastArticle);
map.put("nextArticle",nextArticle);
map.put("comments",pageInfo.getRecords());
return map;
}
/**
* 获取文章总数
* @return
*/
public Integer countAllNum() {
return apiArticleService.countAllNum();
}
/**
* 添加文章
* @param article
* @return
*/
public Reslut addArticle(Article article) {
return apiArticleService.addArticle(article);
}
/**
* 根据关键词去查询文章
* @param word
* @return
*/
public List<Article> selectByWord(String word){
return apiArticleService.selectByWord(word);
}
/**
* 删除文章操作
* @param id
* @return
*/
public Reslut deleteById(Integer id) {
return apiArticleService.deleteById(id);
}
}
<file_sep>package cn.itdan.booksystem.listener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Timer;
@Configuration
public class MyTimer {
@Bean
public Timer timer(){
return new Timer();
}
}
<file_sep>package cn.itdan.booksystem.listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
/**
* session 定时清理监听器
*/
@Component
public class SessionListener implements ServletContextListener,HttpSessionListener {
private Logger logger=LoggerFactory.getLogger(SessionListener.class);
@Autowired
private Timer timer;
//服务启动时就创建session容器
//因为主要涉及增删所以选用LinkedList,还存在并发问题所以需要做同步
private final static List<HttpSession> sessionList= Collections.synchronizedList(new LinkedList<HttpSession>());
//定义一把锁(Session添加到容器和扫描容器这两个操作应该同步起来)
private Object lock = 1;
@Scheduled(cron = "0/1800 * * * * *")//每隔1800秒清理一次session
public void contextInit(){
//执行任务(每隔1800秒执行一次,1秒延迟)
timer.schedule(new MySessionTask(sessionList, lock),1,1800*1000);
logger.info("执行清理任务");
}
public void sessionCreated(HttpSessionEvent se ){
//只要Session一创建了,就应该添加到容器中
synchronized (lock) {
sessionList.add(se.getSession());
}
logger.info("创建session");
}
public void sessionDestroyed(HttpSessionEvent se) {
logger.info("销毁session");
}
public void contextDestroyed(ServletContextEvent sce) {
logger.info("销毁Context");
}
}
<file_sep>package cn.itdan.booksystem.error;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 异常处理类
*/
@Configuration
public class GlobalExeptionResolver implements HandlerExceptionResolver {
private static final Logger logger=LoggerFactory.getLogger(GlobalExeptionResolver.class);
@Bean
public GlobalExeptionResolver globalExxeptionResolver(){
return new GlobalExeptionResolver();
}
@Override
/**
* 全局异常处理器
*/
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//打印控制台
ex.printStackTrace();
//写日志
//一般都调成Info级别
logger.info("系统发生异常");
logger.error("系统发生异常",ex);
//发邮件,发短信
//使用jmall工具包,网上搜
//回显错误页面
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("/error/exception");//显示错误界面
return modelAndView;
}
}
<file_sep># 1.简介
* 本仓库为个人项目练习模块,模块分为:书城模块+博客模块+权限管理模块,现在完成了博客模块。
* 本项目项目前端使用的bootstrap+jquery,后端使用的springboot+dubbo+mybatis-plus。
# 2.项目功能
### (1) 博客系统分为:博客前台和博客后台两部分。
* 博客前台:全文章的全浏览,新增文章评论和文章评论的全浏览,文章搜索。
* 博客后台:文章管理(文章的CRUD),文章评论的管理,admin的登入情况,登入的IP,时间,端口号以登入次数。
* 还写入了防用户重复提交功能,session定时清理
### (2)博客系统架构图

# 3.项目部署
### (1)本地部署
* download项目到idea中,在各小项目resource文件夹下application.propertis配置文件中配置好自己本地的mysql,redis,dubbo和mongodb。
* 启动bolg模块和user模块下的springboot的启动类,启动BlogProvider.class和UserProvider.class。
* 启动web模块下的springboot的启动类,启动WebApplication.class。
* 当三个模块的启动好后,访问http://localhost:9091,就会跳转博客前台,访问http://localhost:9091/admin,在没有登入的情况下会被登入拦截器拦截跳转至登入界面登入,登入后进入博客后台系统。
### (2)Linux部署
* 将项目文件打成zip包(其他包也行,能在Linux上解压就可以)。

* 将压缩好的文件上传到linux系统上,并将其解压后,cd 项目名 进入项目中,通过mvn install -Dmaven.test.skip=true,将项目下的模块打成jar包。




* 创建一个文件,将bolg模块,user模块和web模块的jar拷出放入文件中,通过Java -jar jar名 去运行jar包即可。


# 4.项目浏览










<file_sep>package cn.itdan.booksystem.config;
import cn.itdan.booksystem.interceptor.LoginInterceptor;
import cn.itdan.booksystem.listener.SessionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 登入拦截器配置
*/
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
/**
* 用来配置静态资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
}
/**
* 用来注册拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns("/**") 表示拦截所有的请求,
// excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问
registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns("/", "/index","/admin/index","/login",
"/admin","/admin/login","/api/loginCheck","/js/**","/images/**","/css/**");
}
}
<file_sep>package cn.itdan.booksystem.mapper;
import cn.itdan.booksystem.pojo.AdminLoginLog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface AdminLoginLogMapper extends BaseMapper<AdminLoginLog> {
/**
* 获取指定ID admin的登入情况
* @param adminId
* @return
*/
@Select("Select id, admin_id, date, ip from admin_login_log where admin_id = #{adminId} ORDER BY id DESC LIMIT 2")
List<AdminLoginLog> selectRencent(@Param(value = "adminId") Integer adminId);
/**
* 添加登入信息
* @param adminLoginLog
* @return
*/
@Insert("insert into admin_login_log (admin_id, date,ip,created,updated) " +
"values(#{adminLoginLog.adminId},#{adminLoginLog.date},#{adminLoginLog.ip},#{adminLoginLog.created},#{adminLoginLog.updated})")
Integer addLoginLog(@Param(value = "adminLoginLog") AdminLoginLog adminLoginLog);
/**
* 获取指定ID admin的登入次数
* @param adminId
* @return
*/
@Select("SELECT count(id) from admin_login_log where admin_id=#{adminId}")
Integer selectCountByAdminId(@Param(value = "adminId") Integer adminId);
}
<file_sep>package cn.itdan.booksystem.controller;
import cn.itdan.booksystem.pojo.Comment;
import cn.itdan.booksystem.pojo.Reslut;
import cn.itdan.booksystem.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/comment")
public class CommentController {
@Autowired
private CommentService commentService;
@PostMapping (value = "/addComment")
@ResponseBody
public Reslut commentAdd(HttpServletRequest request) {
Comment comment=new Comment();
comment.setArticleId(Long.parseLong(request.getParameter("articleId")));
comment.setContent(request.getParameter("content"));
comment.setName(request.getParameter("name"));
comment.setEmail(request.getParameter("email"));
Reslut res= commentService.addComment(comment);
return res;
}
}
<file_sep>package cn.itdan.booksystem.service;
import cn.itdan.booksystem.pojo.Comment;
import cn.itdan.booksystem.pojo.PageInfo;
import java.util.List;
public interface CommentService {
/**
* 获取所有评论
* @param article_id
* @param offset
* @param limit
* @return
*/
PageInfo<Comment> allComments(Integer article_id, Integer offset, Integer limit);
/**
* 添加评论
* @param comment
* @return
*/
Integer addComment(Comment comment);
/**
* 获取所有评论数
* @return
*/
Integer countAllNum();
/**
* 删除评论
* @param id
* @return
*/
boolean delById(Long id);
}
| 67e7812751ecf3e7d8923ed3d9811904380bd510 | [
"Markdown",
"Java"
] | 17 | Java | 18376108492/book_system | ca3a7c60da0df5e36f85e468bc46f59019258a83 | 2e47d44c843809dd5e6ed4cb79ec1f09e20b6ebc |
refs/heads/develop | <file_sep>import random
def run():
number_fount = False
limit = int(input('Ingresa el numero limite: '))
random_number = random.randint(0,limit)
while not number_fount:
number = int(input('Intenta un numero: '))
if number == random_number:
print('Felicidades. Encontraste el numero')
number_fount = True
elif number > random_number:
print('El numero es mas pequeño')
else:
print('El numero es mas grande')
if __name__ == '__main__':
run()<file_sep>import turtle
window = turtle.Screen()
tortuga = turtle.Turtle()
tortuga.forward(100)
tortuga.right(90)
tortuga.forward(100)
tortuga.right(90)
tortuga.forward(100)
tortuga.right(90)
tortuga.forward(100)
tortuga.right(90)
tortuga.color('blue')
tortuga.clear()
window.mainloop()<file_sep>def average_temps(temps):
sum_of_temps = 0
for temp in temps:
sum_of_temps+=temp
return sum_of_temps/ len(temps)
if __name__ == '__main__':
temps = [21,24,24,22,20,23,24]
average = average_temps(temps)
print('La temperatura promedio es: {0:.3f}'.format(average))<file_sep>
clients = 'pablo,ricardo,'
def create_client(client_name):
global clients
if client_name not in clients:
clients+= client_name
_add_comma()
else:
print('Client already is in the client\'s list ')
def delete_client(client_name):
global clients
clients += client_name
_add_comma()
def list_clients():
global clients
print(clients)
def update_client(client_name,updated_client_name):
global clients
if client_name in clients:
clients = clients.replace(client_name + ',', updated_client_name +',')
else:
print("Client is not in clients list ")
def _add_comma():
global clients
clients+=','
def _print_welcome():
print('Welcome to platzi venta ')
print('*' * 50)
print('what would you like to do today? ')
print('[C]reate client')
print('[U]reate client')
print('[D]elete client')
def _get_client_name():
return input("Wha is the cient name? ")
if __name__ == '__main__':
_print_welcome()
command = input()
command = command.upper()
if command == 'C':
client_name = _get_client_name()
create_client(client_name)
list_clients()
elif command == 'U':
client_name = _get_client_name()
update_client_name = input("What is the updated client name: ")
update_client(client_name, update_client_name)
list_clients()
elif command == 'D':
delete_client()
else:
print('Invalid command')
<file_sep>
def busqueda(numbers, number,low,high):
if low > high:
return False
mid = int( (low+high) / 2 )
print(mid)
if(numbers[mid] == number):
return True
elif(numbers[mid] > number):
return busqueda(numbers, number,low, mid - 1)
else:
return busqueda(numbers, number, mid +1, high)
if __name__ == '__main__':
numbers = [1, 3, 4, 5, 6, 9, 10, 11, 25, 27, 28, 34, 36, 49, 51]
number = int(input('Que numero estas buscando: '))
result = busqueda(numbers, number,0, len(numbers)-1)
if result == True:
print('El numero fue encontrado!')
else:
print('El numero no fue encontrado!')<file_sep># -*- coding: utf-8 -*-
name = str(input('Whats your name? '))
print('Hola ' + name + '!')<file_sep># Curso Practico de Python
## Funiciones basicas.
### Archivo Main
Todo punto de entrada o archivo principal es declarado con la sentencia.
```python
if __name__ == '__main__':
pass
```
### Revisar el tipo de dato.
```
type($variable)
```
### Parsear Datos.
```python
int($variable)
str($variable)
bool($variable)
float($variable)
```
### Declaracion de una función.
```
suma_de_dos_numeros(x, y):
return x + y
```
## Scope
Dentro de python el scope funciona de tal forma que una variable global no es visible para las demas funciones, amenos que esta sea invocada explicitamente.
Aunque si solo invocas la variable pero no la modificas no es necesario agregar el global.
```python
clients='pablo,ricardo,'
def create_client(client_name):
#Llamando a la variable global clients.
global clients
clients+= client_name
if __name__ == '__main__':
clients += 'david'
print(clients)
```
| 6a16b05c3283ae9021d5df94e837ebba9c4059e8 | [
"Markdown",
"Python"
] | 7 | Python | Audio10/Curso-Python | e59cda3fd6fe52bec0fe0705ae5f79ae7e9d6d83 | 6d3c691d91deceea20404fbf9093d4d8ca202b4b |
refs/heads/master | <file_sep># -*- coding:utf-8 -*-
import time
from collections import UserDict
from peewee import Field
from peewee import Model
class ModelsToDict(dict):
"""peewee to dict
:type data: object
:type is_shield: bool
:type shield_field: list [peewee Field, "name"]
:type field_name: dict {filed or peewee Field: "name"}
:type field_handle: dict {filed or peewee Field: func}
:param data: peewee query object
:param is_shield: is shield kw filed
:param shield_field: shield filed
:param field_handle: apponit filed handle
:param field_name: apponit filed Modified alias
"""
def __bool__(self):
if isinstance(self._data, list):
return bool(len(self._data))
if isinstance(self._data, dict):
return bool(self._data)
def __getitem__(self, item):
print(item)
def __init__(self, **kw):
self._data = kw['data']
self.is_shield = kw.get('is_shield', True)
self.field_name = self._kw_handle(kw.get('field_name', {}))
self.shield_field = self._kw_handle([] if kw.get('shield_field') is None else kw['shield_field'])
self.field_handle = self._kw_handle({} if kw.get('field_handle') is None else kw['field_handle'])
self._data = self._models_dict()
if isinstance(self._data, dict):
super(ModelsToDict, self).__init__(**self._data)
@property
def data(self):
return self._data
def _kw_handle(self, kw):
if isinstance(kw, list):
tmp_ = []
for i in kw:
if isinstance(i, Field):
tmp_.append(i.name)
elif isinstance(i, str):
tmp_append(i)
else:
raise TypeError("{} not peewee Field or not str".format(i))
return tmp_
elif isinstance(kw, dict):
tmp_ = {}
for i in kw:
if isinstance(i, Field):
tmp_[i.name] = kw[i]
elif isinstance(i, str):
tmp_[i] = kw[i]
else:
raise TypeError("{} not peewee Field or not str".format(i))
return tmp_
else:
raise TypeError("{} not list or not dict".fromat(kw))
def _models_dict(self):
if not self._data:
return {}
if isinstance(self._data, list):
# all
return_data = []
for objects in self._data:
fileds_object = objects.select().get_query_meta()[0]
tmp_dict = {}
for _filed in fileds_object:
if _filed.name in self.shield_field and self.is_shield:
continue
_ = getattr(objects, _filed.name)
_field_name = _filed.name
if _filed.name in self.field_handle:
_ = self.field_handle[_filed.name](_)
if _filed.name in self.field_name:
_field_name = self.field_name[_field_name]
tmp_dict[_field_name] = _
return_data.append(tmp_dict)
return return_data
fileds_object = self._data.select().get_query_meta()[0]
return_data = {}
for _filed in fileds_object:
if self.is_shield and _filed.name in self.shield_field:
# shield
continue
_ = getattr(self._data, _filed.name)
_field_name = _filed.name
if _filed.name in self.field_handle:
_ = self.field_handle[_filed.name](_)
if _filed.name in self.field_name:
_field_name = self.field_name[_field_name]
return_data[_field_name] = _
return return_data
def models_to_dict(model):
"""peewee Model sequences into Dict
:param model:peewee query util object
:return: dict
"""
if not model:
return {}
if hasattr(model, 'get_query_meta'):
model_filed = model.get_query_meta()[0]
return [{l.name: getattr(i, l.name) for l in model_filed} for i in model]
model_filed = model.select().get_query_meta()[0]
return {l.name: getattr(model, l.name) for l in model_filed}
<file_sep>from SpiderMan.util.start_scrapy_project import StartScrapyProject
from SpiderMan.util.gen_scrapy_spider import GenSpider
| 3d47673a8cf243a6b795d7a2c9cc92d526b88d39 | [
"Python"
] | 2 | Python | pythonerdd/SpiderMan | e6943e176827141bffa023344848c1af1a79089a | 29d79ff937b2161e63e4326de27715df02e6ab9f |
refs/heads/master | <file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
#include "combustion_kernels.h"
#include <algorithm>
#include <stdexcept>
#include <cmath>
#include <tuple>
#include <string>
namespace griffon
{
void CombustionKernels::mechanism_set_element_mw_map(const std::map<std::string, double> element_mw_map)
{
element_mw_map_ = element_mw_map;
}
void CombustionKernels::mechanism_add_element(const std::string &element_name)
{
const auto &en = mechanismData.phaseData.elementNames;
if (std::find(en.begin(), en.end(), element_name) == en.end())
{
++mechanismData.phaseData.nElements;
mechanismData.phaseData.elementNames.push_back(element_name);
}
}
void CombustionKernels::mechanism_add_species(const std::string &species_name,
const std::map<std::string, double> atom_map)
{
const auto &sn = mechanismData.phaseData.speciesNames;
if (std::find(sn.begin(), sn.end(), species_name) != sn.end())
{
throw std::logic_error("species " + species_name + " cannot be added twice");
}
const auto &en = mechanismData.phaseData.elementNames;
for (const auto &atom_num : atom_map)
{
if (std::find(en.begin(), en.end(), atom_num.first) == en.end())
{
throw std::logic_error("cannot find atom " + atom_num.first);
}
}
double mw = 0.;
for (const auto &atom_num : atom_map)
{
mw += this->element_mw_map_.at(atom_num.first) * atom_num.second;
}
mechanismData.phaseData.speciesIndices.insert(std::make_pair(species_name, mechanismData.phaseData.nSpecies));
mechanismData.phaseData.speciesNames.push_back(species_name);
mechanismData.phaseData.molecularWeights.push_back(mw);
mechanismData.phaseData.inverseMolecularWeights.push_back(1. / mw);
++mechanismData.phaseData.nSpecies;
}
void CombustionKernels::mechanism_set_ref_pressure(const double &p_ref)
{
mechanismData.phaseData.referencePressure = p_ref;
}
void CombustionKernels::mechanism_set_gas_constant(const double &Ru)
{
mechanismData.phaseData.Ru = Ru;
}
void CombustionKernels::mechanism_set_ref_temperature(const double &T_ref)
{
mechanismData.phaseData.referenceTemperature = T_ref;
}
void CombustionKernels::mechanism_resize_heat_capacity_data()
{
const auto ns = mechanismData.phaseData.nSpecies;
mechanismData.heatCapacityData.coefficients.resize(ns);
mechanismData.heatCapacityData.nasa9Coefficients.resize(ns);
mechanismData.heatCapacityData.minTemperatures.resize(ns);
mechanismData.heatCapacityData.maxTemperatures.resize(ns);
mechanismData.heatCapacityData.types.resize(ns);
}
void CombustionKernels::mechanism_add_const_cp(const std::string &spec_name, const double &Tmin, const double &Tmax,
const double &T0, const double &h0, const double &s0, const double &cp)
{
const auto i = mechanismData.phaseData.speciesIndices.at(spec_name);
mechanismData.heatCapacityData.types[i] = CpType::CONST;
mechanismData.heatCapacityData.minTemperatures[i] = Tmin;
mechanismData.heatCapacityData.maxTemperatures[i] = Tmax;
mechanismData.heatCapacityData.coefficients[i][0] = T0;
mechanismData.heatCapacityData.coefficients[i][1] = h0;
mechanismData.heatCapacityData.coefficients[i][2] = s0;
mechanismData.heatCapacityData.coefficients[i][3] = cp;
}
void CombustionKernels::mechanism_add_nasa7_cp(const std::string &spec_name, const double &Tmin, const double &Tmid,
const double &Tmax, const std::vector<double> &low_coeffs,
const std::vector<double> &high_coeffs)
{
const auto i = mechanismData.phaseData.speciesIndices.at(spec_name);
mechanismData.heatCapacityData.types[i] = CpType::NASA7;
mechanismData.heatCapacityData.minTemperatures[i] = Tmin;
mechanismData.heatCapacityData.maxTemperatures[i] = Tmax;
auto &coeffs = mechanismData.heatCapacityData.coefficients[i];
coeffs[0] = Tmid;
const double R = mechanismData.phaseData.Ru;
for (std::size_t i = 0; i < high_coeffs.size(); ++i)
{
coeffs[1 + i] = high_coeffs[i] * R;
}
for (std::size_t i = 0; i < low_coeffs.size(); ++i)
{
coeffs[8 + i] = low_coeffs[i] * R;
}
coeffs[2] /= 2.;
coeffs[3] /= 6.;
coeffs[4] /= 12.;
coeffs[5] /= 20.;
coeffs[9] /= 2.;
coeffs[10] /= 6.;
coeffs[11] /= 12.;
coeffs[12] /= 20.;
}
void CombustionKernels::mechanism_add_nasa9_cp(const std::string &spec_name, const double &Tmin,
const double &Tmax, const std::vector<double> &coeffs_in)
{
const double R = mechanismData.phaseData.Ru;
const auto i = mechanismData.phaseData.speciesIndices.at(spec_name);
mechanismData.heatCapacityData.types[i] = CpType::NASA9;
mechanismData.heatCapacityData.minTemperatures[i] = Tmin;
mechanismData.heatCapacityData.maxTemperatures[i] = Tmax;
const auto nregions = static_cast<int>(coeffs_in[0]);
auto &coeffs = mechanismData.heatCapacityData.nasa9Coefficients[i];
coeffs.resize(coeffs_in.size());
coeffs[0] = coeffs_in[0];
for(int k=0; k<nregions; ++k)
{
const int region_start_idx = 1 + k * 11;
for(int j=0; j<11; ++j)
{
coeffs[region_start_idx + j] = (j < 2 ? 1.0 : R) * coeffs_in[region_start_idx + j];
}
}
}
void CombustionKernels::mechanism_add_reaction_simple(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich,
const bool reversible, const double &fwd_pre_exp_value,
const double &fwd_temp_exponent, const double &fwd_act_energy)
{
typename ReactionData<NSR>::ReactionRateData rxnratedata;
rxnratedata.type = RateType::SIMPLE;
rxnratedata.reversible = reversible;
rxnratedata.hasOrders = false;
rxnratedata.set_fwd_pre_exponential(fwd_pre_exp_value);
rxnratedata.set_fwd_temp_exponent(fwd_temp_exponent);
rxnratedata.set_fwd_activation_energy(fwd_act_energy);
rxnratedata.set_reactants(reactants_stoich, mechanismData.phaseData);
rxnratedata.set_products(products_stoich, mechanismData.phaseData);
rxnratedata.finalize(mechanismData.phaseData);
mechanismData.reactionData.reactions.push_back(rxnratedata);
++mechanismData.reactionData.nReactions;
}
void CombustionKernels::mechanism_add_reaction_three_body(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich,
const bool reversible, const double &fwd_pre_exp_value,
const double &fwd_temp_exponent, const double &fwd_act_energy,
const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency)
{
typename ReactionData<NSR>::ReactionRateData rxnratedata;
rxnratedata.type = RateType::THIRD_BODY;
rxnratedata.reversible = reversible;
rxnratedata.hasOrders = false;
rxnratedata.set_fwd_pre_exponential(fwd_pre_exp_value);
rxnratedata.set_fwd_temp_exponent(fwd_temp_exponent);
rxnratedata.set_fwd_activation_energy(fwd_act_energy);
rxnratedata.set_reactants(reactants_stoich, mechanismData.phaseData);
rxnratedata.set_products(products_stoich, mechanismData.phaseData);
rxnratedata.set_three_body_efficiencies(three_body_efficiencies, default_efficiency, mechanismData.phaseData);
rxnratedata.finalize(mechanismData.phaseData);
mechanismData.reactionData.reactions.push_back(rxnratedata);
++mechanismData.reactionData.nReactions;
}
void CombustionKernels::mechanism_add_reaction_Lindemann(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich,
const bool reversible, const double fwd_pre_exp_value,
const double fwd_temp_exponent, const double fwd_act_energy,
const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency, const double flf_pre_exp_value,
const double flf_temp_exponent, const double flf_act_energy)
{
typename ReactionData<NSR>::ReactionRateData rxnratedata;
rxnratedata.type = RateType::LINDEMANN;
rxnratedata.reversible = reversible;
rxnratedata.hasOrders = false;
rxnratedata.set_fwd_pre_exponential(fwd_pre_exp_value);
rxnratedata.set_fwd_temp_exponent(fwd_temp_exponent);
rxnratedata.set_fwd_activation_energy(fwd_act_energy);
rxnratedata.set_reactants(reactants_stoich, mechanismData.phaseData);
rxnratedata.set_products(products_stoich, mechanismData.phaseData);
rxnratedata.set_three_body_efficiencies(three_body_efficiencies, default_efficiency, mechanismData.phaseData);
rxnratedata.set_falloff_pre_exponential(flf_pre_exp_value);
rxnratedata.set_falloff_temp_exponent(flf_temp_exponent);
rxnratedata.set_falloff_activation_energy(flf_act_energy);
rxnratedata.finalize(mechanismData.phaseData);
mechanismData.reactionData.reactions.push_back(rxnratedata);
++mechanismData.reactionData.nReactions;
}
void CombustionKernels::mechanism_add_reaction_Troe(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich,
const bool reversible, const double fwd_pre_exp_value,
const double fwd_temp_exponent, const double fwd_act_energy,
const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency, const double flf_pre_exp_value,
const double flf_temp_exponent, const double flf_act_energy,
const std::vector<double> &troe_parameters)
{
typename ReactionData<NSR>::ReactionRateData rxnratedata;
rxnratedata.type = RateType::TROE;
rxnratedata.reversible = reversible;
rxnratedata.hasOrders = false;
rxnratedata.set_fwd_pre_exponential(fwd_pre_exp_value);
rxnratedata.set_fwd_temp_exponent(fwd_temp_exponent);
rxnratedata.set_fwd_activation_energy(fwd_act_energy);
rxnratedata.set_reactants(reactants_stoich, mechanismData.phaseData);
rxnratedata.set_products(products_stoich, mechanismData.phaseData);
rxnratedata.set_three_body_efficiencies(three_body_efficiencies, default_efficiency, mechanismData.phaseData);
rxnratedata.set_falloff_pre_exponential(flf_pre_exp_value);
rxnratedata.set_falloff_temp_exponent(flf_temp_exponent);
rxnratedata.set_falloff_activation_energy(flf_act_energy);
rxnratedata.set_troe_parameters(troe_parameters);
rxnratedata.finalize(mechanismData.phaseData);
mechanismData.reactionData.reactions.push_back(rxnratedata);
++mechanismData.reactionData.nReactions;
}
void CombustionKernels::mechanism_add_reaction_simple_with_special_orders(
const std::map<std::string, int> &reactants_stoich, const std::map<std::string, int> &products_stoich,
const bool reversible, const double &fwd_pre_exp_value, const double &fwd_temp_exponent,
const double &fwd_act_energy, const std::map<std::string, double> &special_orders)
{
typename ReactionData<NSR>::ReactionRateData rxnratedata;
rxnratedata.type = RateType::SIMPLE;
rxnratedata.reversible = reversible;
rxnratedata.hasOrders = true;
rxnratedata.set_fwd_pre_exponential(fwd_pre_exp_value);
rxnratedata.set_fwd_temp_exponent(fwd_temp_exponent);
rxnratedata.set_fwd_activation_energy(fwd_act_energy);
rxnratedata.set_reactants(reactants_stoich, mechanismData.phaseData);
rxnratedata.set_products(products_stoich, mechanismData.phaseData);
rxnratedata.set_special_orders(special_orders, mechanismData.phaseData);
rxnratedata.finalize(mechanismData.phaseData);
mechanismData.reactionData.reactions.push_back(rxnratedata);
++mechanismData.reactionData.nReactions;
}
void CombustionKernels::mechanism_add_reaction_three_body_with_special_orders(
const std::map<std::string, int> &reactants_stoich, const std::map<std::string, int> &products_stoich,
const bool reversible, const double &fwd_pre_exp_value, const double &fwd_temp_exponent,
const double &fwd_act_energy, const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency, const std::map<std::string, double> &special_orders)
{
typename ReactionData<NSR>::ReactionRateData rxnratedata;
rxnratedata.type = RateType::THIRD_BODY;
rxnratedata.reversible = reversible;
rxnratedata.hasOrders = true;
rxnratedata.set_fwd_pre_exponential(fwd_pre_exp_value);
rxnratedata.set_fwd_temp_exponent(fwd_temp_exponent);
rxnratedata.set_fwd_activation_energy(fwd_act_energy);
rxnratedata.set_reactants(reactants_stoich, mechanismData.phaseData);
rxnratedata.set_products(products_stoich, mechanismData.phaseData);
rxnratedata.set_special_orders(special_orders, mechanismData.phaseData);
rxnratedata.set_three_body_efficiencies(three_body_efficiencies, default_efficiency, mechanismData.phaseData);
rxnratedata.finalize(mechanismData.phaseData);
mechanismData.reactionData.reactions.push_back(rxnratedata);
++mechanismData.reactionData.nReactions;
}
void CombustionKernels::mechanism_add_reaction_Lindemann_with_special_orders(
const std::map<std::string, int> &reactants_stoich, const std::map<std::string, int> &products_stoich,
const bool reversible, const double fwd_pre_exp_value, const double fwd_temp_exponent,
const double fwd_act_energy, const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency, const double flf_pre_exp_value, const double flf_temp_exponent,
const double flf_act_energy, const std::map<std::string, double> &special_orders)
{
typename ReactionData<NSR>::ReactionRateData rxnratedata;
rxnratedata.type = RateType::LINDEMANN;
rxnratedata.reversible = reversible;
rxnratedata.hasOrders = true;
rxnratedata.set_fwd_pre_exponential(fwd_pre_exp_value);
rxnratedata.set_fwd_temp_exponent(fwd_temp_exponent);
rxnratedata.set_fwd_activation_energy(fwd_act_energy);
rxnratedata.set_reactants(reactants_stoich, mechanismData.phaseData);
rxnratedata.set_products(products_stoich, mechanismData.phaseData);
rxnratedata.set_special_orders(special_orders, mechanismData.phaseData);
rxnratedata.set_three_body_efficiencies(three_body_efficiencies, default_efficiency, mechanismData.phaseData);
rxnratedata.set_falloff_pre_exponential(flf_pre_exp_value);
rxnratedata.set_falloff_temp_exponent(flf_temp_exponent);
rxnratedata.set_falloff_activation_energy(flf_act_energy);
rxnratedata.finalize(mechanismData.phaseData);
mechanismData.reactionData.reactions.push_back(rxnratedata);
++mechanismData.reactionData.nReactions;
}
void CombustionKernels::mechanism_add_reaction_Troe_with_special_orders(
const std::map<std::string, int> &reactants_stoich, const std::map<std::string, int> &products_stoich,
const bool reversible, const double fwd_pre_exp_value, const double fwd_temp_exponent,
const double fwd_act_energy, const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency, const double flf_pre_exp_value, const double flf_temp_exponent,
const double flf_act_energy, const std::vector<double> &troe_parameters,
const std::map<std::string, double> &special_orders)
{
typename ReactionData<NSR>::ReactionRateData rxnratedata;
rxnratedata.type = RateType::TROE;
rxnratedata.reversible = reversible;
rxnratedata.hasOrders = true;
rxnratedata.set_fwd_pre_exponential(fwd_pre_exp_value);
rxnratedata.set_fwd_temp_exponent(fwd_temp_exponent);
rxnratedata.set_fwd_activation_energy(fwd_act_energy);
rxnratedata.set_reactants(reactants_stoich, mechanismData.phaseData);
rxnratedata.set_products(products_stoich, mechanismData.phaseData);
rxnratedata.set_special_orders(special_orders, mechanismData.phaseData);
rxnratedata.set_three_body_efficiencies(three_body_efficiencies, default_efficiency, mechanismData.phaseData);
rxnratedata.set_falloff_pre_exponential(flf_pre_exp_value);
rxnratedata.set_falloff_temp_exponent(flf_temp_exponent);
rxnratedata.set_falloff_activation_energy(flf_act_energy);
rxnratedata.set_troe_parameters(troe_parameters);
rxnratedata.finalize(mechanismData.phaseData);
mechanismData.reactionData.reactions.push_back(rxnratedata);
++mechanismData.reactionData.nReactions;
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_fwd_pre_exponential(const double &v)
{
kFwdCoefs[0] = v;
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_fwd_temp_exponent(const double &v)
{
kFwdCoefs[1] = v;
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_fwd_activation_energy(const double &v)
{
kFwdCoefs[2] = v;
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_reactants(
const std::map<std::string, int> &reactants_stoich, const PhaseData &pd)
{
set_reactants_or_products(reactants_stoich, pd, true);
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_products(
const std::map<std::string, int> &products_stoich, const PhaseData &pd)
{
set_reactants_or_products(products_stoich, pd, false);
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_reactants_or_products(
const std::map<std::string, int> &ss_map, const PhaseData &pd, const bool is_reactants)
{
int i = 0;
for (const auto &species_stoich : ss_map)
{
const int speciesIndex = pd.speciesIndices.at(species_stoich.first);
if (is_reactants)
{
reactant_indices[i] = speciesIndex;
reactant_stoich[i] = species_stoich.second;
reactant_invmw[i] = pd.inverseMolecularWeights[speciesIndex];
}
else
{
product_indices[i] = speciesIndex;
product_stoich[i] = -species_stoich.second;
product_invmw[i] = pd.inverseMolecularWeights[speciesIndex];
}
++i;
}
if (is_reactants)
{
n_reactants = i;
}
else
{
n_products = i;
}
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_three_body_efficiencies(
const std::map<std::string, double> &eff_map, const double &default_efficiency, const PhaseData &pd)
{
thdBdyDefault = default_efficiency;
n_tb = 0;
for (const auto &rs : eff_map)
{
const int speciesIndex = pd.speciesIndices.at(rs.first);
tb_indices.push_back(speciesIndex);
tb_invmw.push_back(pd.inverseMolecularWeights[speciesIndex]);
tb_efficiencies.push_back(tb_invmw[n_tb] * (rs.second - thdBdyDefault));
++n_tb;
}
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_special_orders(
const std::map<std::string, double> &special_orders_inp, const PhaseData &pd)
{
int i = 0;
for (const auto &rs : special_orders_inp)
{
const int speciesIndex = pd.speciesIndices.at(rs.first);
special_indices[i] = speciesIndex;
special_invmw[i] = pd.inverseMolecularWeights[speciesIndex];
special_orders[i] = rs.second;
special_nonzero[i] = std::abs(special_orders[i]) > 1.e-12;
++i;
}
n_special = i;
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_falloff_pre_exponential(const double &v)
{
kPressureCoefs[0] = v;
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_falloff_temp_exponent(const double &v)
{
kPressureCoefs[1] = v;
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_falloff_activation_energy(const double &v)
{
kPressureCoefs[2] = v;
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::set_troe_parameters(const std::vector<double> &troe_params)
{
troeParams[0] = troe_params[0];
troeParams[1] = troe_params[1];
troeParams[2] = troe_params[2];
troeParams[3] = troe_params[3];
}
template <int NSR>
void CombustionKernels::ReactionData<NSR>::ReactionRateData::finalize(const PhaseData &pd)
{
{
sumStoich = 0;
std::map<int, std::tuple<int, double>> net_indices_stoichs; // spec idx to stoich, mw, invmw
for (int i = 0; i < n_reactants; ++i)
{
sumStoich += reactant_stoich[i];
net_indices_stoichs.insert(
std::make_pair(reactant_indices[i], std::make_tuple(reactant_stoich[i], reactant_invmw[i])));
}
for (int i = 0; i < n_products; ++i)
{
sumStoich += product_stoich[i];
if (net_indices_stoichs.find(product_indices[i]) == net_indices_stoichs.end())
{
net_indices_stoichs.insert(
std::make_pair(product_indices[i], std::make_tuple(product_stoich[i], product_invmw[i])));
}
else
{
const auto found_tuple = net_indices_stoichs.at(product_indices[i]);
const auto stoich = std::get<0>(found_tuple);
const auto invmw = std::get<1>(found_tuple);
net_indices_stoichs.erase(product_indices[i]);
net_indices_stoichs.insert(
std::make_pair(product_indices[i], std::make_tuple(stoich + product_stoich[i], invmw)));
}
}
n_net = 0;
for (const auto &net_index : net_indices_stoichs)
{
const auto stoich = std::get<0>(net_index.second);
if (std::abs(stoich) > 1.e-14)
{
++n_net;
}
}
if (n_net < 2 or n_net > 8)
{
std::string msg = "\n\nBad number of net reacting species (n < 2 or n > 8) detected.";
msg += "\n Number of net species detected is " + std::to_string(n_net);
msg += "\n The species are [";
for (const auto &net_index : net_indices_stoichs)
{
const auto index = net_index.first;
const auto stoich = std::get<0>(net_index.second);
if (std::abs(stoich) > 1.e-14)
{
msg += pd.speciesNames[index] + ", ";
}
}
msg += "]";
msg += "\n Reactants: [";
for (int i = 0; i < n_reactants; ++i)
{
msg += pd.speciesNames[reactant_indices[i]] + ", ";
}
msg += "]";
msg += "\n Products: [";
for (int i = 0; i < n_products; ++i)
{
msg += pd.speciesNames[product_indices[i]] + ", ";
}
msg += "]";
throw std::runtime_error(msg.c_str());
}
int idx = 0;
for (const auto &net_index : net_indices_stoichs)
{
const auto index = net_index.first;
const auto stoich = std::get<0>(net_index.second);
const auto invmw = std::get<1>(net_index.second);
if (std::abs(stoich) > 1.e-14)
{
net_indices[idx] = index;
net_stoich[idx] = stoich;
net_mw[idx] = 1. / invmw;
++idx;
}
}
is_dense = (type == RateType::THIRD_BODY or type == RateType::LINDEMANN or type == RateType::TROE);
for (int i = 0; i < n_net; ++i)
{
if (net_indices[i] == pd.nSpecies - 1)
{
is_dense = true;
}
}
for (int i = 0; i < n_reactants; ++i)
{
if (reactant_indices[i] == pd.nSpecies - 1)
{
is_dense = true;
}
}
for (int i = 0; i < n_products; ++i)
{
if (product_indices[i] == pd.nSpecies - 1)
{
is_dense = true;
}
}
for (int i = 0; i < n_tb; ++i)
{
if (tb_indices[i] == pd.nSpecies - 1)
{
is_dense = true;
}
}
n_sens = 0;
if (not is_dense)
{
for (int i = 0; i < n_reactants; ++i)
{
const int idx = reactant_indices[i];
if (std::find(sens_indices.begin(), sens_indices.end(), idx) == sens_indices.end())
{
sens_indices.push_back(idx);
n_sens++;
}
}
for (int i = 0; i < n_products; ++i)
{
const int idx = product_indices[i];
if (std::find(sens_indices.begin(), sens_indices.end(), idx) == sens_indices.end())
{
sens_indices.push_back(idx);
n_sens++;
}
}
for (int i = 0; i < n_tb; ++i)
{
const int idx = tb_indices[i];
if (std::find(sens_indices.begin(), sens_indices.end(), idx) == sens_indices.end())
{
sens_indices.push_back(idx);
n_sens++;
}
}
}
switch (n_reactants)
{
case 1:
if (reactant_stoich[0] == 1)
forwardOrder = ReactionOrder::ONE;
else if (reactant_stoich[0] == 2)
forwardOrder = ReactionOrder::TWO;
else
forwardOrder = ReactionOrder::OTHER;
break;
case 2:
if (reactant_stoich[0] == 1 && reactant_stoich[1] == 1)
forwardOrder = ReactionOrder::ONE_ONE;
else if (reactant_stoich[0] == 1 && reactant_stoich[1] == 2)
forwardOrder = ReactionOrder::ONE_TWO;
else if (reactant_stoich[0] == 2 && reactant_stoich[1] == 1)
forwardOrder = ReactionOrder::TWO_ONE;
else
forwardOrder = ReactionOrder::OTHER;
break;
case 3:
if (reactant_stoich[0] == 1 && reactant_stoich[1] == 1 && reactant_stoich[2] == 1)
forwardOrder = ReactionOrder::ONE_ONE_ONE;
else
forwardOrder = ReactionOrder::OTHER;
break;
default:
forwardOrder = ReactionOrder::OTHER;
}
sumReactantStoich = 0;
for (int s = 0; s < n_reactants; ++s)
{
sumReactantStoich += std::abs(reactant_stoich[s]);
}
switch (n_products)
{
case 1:
if (product_stoich[0] == -1)
reverseOrder = ReactionOrder::ONE;
else if (product_stoich[0] == -2)
reverseOrder = ReactionOrder::TWO;
else
reverseOrder = ReactionOrder::OTHER;
break;
case 2:
if (product_stoich[0] == -1 && product_stoich[1] == -1)
reverseOrder = ReactionOrder::ONE_ONE;
else if (product_stoich[0] == -1 && product_stoich[1] == -2)
reverseOrder = ReactionOrder::ONE_TWO;
else if (product_stoich[0] == -2 && product_stoich[1] == -1)
reverseOrder = ReactionOrder::TWO_ONE;
else
reverseOrder = ReactionOrder::OTHER;
break;
case 3:
if (product_stoich[0] == -1 && product_stoich[1] == -1 && product_stoich[2] == -1)
reverseOrder = ReactionOrder::ONE_ONE_ONE;
else
reverseOrder = ReactionOrder::OTHER;
break;
default:
reverseOrder = ReactionOrder::OTHER;
}
sumProductStoich = 0;
for (int s = 0; s < n_products; ++s)
{
sumProductStoich += std::abs(product_stoich[s]);
}
if (std::abs(kFwdCoefs[2]) < 1.e-6)
{ // if the activation energy is zero
if (std::abs(kFwdCoefs[1]) < 1.e-6)
kForm = RateConstantTForm::CONSTANT; // b=0
else if (std::abs(kFwdCoefs[1] - 1) < 1.e-6)
kForm = RateConstantTForm::LINEAR; // b=1
else if (std::abs(kFwdCoefs[1] - 2) < 1.e-6)
kForm = RateConstantTForm::QUADRATIC; // b=2
else if (std::abs(kFwdCoefs[1] + 1) < 1.e-6)
kForm = RateConstantTForm::RECIPROCAL; // b=-1
else
kForm = RateConstantTForm::ARRHENIUS; // non-integer b
}
else
kForm = RateConstantTForm::ARRHENIUS;
switch (type)
{
case RateType::SIMPLE:
case RateType::THIRD_BODY:
case RateType::LINDEMANN:
troeForm = TroeTermsPresent::NO_TROE_TERMS;
break;
case RateType::TROE:
troeForm = TroeTermsPresent::NO_TROE_TERMS;
if (std::abs(troeParams[1]) > 1.e-8)
{
if (std::abs(troeParams[2]) > 1.e-8)
{
if (std::abs(troeParams[3]) > 1.e-8)
troeForm = TroeTermsPresent::T123;
else
troeForm = TroeTermsPresent::T12;
}
else if (std::abs(troeParams[3]) > 1.e-8)
troeForm = TroeTermsPresent::T13;
else
troeForm = TroeTermsPresent::T1;
}
else
{
if (std::abs(troeParams[2]) > 1.e-8)
{
if (std::abs(troeParams[3]) > 1.e-8)
troeForm = TroeTermsPresent::T23;
else
troeForm = TroeTermsPresent::T2;
}
else if (std::abs(troeParams[3]) > 1.e-8)
troeForm = TroeTermsPresent::T3;
}
break;
default:
{
throw std::runtime_error("unknown reaction type");
}
}
}
}
} // namespace griffon
<file_sep>try:
import unittest
from copy import copy
from numpy.testing import assert_allclose
import numpy as np
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.chemistry.library import Library, Dimension
from spitfire.chemistry.flamelet import FlameletSpec
from spitfire.chemistry.tabulation import build_adiabatic_eq_library, apply_mixing_model, PDFSpec
import cantera
import cantera as ct
from spitfire.chemistry.ctversion import check as cantera_version_check
if cantera_version_check('atleast', 2, 5, None):
class Test(unittest.TestCase):
def test(self):
gas = ct.Solution('h2o2.yaml', transport_model='Multi')
mech = ChemicalMechanismSpec.from_solution(gas)
fs = FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=mech.stream('TPX', (300, 1.e5, 'O2:1, N2:3.76')),
fuel_stream=mech.stream('TPY', (300, 1.e5, 'H2:1')),
grid_points=16)
eq_lib1 = build_adiabatic_eq_library(fs, verbose=False)
z_dim = Dimension(eq_lib1.mixture_fraction_name, eq_lib1.mixture_fraction_values)
fuel_T_dim = Dimension('fuel_temperature', np.linspace(0.0, 1.0, 4))
air_T_dim = Dimension('air_temperature', np.linspace(0.0, 1.0, 3))
eq_lib2 = Library(z_dim, fuel_T_dim)
eq_lib2T = Library(fuel_T_dim, z_dim)
eq_lib3 = Library(z_dim, fuel_T_dim, air_T_dim)
eq_lib3T1 = Library(fuel_T_dim, z_dim, air_T_dim)
eq_lib3T2 = Library(fuel_T_dim, air_T_dim, z_dim)
for p in eq_lib1.props:
eq_lib2[p] = eq_lib2.get_empty_dataset()
eq_lib2T[p] = eq_lib2T.get_empty_dataset()
eq_lib3[p] = eq_lib3.get_empty_dataset()
eq_lib3T1[p] = eq_lib3T1.get_empty_dataset()
eq_lib3T2[p] = eq_lib3T2.get_empty_dataset()
for i, fuel_T_offset in enumerate(fuel_T_dim.values):
fuel_T = 300 + fuel_T_offset * 500.
fs2 = copy(fs)
fs2.fuel_stream.TP = fuel_T, 1.e5
eq_tmp = build_adiabatic_eq_library(fs2, verbose=False)
for p in eq_lib1.props:
eq_lib2[p][:, i] = eq_tmp[p]
eq_lib2T[p][i, :] = eq_tmp[p]
for j, air_T_offset in enumerate(air_T_dim.values):
air_T = 300 + air_T_offset * 500.
fs3 = copy(fs2)
fs3.oxy_stream.TP = air_T, 1.e5
eq_tmp = build_adiabatic_eq_library(fs3, verbose=False)
for p in eq_lib1.props:
eq_lib3[p][:, i, j] = eq_tmp[p]
eq_lib3T1[p][i, :, j] = eq_tmp[p]
eq_lib3T2[p][i, j, :] = eq_tmp[p]
nonT_props = list(eq_lib1.props)
nonT_props.remove('temperature')
eq_lib1.remove(*nonT_props)
eq_lib2.remove(*nonT_props)
eq_lib2T.remove(*nonT_props)
eq_lib3.remove(*nonT_props)
eq_lib3T1.remove(*nonT_props)
eq_lib3T2.remove(*nonT_props)
z_svv = np.linspace(0., 1., 6)
Tf_svv = np.linspace(0., 1., 5)
eq_lib1_t = apply_mixing_model(eq_lib1, {'mixture_fraction': PDFSpec('ClipGauss', z_svv)}, verbose=False)
eq_lib2_t = apply_mixing_model(eq_lib2, {'mixture_fraction': PDFSpec('ClipGauss', z_svv)}, verbose=False)
eq_lib3_t = apply_mixing_model(eq_lib3, {'mixture_fraction': PDFSpec('ClipGauss', z_svv)}, num_procs=1, verbose=False)
eq_lib2T_t = apply_mixing_model(eq_lib2T, {'mixture_fraction': PDFSpec('ClipGauss', z_svv)}, verbose=False)
eq_lib3T1_t = apply_mixing_model(eq_lib3T1, {'mixture_fraction': PDFSpec('ClipGauss', z_svv)}, num_procs=1, verbose=False)
eq_lib3T2_t = apply_mixing_model(eq_lib3T2, {'mixture_fraction': PDFSpec('ClipGauss', z_svv)}, num_procs=1, verbose=False)
eq_lib2_tt = apply_mixing_model(eq_lib2_t, {'fuel_temperature_mean': PDFSpec('Beta', Tf_svv, variance_name='Tfvar')}, added_suffix='', num_procs=1, verbose=False)
eq_lib3_tt = apply_mixing_model(eq_lib3_t, {'fuel_temperature_mean': PDFSpec('Beta', Tf_svv, variance_name='Tfvar')}, added_suffix='', num_procs=1, verbose=False)
def get_dim_names(lib):
return [d.name for d in lib.dims]
self.assertEqual(['mixture_fraction'], get_dim_names(eq_lib1))
self.assertEqual(['mixture_fraction_mean', 'scaled_scalar_variance_mean'], get_dim_names(eq_lib1_t))
self.assertEqual(['mixture_fraction', 'fuel_temperature'], get_dim_names(eq_lib2))
self.assertEqual(['mixture_fraction_mean', 'fuel_temperature_mean', 'scaled_scalar_variance_mean'],
get_dim_names(eq_lib2_t))
self.assertEqual(
['mixture_fraction_mean', 'fuel_temperature_mean', 'scaled_scalar_variance_mean', 'Tfvar'],
get_dim_names(eq_lib2_tt))
self.assertEqual(['mixture_fraction', 'fuel_temperature', 'air_temperature'],
get_dim_names(eq_lib3))
self.assertEqual(['mixture_fraction_mean', 'fuel_temperature_mean', 'air_temperature_mean',
'scaled_scalar_variance_mean'],
get_dim_names(eq_lib3_t))
self.assertEqual(['mixture_fraction_mean', 'fuel_temperature_mean', 'air_temperature_mean',
'scaled_scalar_variance_mean', 'Tfvar'],
get_dim_names(eq_lib3_tt))
self.assertEqual(['fuel_temperature', 'mixture_fraction'], get_dim_names(eq_lib2T))
self.assertEqual(['fuel_temperature_mean', 'mixture_fraction_mean', 'scaled_scalar_variance_mean'],
get_dim_names(eq_lib2T_t), eq_lib2T_t)
self.assertEqual(['fuel_temperature', 'mixture_fraction', 'air_temperature'],
get_dim_names(eq_lib3T1))
self.assertEqual(['fuel_temperature', 'air_temperature', 'mixture_fraction'],
get_dim_names(eq_lib3T2))
self.assertEqual(['fuel_temperature_mean', 'mixture_fraction_mean', 'air_temperature_mean',
'scaled_scalar_variance_mean'],
get_dim_names(eq_lib3T1_t))
self.assertEqual(['fuel_temperature_mean', 'air_temperature_mean', 'mixture_fraction_mean',
'scaled_scalar_variance_mean'],
get_dim_names(eq_lib3T2_t))
self.assertFalse(np.any(np.isnan(eq_lib1['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib1_t['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib2['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib2T['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib2_t['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib2T_t['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib3['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib3T1['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib3T2['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib3_t['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib3_tt['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib3T1_t['temperature'])))
self.assertFalse(np.any(np.isnan(eq_lib3T2_t['temperature'])))
self.assertIsNone(assert_allclose(eq_lib2T['temperature'].T, eq_lib2['temperature']))
self.assertIsNone(assert_allclose(np.swapaxes(eq_lib3T1['temperature'], 0, 1),
eq_lib3['temperature']))
self.assertIsNone(assert_allclose(np.swapaxes(np.swapaxes(eq_lib3T2['temperature'], 1, 2), 0, 1),
eq_lib3['temperature']))
self.assertIsNone(assert_allclose(np.squeeze(eq_lib1_t['temperature'][:, 0]),
eq_lib1['temperature']))
self.assertIsNone(assert_allclose(np.squeeze(eq_lib2_t['temperature'][:, :, 0]),
eq_lib2['temperature']))
self.assertIsNone(assert_allclose(np.squeeze(eq_lib3_t['temperature'][:, :, :, 0]),
eq_lib3['temperature']))
self.assertIsNone(assert_allclose(np.squeeze(eq_lib3_tt['temperature'][:, :, :, 0, 0]),
eq_lib3['temperature']))
if __name__ == '__main__':
unittest.main()
except ImportError:
pass
<file_sep>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize, LogNorm
import matplotlib.animation as manimation
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d as a3
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.chemistry.flamelet2d import _Flamelet2D
FFMpegWriter = manimation.writers['ffmpeg']
metadata = dict(title='Movie Test', artist='Matplotlib',
comment='Movie support!')
writer = FFMpegWriter(fps=15, metadata=metadata)
nx = 24
ny = nx
x_range = np.linspace(0., 1., nx)
y_range = np.linspace(0., 1., ny)
x_grid, y_grid = np.meshgrid(x_range, y_range)
t_list = np.load('ip_times.npy')
solution_list = np.load('ip_solutions.npy')
# t_list = np.load('t_sg_eg_54.npy')
# solution_list = np.load('q_sg_eg_54.npy')
Tmin = 200.
Tmax = int(np.max(solution_list) // 100 + 1) * 100
nt = t_list.size
ndof = solution_list.size // nt
nq = ndof // nx // ny
# m = ChemicalMechanismSpec(cantera_xml='ethylene-luo.xml', group_name='ethylene-luo')
# m = ChemicalMechanismSpec(cantera_xml='coh2-hawkes.xml', group_name='coh2-hawkes')
m = ChemicalMechanismSpec(cantera_xml='heptane-liu-hewson-chen-pitsch-highT.xml', group_name='gas')
variable = 'T'
pressure = 101325.
air = m.stream(stp_air=True)
air.TP = 300., pressure
# sg = m.stream('X', 'H2:1, CO:2')
sg = m.stream('X', 'H2:1, CO:1, CH4:1, CO2:1')
fuel2 = m.copy_stream(sg)
# fuel2.TP = 300., pressure
fuel2.TP = 400., pressure
# c2h4 = m.stream('X', 'C2H4:1')
eg = m.stream('X', 'CO2:1, H2O:1, CO:0.5, H2:0.001')
c7 = m.stream('X', 'NXC7H16:1')
# fuel1 = m.copy_stream(eg)
# fuel1.TP = 300., pressure
fuel1 = m.copy_stream(c7)
fuel1.TP = 485., pressure
fuel1_name = 'C7'
fuel2_name = 'SG'
f = _Flamelet2D(m, 'equilibrium', pressure, air, fuel1, fuel2, 10., 10., grid_1=x_range, grid_2=y_range)
iq = 0 if variable == 'T' else m.species_index(variable) + 1
# if nt == 1:
# phi02d = solution_list[iq::nq].reshape((ny, nx), order='F')
# else:
# phi02d = solution_list[0, iq::nq].reshape((ny, nx), order='F')
phi0 = np.copy(f._initial_state)[iq::nq]
phi02d = phi0.reshape((ny, nx), order='F')
def plot_contours(it):
fig = plt.figure()
# plt.set_current_figure(fig)
if nt == 1:
phi2d = solution_list[iq::nq].reshape((ny, nx), order='F')
else:
phi2d = solution_list[it, iq::nq].reshape((ny, nx), order='F')
ax = plt.subplot2grid((3, 4), (2, 1), rowspan=1, colspan=2)
ax.cla()
ax.plot(x_range, phi02d[0, :], 'b--', label='EQ')
ax.plot(x_range, phi2d[0, :], 'g-', label='SLFM')
if variable == 'T':
ax.set_ylim([Tmin, Tmax])
ax.yaxis.tick_right()
ax.set_xlabel('$Z_1$')
ax.set_xlim([0, 1])
ax.grid(True)
# ax.legend(loc='best')
ax.legend(loc='center left', bbox_to_anchor=(-0.4, 0.5), ncol=1, borderaxespad=0, frameon=False)
ax = plt.subplot2grid((3, 4), (0, 0), rowspan=2, colspan=1)
ax.cla()
ax.plot(phi02d[:, 0], y_range, 'b--', label='EQ')
ax.plot(phi2d[:, 0], y_range, 'g-', label='SLFM')
if variable == 'T':
ax.set_xlim([Tmin, Tmax])
ax.set_ylabel('$Z_2$')
ax.set_ylim([0, 1])
ax.grid(True)
# ax.legend(loc='best')
ax = plt.subplot2grid((3, 4), (0, 1), rowspan=2, colspan=2)
cax = plt.subplot2grid((3, 4), (0, 3), rowspan=2, colspan=1)
ax.cla()
if variable == 'T':
contour = ax.contourf(x_grid, y_grid, phi2d, cmap=plt.get_cmap('magma'),
norm=Normalize(Tmin, Tmax), levels=np.linspace(Tmin, Tmax, 20))
else:
contour = ax.contourf(x_grid, y_grid, phi2d, cmap=plt.get_cmap('magma'),
levels=np.linspace(np.min(phi2d), np.max(phi2d), 20))
plt.colorbar(contour, cax=cax)
ax.plot([0, 0, 1, 0], [0, 1, 0, 0], 'k-', linewidth=0.5, zorder=4)
# ax.contour(x_grid, y_grid, phi2d, cmap=plt.get_cmap('rainbow'),
# norm=Normalize(Tmin, Tmax), levels=np.linspace(Tmin, Tmax, 20))
t1 = plt.Polygon(np.array([[1, 0], [1, 1], [0, 1]]), color='w', zorder=3)
ax.add_patch(t1)
ax.text(-0.1, 1.04, fuel1_name, fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=10)
ax.text(0.95, -0.05, fuel2_name, fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=11)
ax.text(-0.08, -0.05, 'air', fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=12)
# ax.set_xlabel('$Z_1$')
# ax.set_ylabel('$Z_2$', rotation=0)
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.grid(True)
cax.set_title('SLFM T' if variable == 'T' else 'SLFM ' + variable)
plt.tight_layout()
fig5 = plt.figure()
# plt.set_current_figure(fig)
ax = plt.subplot2grid((3, 4), (2, 1), rowspan=1, colspan=2)
ax.cla()
ax.plot(x_range, phi02d[0, :])
ax.plot(x_range, phi2d[0, :])
if variable == 'T':
ax.set_ylim([Tmin, Tmax])
ax.yaxis.tick_right()
ax.set_xlabel('$Z_1$')
ax.set_xlim([0, 1])
ax.grid(True)
ax = plt.subplot2grid((3, 4), (0, 0), rowspan=2, colspan=1)
ax.cla()
ax.plot(phi02d[:, 0], y_range)
ax.plot(phi2d[:, 0], y_range)
if variable == 'T':
ax.set_xlim([Tmin, Tmax])
ax.set_ylabel('$Z_2$')
ax.set_ylim([0, 1])
ax.grid(True)
ax = plt.subplot2grid((3, 4), (0, 1), rowspan=2, colspan=2)
cax = plt.subplot2grid((3, 4), (0, 3), rowspan=2, colspan=1)
ax.cla()
if variable == 'T':
contour = ax.contourf(x_grid, y_grid, phi02d, cmap=plt.get_cmap('magma'),
norm=Normalize(Tmin, Tmax), levels=np.linspace(Tmin, Tmax, 20))
else:
contour = ax.contourf(x_grid, y_grid, phi02d, cmap=plt.get_cmap('magma'),
levels=np.linspace(np.min(phi2d), np.max(phi2d), 20))
plt.colorbar(contour, cax=cax)
ax.plot([0, 0, 1, 0], [0, 1, 0, 0], 'k-', linewidth=0.5, zorder=4)
# ax.contour(x_grid, y_grid, phi2d, cmap=plt.get_cmap('rainbow'),
# norm=Normalize(Tmin, Tmax), levels=np.linspace(Tmin, Tmax, 20))
t1 = plt.Polygon(np.array([[1, 0], [1, 1], [0, 1]]), color='w', zorder=3)
ax.add_patch(t1)
ax.text(-0.1, 1.04, fuel1_name, fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=10)
ax.text(0.95, -0.05, fuel2_name, fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=11)
ax.text(-0.08, -0.05, 'air', fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=12)
# ax.set_xlabel('$Z_1$')
# ax.set_ylabel('$Z_2$', rotation=0)
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.grid(True)
cax.set_title('EQ T' if variable == 'T' else 'EQ ' + variable)
plt.tight_layout()
fig4 = plt.figure()
# plt.set_current_figure(fig4)
if nt == 1:
phi2d = solution_list[iq::nq].reshape((ny, nx), order='F')
else:
phi2d = solution_list[it, iq::nq].reshape((ny, nx), order='F')
ax = plt.subplot2grid((3, 4), (2, 1), rowspan=1, colspan=2)
ax.cla()
ax.plot(x_range, phi2d[0, :] - phi02d[0, :])
ax.yaxis.tick_right()
ax.set_xlabel('$Z_1$')
ax.set_xlim([0, 1])
ax.grid(True)
ax = plt.subplot2grid((3, 4), (0, 0), rowspan=2, colspan=1)
ax.cla()
ax.plot(phi2d[:, 0] - phi02d[:, 0], y_range)
ax.set_ylabel('$Z_2$')
ax.set_ylim([0, 1])
ax.grid(True)
ax = plt.subplot2grid((3, 4), (0, 1), rowspan=2, colspan=2)
cax = plt.subplot2grid((3, 4), (0, 3), rowspan=2, colspan=1)
ax.cla()
relerr = (phi02d - phi2d) / (np.max([np.max(phi02d), np.max(phi2d)]) + 1.e-8)
contour = ax.contourf(x_grid, y_grid, relerr,
cmap=plt.get_cmap('bwr'),
levels=np.linspace(-np.max(np.abs(relerr)), np.max(np.abs(relerr)), 40))
plt.colorbar(contour, cax=cax)
ax.contour(x_grid, y_grid, relerr, levels=[0.], colors=['k'], linewidths=[0.5])
ax.plot([0, 0, 1, 0], [0, 1, 0, 0], 'k-', linewidth=0.5, zorder=4)
t1 = plt.Polygon(np.array([[1, 0], [1, 1], [0, 1]]), color='w', zorder=3)
ax.add_patch(t1)
ax.text(-0.1, 1.04, fuel1_name, fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=10)
ax.text(0.95, -0.05, fuel2_name, fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=11)
ax.text(-0.08, -0.05, 'air', fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=12)
# ax.set_xlabel('$Z_1$')
# ax.set_ylabel('$Z_2$', rotation=0)
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.grid(True)
cax.set_title('relative error\nEQ-SLFM T' if variable == 'T' else 'relative error\nEQ-SLFM ' + variable)
plt.tight_layout()
def plot_3d_scatter():
fig1 = plt.figure()
ax = fig1.add_subplot(111, projection='3d')
xf, yf = x_grid.ravel(order='F'), y_grid.ravel(order='F')
phi = solution_list[-1, iq::nq]
zztri = xf + yf <= 1.
ax.scatter(xf[zztri], yf[zztri], phi[zztri], c=phi[zztri], s=8, cmap=plt.get_cmap('rainbow'))
ax.set_xlabel('$Z_1$')
ax.set_ylabel('$Z_2$')
ax.set_zlabel('T' if variable == 'T' else variable)
ax.set_title('current SLFM')
fig2 = plt.figure()
ax = fig2.add_subplot(111, projection='3d')
xf, yf = x_grid.ravel(order='F'), y_grid.ravel(order='F')
phi = phi0
zztri = xf + yf <= 1.
ax.scatter(xf[zztri], yf[zztri], phi[zztri], c=phi[zztri], s=8, cmap=plt.get_cmap('rainbow'))
ax.set_xlabel('$Z_1$')
ax.set_ylabel('$Z_2$')
ax.set_zlabel('T' if variable == 'T' else variable)
ax.set_title('equilibrium')
fig3 = plt.figure()
ax = fig3.add_subplot(111, projection='3d')
xf, yf = x_grid.ravel(order='F'), y_grid.ravel(order='F')
phi = solution_list[-1, iq::nq] - phi0
zztri = xf + yf <= 1.
ax.scatter(xf[zztri], yf[zztri], phi[zztri], c=phi[zztri], s=8, cmap=plt.get_cmap('rainbow'))
ax.set_xlabel('$Z_1$')
ax.set_ylabel('$Z_2$')
ax.set_zlabel('T' if variable == 'T' else variable)
ax.set_title('SLFM - EQ')
plot_contours(-1)
plt.show()
plot_3d_scatter()
plt.show()
# for i in range(0, nt - 1, 1):
# newplot(i)
# plt.title(str(i + 1) + ' / ' + str(nt))
# plt.show()
# with writer.saving(fig, 'movie.mp4', nt):
# for i in range(0, nt, 7):
# print(i + 1, '/', nt)
# newplot(i)
# writer.grab_frame()
<file_sep>from os.path import abspath, join
def run():
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.chemistry.tabulation import build_nonadiabatic_defect_bs_library
import spitfire.chemistry.analysis as sca
test_xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
m = ChemicalMechanismSpec(cantera_input=test_xml, group_name='h2-burke')
pressure = 101325.
air = m.stream(stp_air=True)
air.TP = 1200., pressure
fuel = m.stream('TPY', (300., pressure, 'H2:1'))
flamelet_specs = {'mech_spec': m, 'oxy_stream': air, 'fuel_stream': fuel, 'grid_points': 34}
l = build_nonadiabatic_defect_bs_library(flamelet_specs, verbose=False)
l = sca.compute_specific_enthalpy(m, l)
l = sca.compute_isochoric_specific_heat(m, l)
l = sca.compute_isobaric_specific_heat(m, l)
l = sca.compute_density(m, l)
l = sca.compute_pressure(m, l)
l = sca.compute_viscosity(m, l)
return l
if __name__ == '__main__':
gold_pkl = abspath(join('tests', 'tabulation', 'nonadiabatic_defect_burke_schumann', 'gold.pkl'))
output_library = run()
output_library.save_to_file(gold_pkl)
<file_sep>"""
This module contains the _Flamelet2D class that provides a high-level interface for nonpremixed three-stream flamelets.
This is unsupported at the moment but it's pretty close to being useful...
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
import numpy as np
from scipy.special import erfinv
from scipy.sparse.linalg import LinearOperator, bicgstab
class _Flamelet2D(object):
_initializations = ['unreacted', 'equilibrium', 'linear-TY']
_grid_types = ['uniform', 'clustered']
_rates_sensitivity_option_dict = {'exact': 0, 'no-TBAF': 1}
_sensitivity_transform_option_dict = {'exact': 0}
@classmethod
def _compute_dissipation_rate(cls,
mixture_fraction,
max_dissipation_rate,
form='Peters'):
"""Compute the scalar dissipation rate across mixture fraction
Parameters
----------
mixture_fraction : array_like
the locations of grid points in mixture fraction space
max_dissipation_rate : float
the maximum value of the dissipation rate
form : str, optional
the form of the dissipation rate's dependency on mixture fraction, defaults to 'Peters', which
uses the form of N. Peters, Turbulent Combustion, 2000.
Specifying anything else will yield a constant scalar dissipation rate.
Returns
-------
x : array_like
the scalar dissipation rate on the given mixture fraction grid
"""
if form == 'Peters' or form == 'peters':
x = max_dissipation_rate * np.exp(-2. * (erfinv(2. * mixture_fraction - 1.)) ** 2)
else:
x = np.empty_like(mixture_fraction)
x[:] = max_dissipation_rate
return x
def __init__(self,
mech_spec,
initial_condition,
pressure,
stream_1,
stream_2,
stream_3,
max_dissipation_rate_1,
max_dissipation_rate_2,
dissipation_rate_1_form='Peters',
dissipation_rate_2_form='Peters',
grid_1=None,
grid_2=None,
rates_sensitivity_type='exact',
sensitivity_transform_type='exact'):
self._gas = mech_spec.copy_stream(stream_1)
self._stream_1 = stream_1
self._stream_2 = stream_2
self._stream_3 = stream_3
self._pressure = pressure
self._mechanism = mech_spec
self._griffon = self._mechanism.griffon
self._n_species = self._gas.n_species
self._n_reactions = self._gas.n_reactions
self._n_equations = self._n_species
self._state_1 = np.hstack([stream_1.T, stream_1.Y[:-1]])
self._state_2 = np.hstack([stream_2.T, stream_2.Y[:-1]])
self._state_3 = np.hstack([stream_3.T, stream_3.Y[:-1]])
self._rsopt = self._rates_sensitivity_option_dict[rates_sensitivity_type]
self._stopt = self._sensitivity_transform_option_dict[sensitivity_transform_type]
self._chi_1 = self._compute_dissipation_rate(grid_1, max_dissipation_rate_1, dissipation_rate_1_form)
self._chi_2 = self._compute_dissipation_rate(grid_2, max_dissipation_rate_2, dissipation_rate_2_form)
self._n_x = grid_1.size
self._n_y = grid_2.size
self._n_dof = self._n_equations * self._n_x * self._n_y # - 4
self._x_range = grid_1
self._y_range = grid_2
self._dx = grid_1[1:] - grid_1[:-1]
self._dy = grid_2[1:] - grid_2[:-1]
self._initial_state = np.zeros(self._n_dof)
self._z_1 = np.zeros(self._n_x * self._n_y)
self._z_2 = np.zeros(self._n_x * self._n_y)
nx = self._n_x
ny = self._n_y
nq = self._n_equations
nyq = ny * nq
h1 = self._stream_1.enthalpy_mass
h2 = self._stream_2.enthalpy_mass
h3 = self._stream_3.enthalpy_mass
Y1 = self._stream_1.Y
Y2 = self._stream_2.Y
Y3 = self._stream_3.Y
if isinstance(initial_condition, np.ndarray):
self._initial_state = np.copy(initial_condition)
elif isinstance(initial_condition, str):
for i in range(nx):
x = self._x_range[i]
for j in range(ny):
y = self._y_range[j]
ij_z = i * ny + j
ij = i * nyq + j * nq
if y > 1. - x:
z1 = 1. - y
z2 = 1. - x
else:
z1 = x
z2 = y
self._z_1[ij_z] = z1
self._z_2[ij_z] = z2
if initial_condition == 'linear-TY':
mix_state = z1 * self._state_3 + z2 * self._state_2 + (1. - z1 - z2) * self._state_1
self._initial_state[ij:ij + nq] = mix_state
else:
hmix = z1 * h3 + z2 * h2 + (1. - z1 - z2) * h1
Ymix = z1 * Y3 + z2 * Y2 + (1. - z1 - z2) * Y1
mix = mech_spec.stream('HPY', (hmix, pressure, Ymix))
if initial_condition == 'equilibrium':
mix.equilibrate('HP')
elif initial_condition == 'unreacted':
pass
else:
raise ValueError(
'invalid initial_condition string, only "equilibrium", "unreacted", and "linear-TY" are allowed')
self._initial_state[ij:ij + nq] = np.hstack([mix.T, mix.Y[:-1]])
self._variable_scales = np.ones_like(self._initial_state)
self._variable_scales[::nq] = 1.e3
nxq = (self._n_x - 1) * self._n_equations
nyq = (self._n_y - 1) * self._n_equations
self._xcp = np.zeros(nxq)
self._xcr = np.zeros(nxq)
self._xcl = np.zeros(nxq)
self._ycp = np.zeros(nyq)
self._yct = np.zeros(nyq)
self._ycb = np.zeros(nyq)
bleh1 = np.zeros(self._n_x - 1)
bleh2 = np.zeros(self._n_x - 1)
self._griffon.flamelet_stencils(self._dx, self._n_x - 1, self._chi_1, np.ones(self._n_equations),
self._xcp, self._xcl, self._xcr, bleh1, bleh2)
self._griffon.flamelet_stencils(self._dy, self._n_y - 1, self._chi_2, np.ones(self._n_equations),
self._ycp, self._ycb, self._yct, bleh1, bleh2)
self._block_diag_jac_values = np.zeros(nx * ny * nq * nq)
self._block_diag_jac_factors = np.zeros(nx * ny * nq * nq)
self._block_diag_jac_pivots = np.zeros(nx * ny * nq, dtype=np.int32)
self._jacobi_prefactor = None
self._iteration_count = 0
def rhs(self, t, state):
r = np.zeros_like(state)
self._griffon.flamelet2d_rhs(state, self._pressure, self._n_x, self._n_y, self._xcp, self._xcl, self._xcr,
self._ycp, self._ycb, self._yct, r)
return r
def block_Jacobi_setup(self, t, state, prefactor):
self._jacobi_prefactor = prefactor
self._griffon.flamelet2d_factored_block_diag_jacobian(state, self._pressure,
self._n_x, self._n_y, self._xcp, self._ycp, prefactor,
self._block_diag_jac_values,
self._block_diag_jac_factors,
self._block_diag_jac_pivots)
def block_Jacobi_solve(self, b):
nx = self._n_x
ny = self._n_y
xcp = self._xcp
xcl = self._xcl
xcr = self._xcr
ycp = self._ycp
ycb = self._ycb
yct = self._yct
pf = self._jacobi_prefactor
dj = self._block_diag_jac_values
df = self._block_diag_jac_factors
dp = self._block_diag_jac_pivots
ax = np.zeros_like(b)
rx = np.zeros_like(b)
x = np.zeros_like(b)
inv_dof_scales = 1. / self._variable_scales
tol = 1.e-8
maxiter = 16
err = tol + 1.
iteration = 0
while err > tol and iteration < maxiter:
self._griffon.flamelet2d_offdiag_matvec(x, nx, ny, xcp, xcl, xcr, ycp, ycb, yct, pf, rx)
self._griffon.flamelet2d_block_diag_solve(nx, ny, df, dp, b - rx, x)
self._griffon.flamelet2d_matvec(x, nx, ny, xcp, xcl, xcr, ycp, ycb, yct, pf, dj, ax)
err = (b - ax) * inv_dof_scales
err = np.sqrt(err.dot(err))
iteration += 1
return x, iteration, iteration < maxiter
def matvec(self, v):
nx = self._n_x
ny = self._n_y
xcp = self._xcp
xcl = self._xcl
xcr = self._xcr
ycp = self._ycp
ycb = self._ycb
yct = self._yct
pf = self._jacobi_prefactor
dj = self._block_diag_jac_values
av = np.zeros_like(v)
self._griffon.flamelet2d_matvec(v, nx, ny, xcp, xcl, xcr, ycp, ycb, yct, pf, dj, av)
return av
def block_diag_solve(self, b):
nx = self._n_x
ny = self._n_y
df = self._block_diag_jac_factors
dp = self._block_diag_jac_pivots
x = np.zeros_like(b)
self._griffon.flamelet2d_block_diag_solve(nx, ny, df, dp, b, x)
return x
def _increment_iteration_count(self, *args, **kwargs):
self._iteration_count += 1
def block_Jacobi_prec_bicgstab_solve(self, b):
a = LinearOperator((self._n_dof, self._n_dof), lambda v: self.matvec(v))
p = LinearOperator((self._n_dof, self._n_dof), lambda rhs: self.block_diag_solve(rhs))
self._iteration_count = 0
x, i = bicgstab(a, b, M=p, tol=1.e-14, maxiter=8, callback=self._increment_iteration_count)
return x, self._iteration_count, not i
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
/*
* This file includes a few wrappers around LAPACK and BLAS routines,
* some of which are written natively here to unleash optimizing compilers
* that seem to be better than BLAS/LAPACK for certain operations.
*
* Note that the factorization and solution routines below will make copies of
* input matrices or solution vectors/matrices that LAPACK otherwise modifies
* in place. This is for convenience when copying is required or acceptable.
* If copies are not acceptable, the methods should make it simple enough to
* see how to directly use the underlying LAPACK routines.
*/
#ifndef GRIFFON_LAPACK_WRAPPER_H
#define GRIFFON_LAPACK_WRAPPER_H
#include <cstddef>
namespace griffon
{
namespace blas
{
/*
* @brief compute an inner product of two arrays
*
* @param n the number of elements
* @param x the first vector
* @param y the second vector
*/
inline double
inner_product(const int n, const double *x, const double *y)
{
double d = 0.;
for (int i = 0; i < n; ++i)
d += y[i] * x[i];
return d;
}
/*
* @brief add a matvec to a vector, y = beta * y + alpha * mat * x
*
* @param n the number of elements
* @param y the output vector
* @param alpha the scale on the matvec product
* @param mat the column-major matrix
* @param x the vector being multiplied by the matrix
* @param beta the scale on the y vector
*/
inline void
matrix_vector_multiply(const int n, double *y, const double alpha, const double *mat, const double *x,
const double beta)
{
for (int j = 0; j < n; ++j)
{
y[j] *= beta;
}
for (int i = 0; i < n; ++i)
{
const double axi = alpha * x[i];
const int offset = i * n;
for (int j = 0; j < n; ++j)
{
y[j] = y[j] + mat[offset + j] * axi;
}
}
}
} // namespace blas
namespace lapack
{
extern "C" void
dgetrf_(const int *nrows, const int *ncols, double *a, const int *lda, int *ipiv, int *info);
/*
* @brief factorize a linear system of equations for later solution
*
* @param n number of rows in the matrix
* @param matrix the left-hand side matrix
* @param ipiv the pivots from dgetrf (out argument)
* @param factor the factored matrix (out argument)
*/
inline void
lu_factorize_with_copy(const int n, const double *matrix, int *ipiv, double *factor)
{
for (int i = 0; i < n * n; ++i)
factor[i] = matrix[i];
int info;
dgetrf_(&n, &n, factor, &n, ipiv, &info);
}
extern "C" void
dgetrs_(const char *transpose, const int *nrows, const int *nrhs, const double *plu, const int *lda,
const int *ipiv, double *rhs, const int *ldb, int *info);
/*
* @brief compute the solution to a prefactored linear system of equations
*
* @param n number of rows in the matrix
* @param factor the factored matrix from dgetrf
* @param ipiv the pivots from dgetrf
* @param rhs the right-hand side of the linear system
* @param solution the solution (out argument)
*/
inline void
lu_solve_with_copy(const int n, const double *factor, const int *ipiv, const double *rhs, double *solution)
{
const int one = 1;
char trans = 'N';
int info;
for (int i = 0; i < n; ++i)
solution[i] = rhs[i];
dgetrs_(&trans, &n, &one, factor, &n, ipiv, solution, &n, &info);
}
/*
* @brief compute the solution to a set of prefactored linear system of equations with the same left-hand side matrix
*
* @param n number of rows in the matrix
* @param factor the factored matrix from dgetrf
* @param ipiv the pivots from dgetrf
* @param rhsmatrix the right-hand side matrix
* @param solutionmatrix the solution (out argument)
*/
inline void
lu_solve_on_matrix_with_copy(const int n, const double *factor, const int *ipiv, const double *rhsmatrix,
double *solutionmatrix)
{
char trans = 'N';
int info;
for (int i = 0; i < n * n; ++i)
solutionmatrix[i] = rhsmatrix[i];
dgetrs_(&trans, &n, &n, factor, &n, ipiv, solutionmatrix, &n, &info);
}
extern "C" void
dgeev_(const char *doleft, const char *doright, const int *n, double *a, const int *lda, double *real, double *imag,
double *leftmat, const int *ldleft, double *rightmat, const int *ldright, double *work, int *lwork,
int *info);
/*
* @brief compute the eigenvalues of a matrix
*
* @param n number of rows in the matrix
* @param matrix the values of the matrix in column-major form
* @param realparts the real parts of the eigenvalues (out argument)
* @param imagparts the imaginary parts of the eigenvalues (out argument)
*/
inline void
eigenvalues(const int n, const double *matrix, double *realparts, double *imagparts)
{
const char rightchar = 'N';
const char leftchar = 'N';
double null[1];
int lwork, info;
double wkopt;
double matrixcopy[n * n];
for (int i = 0; i < n * n; ++i)
matrixcopy[i] = matrix[i];
// first query dgeev for the optimal workspace size
lwork = -1;
dgeev_(&leftchar, &rightchar, &n, matrixcopy, &n, realparts, imagparts, null, &n, null, &n, &wkopt, &lwork,
&info);
// allocate the workspace and compute the decomposition
lwork = static_cast<std::size_t>(wkopt);
double *work = new double[lwork];
dgeev_(&leftchar, &rightchar, &n, matrixcopy, &n, realparts, imagparts, null, &n, null, &n, work, &lwork, &info);
delete[] work;
}
} // namespace lapack
} // namespace griffon
#endif //GRIFFON_LAPACK_WRAPPER_H
<file_sep>"""
This module contains Spitfire's core time integration methods.
"""
<file_sep>import unittest
from os.path import join, abspath
from numpy.testing import assert_allclose
from tests.tabulation.nonadiabatic_defect_steady_slfm.rebless import run
from spitfire.chemistry.library import Library
from spitfire.chemistry.ctversion import check as cantera_version_check
if cantera_version_check('atleast', 2, 5, None):
class Test(unittest.TestCase):
def test_serial(self):
output_library = run(num_procs=1)
gold_file = abspath(join('tests',
'tabulation',
'nonadiabatic_defect_steady_slfm',
'gold.pkl'))
gold_library = Library.load_from_file(gold_file)
for prop in gold_library.props:
self.assertIsNone(assert_allclose(gold_library[prop], output_library[prop], rtol=2.e-4, atol=1.e-4))
def test_parallel(self):
output_library = run(num_procs=2)
gold_file = abspath(join('tests',
'tabulation',
'nonadiabatic_defect_steady_slfm',
'gold.pkl'))
gold_library = Library.load_from_file(gold_file)
for prop in gold_library.props:
self.assertIsNone(assert_allclose(gold_library[prop], output_library[prop], rtol=2.e-4, atol=1.e-4))
if __name__ == '__main__':
unittest.main()
<file_sep>Time Integration
----------------
.. toctree::
:maxdepth: 1
:caption: Demonstrations:
demo/time_integration/explicit/explicit_exponential_decay_simple
demo/time_integration/explicit/explicit_exponential_decay_custom_methods
demo/time_integration/explicit/adaptive_stepping_and_custom_termination
demo/time_integration/explicit/customized_adaptive_stepping
demo/time_integration/explicit/lid_driven_cavity_scalar_mixing
demo/time_integration/implicit/implicit_exponential_decay_simple
demo/time_integration/implicit/implicit_advection_diffusion_linear_solvers_advanced
demo/time_integration/implicit/implicit_diffusion_reaction
Methods for First-Order Ordinary Differential Equations
=======================================================
Spitfire can solve general explicit ordinary differential equations
.. math::
\frac{\partial \boldsymbol{q}}{\partial t} = \boldsymbol{r}(t, \boldsymbol{q}),
:label: general_explicit_ode
where :math:`\boldsymbol{q}=[q_1,q_2,\ldots]` is the vector of state variables
and :math:`\boldsymbol{r}=[r_1,r_2,\ldots]` is the vector of right-hand side functions.
Many systems of scientific and engineering interest fit into this form,
either as ODEs derived naturally as :eq:`general_explicit_ode` or as
partial differential equations (PDEs) in semi-discrete form (after spatial, but not temporal, discretization).
Spitfire does not currently support implicit differential equations or differential algebraic equation (DAE) systems
represented generally as :math:`\mathrm{M}\dot{\boldsymbol{q}}=\boldsymbol{r}(t,\boldsymbol{q})` for a possibly singular matrix :math:`\mathrm{M}`.
Spitfire provides a number of explicit and implicit numerical methods of solving systems in the form of :eq:`general_explicit_ode`.
All of these methods may be classified as one-step Runge-Kutta methods.
Spitfire does not yet support multi-step methods such as BDF or Adams methods, or general linear methods.
Additionally Spitfire's abstraction does not support fully-implicit Runge-Kutta methods (singly-diagonally implicit `is` supported).
Finally Spitfire does not (yet!) support implicit-explicit methods such as additive Runge-Kutta or operator splitting techniques,
but this will hopefully be tackled soon.
Methods are named according to stage count (S#), order of accuracy (P#), and the order of accuracy of the embedded error estimator (Q#) if present, similarly to ARKODE's convention.
If the embedded error order is noted, the method can be used for adaptive time-stepping based on local temporal error control.
You can add new methods of your own, even for adaptive time stepping - demonstrations in `spitfire_demo/time_integration` show how.
The explicit methods are:
- Forward Euler: ``ForwardEulerS1P1``
- Midpoint method: ``ExpMidpointS2P2``
- Trapezoidal method: ``ExpTrapezoidalS2P2Q1``
- Ralston's two-stage method: ``ExpRalstonS2P2``
- Kutta's three-stage method: ``RK3KuttaS3P3``
- The 'classical' RK4 method: ``RK4ClassicalS4P4``
- The Bogacki-Shampine four-stage method: ``BogackiShampineS4P3Q2``
- A five-stage order 4 method of Zonneveld: ``ZonneveldS5P4Q3``
- The Cash-Karp order 4 method: ``AdaptiveERK54CashKarp``
- Kennedy & Carpenter's six-stage order 4 method: ``ExpKennedyCarpetnerS6P4Q3``
- A general-purpose explicit RK method that can use any explicit Butcher table provided by the user: ``GeneralAdaptiveERK``
The implicit methods are:
- Backward Euler (BDF1): ``BackwardEulerS1P1Q1``
- Crank-Nicolson (implicit Trapezoidal): ``CrankNicolsonS2P2``
- Four-stage, order 3 method: ``KennedyCarpenterS4P3Q2``
- Four-stage, order 3 method: ``KvaernoS4P3Q2``
- Six-stage, L-stable, order 4 method with stage order two: ``KennedyCarpenterS6P4Q3``
- Eight-stage, L-stable, order 5 method with stage order two: ``KennedyCarpenterS8P5Q4``
All simulations, whether with explicit or implicit methods, with a constant or adaptive time step, are driven by Spitfire's ``odesolve`` method.
This method manages the logging of information and in-situ post-processing of user data as the simulation proceeds,
evaluation of the Jacobian/preconditioning matrix used in implicit methods, depending upon performance
of nonlinear and linear solvers in each implicit time step.
Spitfire's Abstraction of the Implicit Solver Stack
===================================================
When ODEs such as :eq:`general_explicit_ode` are solved with implicit time integration methods, a nonlinear system of equations must be solved at each time step.
The nonlinear system can be written in terms of a nonlinear operator :math:`\boldsymbol{\mathcal{N}}`,
.. math::
\boldsymbol{\mathcal{N}}(\boldsymbol{q}) = \boldsymbol{0}.
:label: eqn: simple nlin
A corresponding approximate linear operator :math:`\widetilde{\mathrm{A}}` is required in solving an exact linear problem required by the nonlinear problem,
.. math::
\widetilde{\mathrm{A}} = \bar{p}\widetilde{\boldsymbol{\mathcal{N}}_{\boldsymbol{q}}} - \mathcal{I} \quad \rightarrow \quad \mathrm{solving}\, \left[\bar{p}\boldsymbol{\mathcal{N}}_{\boldsymbol{q}} - \mathrm{I}\right]\boldsymbol{x}=\boldsymbol{b},
:label: eqn: simple lin
where the prefactor :math:`\bar{p}=ph` consists of the temporal discretization coefficient :math:`p` and time step size :math:`h`, the identity operator :math:`\mathcal{I}`, and identity matrix :math:`\mathrm{I}`, and the :math:`\widetilde{\boldsymbol{\mathcal{N}}_{\boldsymbol{q}}}` operator, an approximation of the Jacobian matrix :math:`\boldsymbol{\mathcal{N}}_{\boldsymbol{q}}`.
Nonlinear solution procedures typically require the repeated action of the inverse of the :math:`\mathrm{A}` operator, which can often be optimized by breaking it up into a costly setup phase (*e.g.*, factorization, preconditioner computation) and cheaper solve phase (*e.g.*, back-solution after factorization) so that the setup is called once per solve while solve is called many times.
The linear problem is a subset of the nonlinear problem, which itself is a subset of each single time step (:math:`t^n\to t^{n+1}`), which is a subset of a time integration loop with possibly adaptive time stepping (varying :math:`h` in time).
These five pieces form the backbone of time integration with implicit methods - this is referred to as the 'solver stack.'
In Spitfire the stack consists of ``odesolve`` (time loop), ``StepController`` (:math:`h` adaptation), ``TimeStepper`` (single step method), ``NonlinearSolver`` (solve :math:`\boldsymbol{\mathcal{N}}(\boldsymbol{q}) = \boldsymbol{0}`), and finally the ``setup`` and ``solve`` procedures for the linear solve (building the inverse of the approximate linear operator and repeatedly applying it, respectively).
Python & Performance Optimality
===============================
Composing the solver stack in Python makes it more easily extensible, but it brings performance optimality into doubt.
Similar questions arise in development of HPC codes with C++, where virtual functions are 'slow' (and have other issues).
The key factor in performance is the cost of evaluating the nonlinear residual and the various operations in the linear solve.
In solving large, one-dimensional diffusion-reaction problems (flamelets), for which Spitfire is most often used, the large majority of time is spent evaluating the residual and Jacobian matrix and solving the linear system.
Performance improvements have come from optimizing the evaluation code and leveraging adaptive time-steppers that evaluate and factorize (the "setup" phase) fewer Jacobian matrices.
Early on we prototyped moving the entire solver stack, specializg it for a single time integration method, step control strategy, nonlinear solver, and linear solver to Griffon (Spitfire's internal C++ engine).
On even the smallest practical flamelet problems, this made no real difference in the end-to-end runtime, and the use of Python in the solver stack is entirely justified.
Now, if you're solving a single exponential decay ODE, Spitfire will be terribly slow compared to an optimized compiled application.
You may not care about performance as it will still be pretty fast, but certainly there are many-query applications that might want every last bit of performance on relatively small problems.
An option there is to combine ensembles of ODEs into one large system with optimized residual and Jacobian evaluation and linear solvers.
Solving many systems at once scales down the Python overhead and puts performance optimization in the hands of the user.
As a serial, single-threaded code meant for typical CPU hardware and a general problem space, our perspective with Spitfire is simply that performance is good enough on very small problems,
and is the user's responsibility in large problems (in computing the residual, Jacobian, and linear solver).
Thus, we write abstract numerical algorithms in Spitfire with extensibility and algorithmic optimality in mind.
<file_sep>try:
import unittest
from copy import copy
from os.path import abspath, join
from numpy.testing import assert_allclose
import numpy as np
try:
from scipy.integrate import simpson
except ImportError:
from scipy.integrate import simps as simpson
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.chemistry.library import Library, Dimension
from spitfire.chemistry.flamelet import FlameletSpec
from spitfire.chemistry.tabulation import build_adiabatic_slfm_library, apply_mixing_model, PDFSpec
import cantera
import cantera as ct
import pytabprops
from spitfire.chemistry.ctversion import check as cantera_version_check
if cantera_version_check('atleast', 2, 5, None):
class Test(unittest.TestCase):
def test(self):
test_xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
m = ChemicalMechanismSpec(cantera_input=test_xml, group_name='h2-burke')
pressure = 101325.
air = m.stream(stp_air=True)
air.TP = 300., pressure
fuel = m.stream('TPY', (300., pressure, 'H2:1'))
flamelet_specs = {'mech_spec': m, 'oxy_stream': air, 'fuel_stream': fuel, 'grid_points': 34}
slfm = build_adiabatic_slfm_library(flamelet_specs,
diss_rate_values=np.logspace(-1, 4, 40),
diss_rate_ref='stoichiometric',
include_extinguished=True,
verbose=False)
class LogMean1ParamPDF:
def __init__(self, sigma):
self._sigma = sigma
self._mu = 0.
self._s2pi = np.sqrt(2. * np.pi)
self._xt = np.logspace(-6, 6, 1000)
self._pdft = np.zeros_like(self._xt)
def get_pdf(self, x):
s = self._sigma
m = self._mu
return 1. / (x * s * self._s2pi) * np.exp(-(np.log(x) - m) * (np.log(x) - m) / (2. * s * s))
def set_mean(self, mean):
self._mu = np.log(mean) - 0.5 * self._sigma * self._sigma
self._pdft = self.get_pdf(self._xt)
def set_variance(self, variance):
pass
def set_scaled_variance(self, variance):
raise ValueError(
'cannot use set_scaled_variance on LogMean1ParamPDF, use direct variance values')
def integrate(self, interpolant):
ig = interpolant(self._xt) * self._pdft
return simpson(ig, x=self._xt)
lm_pdf = LogMean1ParamPDF(1.0)
mass_fracs = slfm.props
mass_fracs.remove('temperature')
slfm.remove(*mass_fracs)
slfm_l = apply_mixing_model(
slfm,
mixing_spec={}
)
slfm_t = apply_mixing_model(
slfm,
mixing_spec={'dissipation_rate_stoich': PDFSpec(pdf=lm_pdf, variance_values=np.array([1.]))}
)
slfm_t2 = apply_mixing_model(
slfm,
mixing_spec={'dissipation_rate_stoich': PDFSpec(pdf=lm_pdf, variance_values=np.array([1.])),
'mixture_fraction': 'delta'}
)
slfm_t3 = apply_mixing_model(
slfm,
mixing_spec={'dissipation_rate_stoich': PDFSpec(pdf=lm_pdf, variance_values=np.array([1.])),
'mixture_fraction': PDFSpec(pdf='delta')}
)
slfm_t4 = apply_mixing_model(
slfm,
mixing_spec={'dissipation_rate_stoich': 'delta',
'mixture_fraction': PDFSpec(pdf='delta')},
added_suffix='_avg'
)
slfm_tt1 = apply_mixing_model(
slfm_t,
mixing_spec={
'mixture_fraction_mean': PDFSpec(pdf='ClipGauss', scaled_variance_values=np.linspace(0, 1, 8))},
added_suffix=''
)
slfm_tt2 = apply_mixing_model(
slfm,
mixing_spec={'dissipation_rate_stoich': PDFSpec(pdf=lm_pdf, variance_values=np.array([1.])),
'mixture_fraction': PDFSpec(pdf='ClipGauss',
scaled_variance_values=np.logspace(-4, 0, 8),
log_scaled=True)}
)
# todo: this test could use some checks, right now it just makes sure that all of the variations
# above and the custom PDF can actually run
if __name__ == '__main__':
unittest.main()
except ImportError:
pass
<file_sep>import unittest
import numpy as np
from os.path import join, abspath
import cantera as ct
from spitfire import ChemicalMechanismSpec as Mechanism, HomogeneousReactor
import spitfire.chemistry.analysis as sca
from spitfire.chemistry.ctversion import check as cantera_version_check
xml = abspath(join('tests', 'test_mechanisms', 'hydrogen_one_step.yaml'))
if cantera_version_check('pre', 2, 6, None):
species = ct.Species.listFromFile(xml)
ref = ct.Solution(thermo='IdealGas',
kinetics='GasKinetics',
species=species)
reactions = ct.Reaction.listFromFile(xml, ref)
else:
species = ct.Species.list_from_file(xml)
ref = ct.Solution(thermo='IdealGas',
kinetics='GasKinetics',
species=species)
reactions = ct.Reaction.list_from_file(xml, ref)
sol = ct.Solution(thermo='IdealGas',
kinetics='GasKinetics',
species=species,
reactions=reactions)
mechanism = Mechanism.from_solution(sol)
def construct_reactor(configuration, mass_transfer, heat_transfer, shape):
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
mix = mechanism.mix_for_equivalence_ratio(1.0, fuel, air)
mix.TP = 1200., 101325.
feed = mechanism.copy_stream(mix)
tau = 1.e-3
extra_args = dict()
if mass_transfer == 'open':
if configuration == 'isobaric':
extra_args['feed_temperature'] = feed.T
extra_args['feed_mass_fractions'] = feed.Y
extra_args['mixing_tau'] = tau
elif configuration == 'isochoric':
extra_args['feed_temperature'] = feed.T
extra_args['feed_mass_fractions'] = feed.Y
extra_args['feed_density'] = feed.density
extra_args['mixing_tau'] = tau
if heat_transfer == 'diathermal':
extra_args['convection_coefficient'] = 1.
extra_args['convection_temperature'] = 300.
extra_args['radiative_emissivity'] = 1.
extra_args['radiation_temperature'] = 300.
extra_args['shape_dimension_dict'] = {'shape': shape, 'char. length': 1.e-3}
try:
HomogeneousReactor(mechanism, mix,
configuration=configuration,
heat_transfer=heat_transfer,
mass_transfer=mass_transfer,
**extra_args)
return True
except:
return False
def integrate_a_few_steps(configuration, mass_transfer, heat_transfer, shape):
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
mix = mechanism.mix_for_equivalence_ratio(1.0, fuel, air)
mix.TP = 1200., 101325.
feed = mechanism.copy_stream(mix)
tau = 1.e-3
extra_args = dict()
if mass_transfer == 'open':
if configuration == 'isobaric':
extra_args['feed_temperature'] = feed.T
extra_args['feed_mass_fractions'] = feed.Y
extra_args['mixing_tau'] = tau
elif configuration == 'isochoric':
extra_args['feed_temperature'] = feed.T
extra_args['feed_mass_fractions'] = feed.Y
extra_args['feed_density'] = feed.density
extra_args['mixing_tau'] = tau
if heat_transfer == 'diathermal':
extra_args['convection_coefficient'] = 1.
extra_args['convection_temperature'] = 300.
extra_args['radiative_emissivity'] = 1.
extra_args['radiation_temperature'] = 300.
extra_args['shape_dimension_dict'] = {'shape': shape, 'char. length': 1.e-3}
try:
reactor = HomogeneousReactor(mechanism, mix,
configuration=configuration,
heat_transfer=heat_transfer,
mass_transfer=mass_transfer,
**extra_args)
reactor.integrate_to_time(final_time=1.e-6,
first_time_step=1.e-7,
minimum_time_step_count=1)
return True
except:
return False
def integrate_steady(configuration, mass_transfer, heat_transfer, shape):
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
mix = mechanism.mix_for_equivalence_ratio(1.0, fuel, air)
mix.TP = 1200., 101325.
feed = mechanism.copy_stream(mix)
tau = 1.e-3
extra_args = dict()
if mass_transfer == 'open':
if configuration == 'isobaric':
extra_args['feed_temperature'] = feed.T
extra_args['feed_mass_fractions'] = feed.Y
extra_args['mixing_tau'] = tau
elif configuration == 'isochoric':
extra_args['feed_temperature'] = feed.T
extra_args['feed_mass_fractions'] = feed.Y
extra_args['feed_density'] = feed.density
extra_args['mixing_tau'] = tau
if heat_transfer == 'diathermal':
extra_args['convection_coefficient'] = 1.
extra_args['convection_temperature'] = 300.
extra_args['radiative_emissivity'] = 1.
extra_args['radiation_temperature'] = 300.
extra_args['shape_dimension_dict'] = {'shape': shape, 'char. length': 1.e-3}
try:
reactor = HomogeneousReactor(mechanism, mix,
configuration=configuration,
heat_transfer=heat_transfer,
mass_transfer=mass_transfer,
**extra_args)
output = reactor.integrate_to_steady(steady_tolerance=1.e-4,
transient_tolerance=1.e-8)
num_time_steps = output.time_npts
return 20 < num_time_steps < 300
except:
return False
def adiabatic_closed_ignition_delay(configuration):
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
try:
mix = mechanism.mix_for_equivalence_ratio(1.0, fuel, air)
mix.TP = 1200., 101325.
reactor = HomogeneousReactor(mechanism, mix,
configuration=configuration,
heat_transfer='adiabatic',
mass_transfer='closed',
rates_sensitivity_type='dense')
t_ignition_1 = reactor.compute_ignition_delay(transient_tolerance=1.e-8, return_solution=False)
reactor = HomogeneousReactor(mechanism, mix,
configuration=configuration,
heat_transfer='adiabatic',
mass_transfer='closed',
rates_sensitivity_type='dense')
t_ignition_2 = reactor.compute_ignition_delay(transient_tolerance=1.e-10, return_solution=False)
reactor = HomogeneousReactor(mechanism, mix,
configuration=configuration,
heat_transfer='adiabatic',
mass_transfer='closed',
rates_sensitivity_type='sparse')
t_ignition_3 = reactor.compute_ignition_delay(transient_tolerance=1.e-10, return_solution=False)
success = (t_ignition_1 - t_ignition_2) / t_ignition_2 < 0.05 and \
(t_ignition_3 - t_ignition_2) / t_ignition_2 < 1e-6
if not success:
print(configuration, t_ignition_1, t_ignition_2, t_ignition_3)
return success
except Exception as e:
print(configuration, e)
return False
def adiabatic_closed_steady_after_ignition(configuration):
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
mix = mechanism.mix_for_equivalence_ratio(1.0, fuel, air)
mix.TP = 1200., 101325.
try:
reactor = HomogeneousReactor(mechanism, mix,
configuration=configuration,
heat_transfer='adiabatic',
mass_transfer='closed')
reactor.integrate_to_steady_after_ignition()
return True
except:
return False
def post_processing(configuration, mass_transfer, heat_transfer):
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
mix = mechanism.mix_for_equivalence_ratio(1.0, fuel, air)
mix.TP = 1200., 101325.
feed = mechanism.copy_stream(mix)
tau = 1.e-3
extra_args = dict()
if mass_transfer == 'open':
if configuration == 'isobaric':
extra_args['feed_temperature'] = feed.T
extra_args['feed_mass_fractions'] = feed.Y
extra_args['mixing_tau'] = tau
elif configuration == 'isochoric':
extra_args['feed_temperature'] = feed.T
extra_args['feed_mass_fractions'] = feed.Y
extra_args['feed_density'] = feed.density
extra_args['mixing_tau'] = tau
if heat_transfer == 'diathermal':
extra_args['convection_coefficient'] = 1.
extra_args['convection_temperature'] = 300.
extra_args['radiative_emissivity'] = 1.
extra_args['radiation_temperature'] = 300.
extra_args['shape_dimension_dict'] = {'shape': 'sphere', 'char. length': 1.e-3}
try:
reactor = HomogeneousReactor(mechanism, mix,
configuration=configuration,
heat_transfer=heat_transfer,
mass_transfer=mass_transfer,
**extra_args)
tol = np.sqrt(np.finfo(float).eps)
test_success = True
output_library = reactor.integrate_to_time(1e-16, minimum_time_step_count=0)
output_library = sca.compute_specific_enthalpy(mechanism, output_library)
output_library = sca.compute_density(mechanism, output_library)
output_library = sca.compute_pressure(mechanism, output_library)
output_library = sca.compute_isobaric_specific_heat(mechanism, output_library)
output_library = sca.compute_isochoric_specific_heat(mechanism, output_library)
output_library = sca.explosive_mode_analysis(mechanism, output_library,
configuration, heat_transfer,
True, True, True)
test_success = test_success and np.abs(mix.T - output_library['temperature'][-1]) / mix.T < tol
test_success = test_success and np.abs(mix.P - output_library['pressure'][-1]) / mix.P < tol
test_success = test_success and np.abs(mix.density - output_library['density'][-1]) / mix.density < tol
test_success = test_success and np.abs(mix.enthalpy - output_library['enthalpy'][-1]) / mix.enthalpy_mass < tol
test_success = test_success and np.abs(mix.cv_mass - output_library['heat capacity cv'][-1]) / mix.cv_mass < tol
test_success = test_success and np.abs(mix.cp_mass - output_library['heat capacity cp'][-1]) / mix.cp_mass < tol
return test_success
except:
return False
def create_test(test_method, c, m=None, h=None, s=None):
if test_method == 'construct':
def test(self):
self.assertTrue(construct_reactor(c, m, h, s))
elif test_method == 'integrate_a_few_steps':
def test(self):
self.assertTrue(integrate_a_few_steps(c, m, h, s))
elif test_method == 'integrate_steady':
def test(self):
self.assertTrue(integrate_steady(c, m, h, s))
elif test_method == 'ignition_delay':
def test(self):
self.assertTrue(adiabatic_closed_ignition_delay(c))
elif test_method == 'steady_after_ignition':
def test(self):
self.assertTrue(adiabatic_closed_steady_after_ignition(c))
elif test_method == 'post_processing_coverage':
def test(self):
self.assertTrue(post_processing(c, m, h))
return test
class Construction(unittest.TestCase):
pass
shape = list(HomogeneousReactor.get_supported_reactor_shapes())[0]
for configuration in ['isobaric', 'isochoric']:
for mass_transfer in ['closed', 'open']:
for heat_transfer in ['adiabatic', 'isothermal', 'diathermal']:
testname = 'test_construct_reactor_' + configuration + \
'_' + mass_transfer + \
'_' + heat_transfer + \
'_' + shape
setattr(Construction, testname, create_test('construct',
configuration,
mass_transfer,
heat_transfer,
shape))
testname = 'test_integrate_a_few_steps_' + configuration + \
'_' + mass_transfer + \
'_' + heat_transfer + \
'_' + shape
setattr(Construction, testname, create_test('integrate_a_few_steps',
configuration,
mass_transfer,
heat_transfer,
shape))
testname = 'test_integrate_steady_' + configuration + \
'_' + mass_transfer + \
'_' + heat_transfer + \
'_' + shape
setattr(Construction, testname, create_test('integrate_steady',
configuration,
mass_transfer,
heat_transfer,
'cube'))
testname = 'test_post_processing_coverage_' + configuration + '_' + mass_transfer + '_' + heat_transfer
setattr(Construction, testname,
create_test('post_processing_coverage', configuration, mass_transfer, heat_transfer))
testname = 'test_compute_ignition_delay_adiabatic_closed_' + configuration
setattr(Construction, testname, create_test('ignition_delay', configuration))
testname = 'test_compute_steady_after_ignition_adiabatic_closed_' + configuration
setattr(Construction, testname, create_test('steady_after_ignition', configuration))
if __name__ == '__main__':
unittest.main()
<file_sep>import unittest
from numpy import hstack, max, abs, ones, zeros, sum, sqrt
from cantera import Solution, one_atm, gas_constant
import numpy as np
from spitfire import ChemicalMechanismSpec
from os.path import join, abspath
from subprocess import getoutput
test_mech_directory = abspath(join('tests', 'test_mechanisms', 'old_xmls'))
mechs = [x.replace('.yaml', '') for x in getoutput('ls ' + test_mech_directory + ' | grep .yaml').split('\n')]
def validate_on_mechanism(mech, temperature, pressure, test_rhs=True, test_jac=True):
xml = join(test_mech_directory, mech + '.yaml')
T = temperature
p = pressure
r = ChemicalMechanismSpec(xml, 'gas').griffon
gas = Solution(xml)
ns = gas.n_species
gas.TPX = T, p, ones(ns)
y = gas.Y
state = hstack((T, y[:-1]))
rhsGR = np.empty(ns)
r.reactor_rhs_isobaric(state, p, 0., np.ndarray(1), 0, 0, 0, 0, 0, 0, 0, False, rhsGR)
if test_jac:
Tin, yin, tau = 0, np.ndarray(1), 0
rhsTmp = np.empty(ns)
jacGR = np.empty(ns * ns)
r.reactor_jac_isobaric(state, p, Tin, yin, tau, 0, 0, 0, 0, 0, 0, False, 0, 0, rhsTmp, jacGR)
jacGR = jacGR.reshape((ns, ns), order='F')
dT = 1.e-6
dY = 1.e-6
jacFD = np.empty((ns, ns))
rhsGR1, rhsGR2 = np.empty(ns), np.empty(ns)
state_m = hstack((T - dT, y[:-1]))
state_p = hstack((T + dT, y[:-1]))
r.reactor_rhs_isobaric(state_m, p, Tin, yin, tau, 0, 0, 0, 0, 0, 0, False, rhsGR1)
r.reactor_rhs_isobaric(state_p, p, Tin, yin, tau, 0, 0, 0, 0, 0, 0, False, rhsGR2)
jacFD[:, 0] = (- rhsGR1 + rhsGR2) / (2. * dT)
for i in range(ns - 1):
y_m1, y_p1 = np.copy(y), np.copy(y)
y_m1[i] += - dY
y_m1[-1] -= - dY
y_p1[i] += dY
y_p1[-1] -= dY
state_m = hstack((T, y_m1[:-1]))
state_p = hstack((T, y_p1[:-1]))
r.reactor_rhs_isobaric(state_m, p, Tin, yin, tau, 0, 0, 0, 0, 0, 0, False, rhsGR1)
r.reactor_rhs_isobaric(state_p, p, Tin, yin, tau, 0, 0, 0, 0, 0, 0, False, rhsGR2)
jacFD[:, 1 + i] = (- rhsGR1 + rhsGR2) / (2. * dY)
pass_jac = max(abs(jacGR - jacFD) / (abs(jacGR) + 1.)) < 1.e-2
if not pass_jac:
print('fd:')
for i in range(ns):
for j in range(ns):
print(f'{jacFD[i, j]:12.2e}', end=', ')
print('')
print('gr:')
for i in range(ns):
for j in range(ns):
print(f'{jacGR[i, j]:12.2e}', end=', ')
print('')
print('gr-fd:')
for i in range(ns):
for j in range(ns):
print(f'{(jacGR[i, j] - jacFD[i, j]) / (abs(jacFD[i, j]) + 1.0):12.2e}', end=', ')
print('')
print('')
w = gas.net_production_rates * gas.molecular_weights
h = gas.standard_enthalpies_RT * gas.T * gas_constant / gas.molecular_weights
rhsCN = zeros(ns)
rhsCN[1:] = w[:-1] / gas.density
rhsCN[0] = - sum(w * h) / gas.density / gas.cp_mass
if max(abs(rhsGR - rhsCN) / (abs(rhsCN) + 1.)) > 100. * sqrt(np.finfo(float).eps):
print(rhsGR, rhsCN)
pass_rhs = max(abs(rhsGR - rhsCN) / (abs(rhsCN) + 1.)) < 100. * sqrt(np.finfo(float).eps)
if test_rhs and test_jac:
return pass_rhs and pass_jac
if test_rhs:
return pass_rhs
if test_jac:
return pass_jac
def create_test(m, T, p, test_rhs, test_jac):
def test(self):
self.assertTrue(validate_on_mechanism(m, T, p, test_rhs, test_jac))
return test
class Accuracy(unittest.TestCase):
pass
temperature_dict = {'600K': 600., '1200K': 1200.}
pressure_dict = {'1atm': one_atm, '2atm': 2. * one_atm}
for mech in mechs:
for temperature in temperature_dict:
for pressure in pressure_dict:
rhsname = 'test_rhs_' + mech + '_' + temperature + '_' + pressure
jacname = 'test_jac_' + mech + '_' + temperature + '_' + pressure
setattr(Accuracy, rhsname, create_test(mech, temperature_dict[temperature], pressure_dict[pressure],
test_rhs=True, test_jac=False))
setattr(Accuracy, jacname, create_test(mech, temperature_dict[temperature], pressure_dict[pressure],
test_rhs=False, test_jac=True))
if __name__ == '__main__':
unittest.main()
<file_sep>import pickle
import unittest
from os.path import join, abspath
from numpy.testing import assert_allclose
from tests.time_integration.chemistry_abc_explicit.rebless import run
class Test(unittest.TestCase):
def test(self):
output = run()
gold_file = abspath(join('tests',
'time_integration',
'chemistry_abc_explicit',
'gold.pkl'))
with open(gold_file, 'rb') as gold_input:
gold_output = pickle.load(gold_input)
self.assertIsNone(assert_allclose(output['t'], gold_output['t'], atol=1.e-8))
self.assertIsNone(assert_allclose(output['sol'], gold_output['sol'], atol=1.e-8))
if __name__ == '__main__':
unittest.main()
<file_sep>from multiprocessing.sharedctypes import Value
import cantera
def check(qual, major, minor, patch=None):
"""Check cantera version, specify qualifier as one of ["pre", "at", "atleast", "post"] and major/minor/patch version numbers, using None to ignore a level of precision (default for patch is None to ignore)"""
patch = 0 if patch is None else patch
minor = 0 if minor is None else minor
if major is None:
raise ValueError('Invalid major version, None, for cantera version check.')
check_version = major * 100 + minor * 10 + patch
cv_split = [int(a) for a in cantera.__version__.split('.') if a.isdigit()]
cv_patch = 0 if patch is None else cv_split[2]
cv_minor = 0 if minor is None else cv_split[1]
cv = 100 * cv_split[0] + 10 * cv_minor + cv_patch
if qual == 'pre':
return cv < check_version
elif qual == 'at':
return cv == check_version
elif qual == 'atleast':
return cv >= check_version
elif qual == 'post':
return cv > check_version
else:
raise ValueError(f'Invalid qualification {qual} for cantera version check, must be one of ["pre", "at", "atleast", "post"].')
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
#include "combustion_kernels.h"
#include <cmath>
#include <iostream>
#define GRIFFON_SUM2(prop) (prop(0) + prop(1))
#define GRIFFON_SUM3(prop) (GRIFFON_SUM2(prop) + prop(2))
#define GRIFFON_SUM4(prop) (GRIFFON_SUM3(prop) + prop(3))
#define GRIFFON_SUM5(prop) (GRIFFON_SUM4(prop) + prop(4))
#define GRIFFON_SUM6(prop) (GRIFFON_SUM5(prop) + prop(5))
#define GRIFFON_SUM7(prop) (GRIFFON_SUM6(prop) + prop(6))
#define GRIFFON_SUM8(prop) (GRIFFON_SUM7(prop) + prop(7))
#define ARRHENIUS(coef) ((coef)[0] * std::exp((coef)[1] * logT - (coef)[2] * invT))
#define THD_BDY(i) (tb_efficiencies[(i)] * y[tb_indices[(i)]])
#define GIBBS(i) (net_stoich[(i)] * specG[net_indices[(i)]])
namespace griffon
{
void CombustionKernels::production_rates(const double &temperature, const double &density, const double *y,
double *out_prodrates) const
{
production_rates(temperature, density, mixture_molecular_weight(y), y, out_prodrates);
}
void CombustionKernels::production_rates(const double &temperature, const double &density, const double &mmw,
const double *y, double *out_prodrates) const
{
const auto T = temperature;
const auto invT = 1 / T;
const auto logT = std::log(T);
const auto rho = density;
const auto conc = rho / mmw;
const auto nSpec = mechanismData.phaseData.nSpecies;
const auto nRxns = mechanismData.reactionData.nReactions;
const auto standardStatePressure = mechanismData.phaseData.referencePressure;
const auto invGasConstant = 1. / mechanismData.phaseData.Ru;
const auto port = standardStatePressure * invT * invGasConstant;
for (int i = 0; i < nSpec; ++i)
{
out_prodrates[i] = 0.;
}
double specG[nSpec];
for (int n = 0; n < nSpec; ++n)
{
const auto polyType = mechanismData.heatCapacityData.types[n];
const auto &c = mechanismData.heatCapacityData.coefficients[n];
const auto &c9 = mechanismData.heatCapacityData.nasa9Coefficients[n];
switch (polyType)
{
case CpType::NASA7:
if (T <= c[0])
{
specG[n] = c[13] + T * (c[8] - c[14] - c[8] * logT - T * (c[9] + T * (c[10] + T * (c[11] + T * c[12]))));
}
else
{
specG[n] = c[6] + T * (c[1] - c[7] - c[1] * logT - T * (c[2] + T * (c[3] + T * (c[4] + T * c[5]))));
}
break;
case CpType::NASA9:
{
const auto nregions = static_cast<int>(c9[0]);
for(int k=0; k<nregions; ++k)
{
const int region_start_idx = 1 + k * 11;
if(T < c9[region_start_idx + 1] && T > c9[region_start_idx])
{
const auto *a = &(c9[region_start_idx + 2]);
specG[n] = a[7] - 0.5 * a[0] * invT + a[1] * (logT + 1.0) - T * (a[2] * (logT - 1.0) + a[8] + T * (0.5 * a[3] + T * (0.1666666666666666 * a[4] + T * (0.0833333333333333 * a[5] + T * 0.05 * a[6]))));
break;
}
}
}
break;
case CpType::CONST:
specG[n] = c[1] + c[3] * (T - c[0]) - T * (c[2] + c[3] * (logT - log(c[0])));
break;
default:
{
throw std::runtime_error("unsupported thermo");
}
}
}
double k = 0;
double kr;
double m;
double pr;
double logPrC;
double logFCent;
for (int r = 0; r < nRxns; ++r)
{
const auto &rxnData = mechanismData.reactionData.reactions[r];
const auto &tb_indices = rxnData.tb_indices;
const auto &tb_efficiencies = rxnData.tb_efficiencies;
const auto n_tb = rxnData.n_tb;
const auto &rc_indices = rxnData.reactant_indices;
const auto &rc_stoich = rxnData.reactant_stoich;
const auto &rc_invmw = rxnData.reactant_invmw;
const auto n_rc = rxnData.n_reactants;
const auto &pd_indices = rxnData.product_indices;
const auto &pd_stoich = rxnData.product_stoich;
const auto &pd_invmw = rxnData.product_invmw;
const auto n_pd = rxnData.n_products;
const auto &sp_indices = rxnData.special_indices;
const auto &sp_order = rxnData.special_orders;
const auto &sp_invmw = rxnData.special_invmw;
const auto &sp_nonzero = rxnData.special_nonzero;
const auto n_sp = rxnData.n_special;
const auto &net_indices = rxnData.net_indices;
const auto &net_stoich = rxnData.net_stoich;
const auto &net_mw = rxnData.net_mw;
const auto n_net = rxnData.n_net;
const auto &kCoefs = rxnData.kFwdCoefs;
const auto &kPCoefs = rxnData.kPressureCoefs;
const auto baseEff = rxnData.thdBdyDefault;
const auto &troe = rxnData.troeParams;
switch (rxnData.kForm)
{
case RateConstantTForm::CONSTANT:
k = kCoefs[0];
break;
case RateConstantTForm::LINEAR:
k = kCoefs[0] * T;
break;
case RateConstantTForm::QUADRATIC:
k = kCoefs[0] * T * T;
break;
case RateConstantTForm::RECIPROCAL:
k = kCoefs[0] * invT;
break;
case RateConstantTForm::ARRHENIUS:
k = ARRHENIUS(kCoefs);
break;
}
switch (rxnData.type)
{
case RateType::SIMPLE:
break;
case RateType::THIRD_BODY:
switch (n_tb)
{
case 0:
k *= baseEff * conc;
break;
case 1:
k *= (baseEff * conc + rho * (THD_BDY(0)));
break;
case 2:
k *= (baseEff * conc + rho * (GRIFFON_SUM2(THD_BDY)));
break;
case 3:
k *= (baseEff * conc + rho * (GRIFFON_SUM3(THD_BDY)));
break;
case 4:
k *= (baseEff * conc + rho * (GRIFFON_SUM4(THD_BDY)));
break;
case 5:
k *= (baseEff * conc + rho * (GRIFFON_SUM5(THD_BDY)));
break;
case 6:
k *= (baseEff * conc + rho * (GRIFFON_SUM6(THD_BDY)));
break;
case 7:
k *= (baseEff * conc + rho * (GRIFFON_SUM7(THD_BDY)));
break;
case 8:
k *= (baseEff * conc + rho * (GRIFFON_SUM8(THD_BDY)));
break;
default:
m = baseEff * conc + rho * (GRIFFON_SUM8(THD_BDY));
for (int i = 8; i != n_tb; ++i)
m += rho * THD_BDY(i);
k *= m;
break;
}
break;
case RateType::LINDEMANN:
switch (n_tb)
{
case 0:
k /= (1 + k / (ARRHENIUS(kPCoefs) * (baseEff * conc)));
break;
case 1:
k /= (1 + k / (ARRHENIUS(kPCoefs) * (baseEff * conc + rho * (THD_BDY(0)))));
break;
case 2:
k /= (1 + k / (ARRHENIUS(kPCoefs) * (baseEff * conc + rho * (GRIFFON_SUM2(THD_BDY)))));
break;
case 3:
k /= (1 + k / (ARRHENIUS(kPCoefs) * (baseEff * conc + rho * (GRIFFON_SUM3(THD_BDY)))));
break;
case 4:
k /= (1 + k / (ARRHENIUS(kPCoefs) * (baseEff * conc + rho * (GRIFFON_SUM4(THD_BDY)))));
break;
case 5:
k /= (1 + k / (ARRHENIUS(kPCoefs) * (baseEff * conc + rho * (GRIFFON_SUM5(THD_BDY)))));
break;
case 6:
k /= (1 + k / (ARRHENIUS(kPCoefs) * (baseEff * conc + rho * (GRIFFON_SUM6(THD_BDY)))));
break;
case 7:
k /= (1 + k / (ARRHENIUS(kPCoefs) * (baseEff * conc + rho * (GRIFFON_SUM7(THD_BDY)))));
break;
case 8:
k /= (1 + k / (ARRHENIUS(kPCoefs) * (baseEff * conc + rho * (GRIFFON_SUM8(THD_BDY)))));
break;
default:
m = baseEff * conc + rho * (GRIFFON_SUM8(THD_BDY));
for (int i = 8; i != n_tb; ++i)
m += rho * THD_BDY(i);
k /= (1 + k / (ARRHENIUS(kPCoefs) * m));
break;
}
break;
case RateType::TROE:
switch (n_tb)
{
case 0:
pr = ARRHENIUS(kPCoefs) / k * (baseEff * conc);
break;
case 1:
pr = ARRHENIUS(kPCoefs) / k * (baseEff * conc + rho * (THD_BDY(0)));
break;
case 2:
pr = ARRHENIUS(kPCoefs) / k * (baseEff * conc + rho * (GRIFFON_SUM2(THD_BDY)));
break;
case 3:
pr = ARRHENIUS(kPCoefs) / k * (baseEff * conc + rho * (GRIFFON_SUM3(THD_BDY)));
break;
case 4:
pr = ARRHENIUS(kPCoefs) / k * (baseEff * conc + rho * (GRIFFON_SUM4(THD_BDY)));
break;
case 5:
pr = ARRHENIUS(kPCoefs) / k * (baseEff * conc + rho * (GRIFFON_SUM5(THD_BDY)));
break;
case 6:
pr = ARRHENIUS(kPCoefs) / k * (baseEff * conc + rho * (GRIFFON_SUM6(THD_BDY)));
break;
case 7:
pr = ARRHENIUS(kPCoefs) / k * (baseEff * conc + rho * (GRIFFON_SUM7(THD_BDY)));
break;
case 8:
pr = ARRHENIUS(kPCoefs) / k * (baseEff * conc + rho * (GRIFFON_SUM8(THD_BDY)));
break;
default:
m = baseEff * conc + rho * (GRIFFON_SUM8(THD_BDY));
for (int i = 8; i != n_tb; ++i)
m += rho * THD_BDY(i);
pr = ARRHENIUS(kPCoefs) / k * m;
break;
}
switch (rxnData.troeForm)
{
case TroeTermsPresent::T123:
logFCent = std::log10(
(1 - troe[0]) * std::exp(-T / troe[1]) + troe[0] * std::exp(-T / troe[2]) + std::exp(-invT * troe[3]));
break;
case TroeTermsPresent::T12:
logFCent = std::log10((1 - troe[0]) * std::exp(-T / troe[1]) + troe[0] * std::exp(-T / troe[2]) + 0.0);
break;
case TroeTermsPresent::T1:
logFCent = std::log10((1 - troe[0]) * std::exp(-T / troe[1]) + 0.0 + 0.0);
break;
case TroeTermsPresent::T23:
logFCent = std::log10(0.0 + troe[0] * std::exp(-T / troe[2]) + std::exp(-invT * troe[3]));
break;
case TroeTermsPresent::T2:
logFCent = std::log10(0.0 + troe[0] * std::exp(-T / troe[2]) + 0.0);
break;
case TroeTermsPresent::T13:
logFCent = std::log10((1 - troe[0]) * std::exp(-T / troe[1]) + 0.0 + std::exp(-invT * troe[3]));
break;
case TroeTermsPresent::T3:
logFCent = std::log10(0.0 + 0.0 + std::exp(-invT * troe[3]));
break;
case TroeTermsPresent::NO_TROE_TERMS:
default:
{
throw std::runtime_error("no troe Terms flagged for evaluation");
}
}
#define CTROE (-0.4 - 0.67 * logFCent)
#define NTROE (0.75 - 1.27 * logFCent)
#define F1 (logPrC / (NTROE - 0.14 * logPrC))
logPrC = std::log10(std::max(pr, 1.e-300)) + CTROE;
k = k * std::pow(10, logFCent / (1 + F1 * F1)) * pr / (1 + pr);
break;
default:
{
throw std::runtime_error("unidentified reaction");
}
}
#undef CTROE
#undef NTROE
#undef F1
if (rxnData.hasOrders)
{
#define C_S(i) (y[sp_indices[i]] * rho * sp_invmw[i])
for (int i = 0; i < n_sp; ++i)
{
if (sp_nonzero[i])
{
k *= std::pow(std::max(C_S(i), 0.), sp_order[i]);
}
}
kr = 0.;
#undef C_S
}
else
{
kr = 0.;
if (rxnData.reversible)
{
switch (n_net)
{
case 3:
kr = k * std::exp(rxnData.sumStoich * std::log(port) - invT * invGasConstant * (GRIFFON_SUM3(GIBBS)));
break;
case 2:
kr = k * std::exp(rxnData.sumStoich * std::log(port) - invT * invGasConstant * (GRIFFON_SUM2(GIBBS)));
break;
case 4:
kr = k * std::exp(rxnData.sumStoich * std::log(port) - invT * invGasConstant * (GRIFFON_SUM4(GIBBS)));
break;
case 5:
kr = k * std::exp(rxnData.sumStoich * std::log(port) - invT * invGasConstant * (GRIFFON_SUM5(GIBBS)));
break;
case 6:
kr = k * std::exp(rxnData.sumStoich * std::log(port) - invT * invGasConstant * (GRIFFON_SUM6(GIBBS)));
break;
case 7:
kr = k * std::exp(rxnData.sumStoich * std::log(port) - invT * invGasConstant * (GRIFFON_SUM7(GIBBS)));
break;
case 8:
kr = k * std::exp(rxnData.sumStoich * std::log(port) - invT * invGasConstant * (GRIFFON_SUM8(GIBBS)));
break;
}
}
#define C_R(i) (y[rc_indices[i]] * rho * rc_invmw[i])
#define C_P(i) (y[pd_indices[i]] * rho * pd_invmw[i])
switch (rxnData.forwardOrder)
{
case ReactionOrder::ONE:
k *= C_R(0);
break;
case ReactionOrder::TWO:
k *= C_R(0) * C_R(0);
break;
case ReactionOrder::ONE_ONE:
k *= C_R(0) * C_R(1);
break;
case ReactionOrder::ONE_ONE_ONE:
k *= C_R(0) * C_R(1) * C_R(2);
break;
case ReactionOrder::TWO_ONE:
k *= C_R(0) * C_R(0) * C_R(1);
break;
case ReactionOrder::ONE_TWO:
k *= C_R(0) * C_R(1) * C_R(1);
break;
default:
for (int i = 0; i < n_rc; ++i)
{
switch (rc_stoich[i])
{
case 1:
k *= C_R(i);
break;
case 2:
k *= C_R(i) * C_R(i);
break;
case 3:
k *= C_R(i) * C_R(i) * C_R(i);
break;
}
}
break;
}
if (rxnData.reversible)
{
switch (rxnData.reverseOrder)
{
case ReactionOrder::ONE:
kr *= C_P(0);
break;
case ReactionOrder::TWO:
kr *= C_P(0) * C_P(0);
break;
case ReactionOrder::ONE_ONE:
kr *= C_P(0) * C_P(1);
break;
case ReactionOrder::ONE_ONE_ONE:
kr *= C_P(0) * C_P(1) * C_P(2);
break;
case ReactionOrder::TWO_ONE:
kr *= C_P(0) * C_P(0) * C_P(1);
break;
case ReactionOrder::ONE_TWO:
kr *= C_P(0) * C_P(1) * C_P(1);
break;
default:
for (int i = 0; i < n_pd; ++i)
{
switch (pd_stoich[i])
{
case -1:
kr *= C_P(i);
break;
case -2:
kr *= C_P(i) * C_P(i);
break;
case -3:
kr *= C_P(i) * C_P(i) * C_P(i);
break;
}
}
break;
}
}
#undef C_R
#undef C_P
}
for (int i = 0; i < n_net; ++i)
{
const auto idx = net_indices[i];
out_prodrates[idx] -= net_stoich[i] * net_mw[i] * (k - kr);
}
}
}
void CombustionKernels::prod_rates_primitive_sensitivities(const double &density, const double &temperature,
const double *y, int rates_sensitivity_option,
double *out_prodratessens) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
double prod_rates[nSpec];
switch (rates_sensitivity_option)
{
case 1:
prod_rates_sens_no_tbaf(temperature, density, mixture_molecular_weight(y), y, prod_rates, out_prodratessens);
break;
case 0:
prod_rates_sens_exact(temperature, density, mixture_molecular_weight(y), y, prod_rates, out_prodratessens);
break;
case 2:
prod_rates_sens_sparse(temperature, density, mixture_molecular_weight(y), y, prod_rates, out_prodratessens);
break;
}
}
} // namespace griffon
<file_sep>from spitfire.chemistry.flamelet2d import _Flamelet2D
from spitfire.chemistry.flamelet import Flamelet
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.time.integrator import Governor, NumberOfTimeSteps, FinalTime, Steady, SaveAllDataToList
from spitfire.time.methods import AdaptiveERK54CashKarp, ESDIRK64, BackwardEulerWithError
from spitfire.time.nonlinear import SimpleNewtonSolver
from spitfire.time.stepcontrol import PIController
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d as a3
from scipy.interpolate import RectBivariateSpline
# m = ChemicalMechanismSpec(cantera_xml='methane-lu30.xml', group_name='methane-lu30')
# m = ChemicalMechanismSpec(cantera_xml='h2-burke.xml', group_name='h2-burke')
# m = ChemicalMechanismSpec(cantera_xml='coh2-hawkes.xml', group_name='coh2-hawkes')
m = ChemicalMechanismSpec(cantera_xml='heptane-liu-hewson-chen-pitsch-highT.xml', group_name='gas')
# m = ChemicalMechanismSpec(cantera_xml='dme-bhagatwala.xml', group_name='dme-bhagatwala')
# m = ChemicalMechanismSpec(cantera_xml='ethylene-luo.xml', group_name='ethylene-luo')
pressure = 101325.
print(m.n_species, m.n_reactions)
air = m.stream(stp_air=True)
air.TP = 300., pressure
n2 = m.stream('X', 'N2:1')
c7 = m.stream('X', 'NXC7H16:1')
# dme = m.stream('X', 'CH3OCH3:1')
# ch4 = m.stream('X', 'CH4:1')
# sg = m.stream('X', 'H2:1, CO:2')
sg = m.stream('X', 'H2:1, CO:1, CH4:1, CO2:1')
# eg = m.stream('X', 'CO2:1, H2O:1, CO:0.5, H2:0.001')
# c2h4 = m.stream('X', 'C2H4:1')
# fuel1 = m.mix_fuels_for_stoich_mixture_fraction(sg, n2, 0.1, air)
fuel1 = m.copy_stream(c7)
fuel1.TP = 485., pressure
# fuel1 = m.stream(stp_air=True)
# fuel1.TP = 1000., pressure
# fuel2 = m.mix_fuels_for_stoich_mixture_fraction(c2h4, n2, 0.2, air)
fuel2 = m.copy_stream(sg)
fuel2.TP = 400., pressure
# fuel2 = m.copy_stream(eg)
# fuel2.TP = 1000., pressure
x_cp = m.stoich_mixture_fraction(fuel2, air)
y_cp = m.stoich_mixture_fraction(fuel1, air)
x_cp = x_cp if x_cp < 0.5 else 1. - x_cp
y_cp = y_cp if y_cp < 0.5 else 1. - y_cp
print(x_cp, y_cp)
x_cc = 6.
y_cc = 6.
def make_clustered_grid(nx, ny, x_cp, y_cp, x_cc, y_cc):
x_half1 = Flamelet._clustered_grid(nx // 2, x_cp * 2., x_cc)[0] * 0.5
y_half1 = Flamelet._clustered_grid(nx // 2, y_cp * 2., y_cc)[0] * 0.5
x_half2 = (0.5 - x_half1)[::-1]
y_half2 = (0.5 - y_half1)[::-1]
x_range = np.hstack((x_half1, 0.5 + x_half2))
y_range = np.hstack((y_half1, 0.5 + y_half2))
dx_mid = x_range[nx // 2 - 1] - x_range[nx // 2 - 2]
x_range[nx // 2 - 1] -= dx_mid / 3.
x_range[nx // 2 + 0] += dx_mid / 3.
dy_mid = y_range[ny // 2 - 1] - y_range[ny // 2 - 2]
y_range[ny // 2 - 1] -= dy_mid / 3.
y_range[ny // 2 + 0] += dy_mid / 3.
return x_range, y_range
# x_range, y_range = make_clustered_grid(nx, ny, x_cp, y_cp, x_cc, y_cc)
nx = 24
ny = nx
# x_range = Flamelet._uniform_grid(nx)[0]
# y_range = Flamelet._uniform_grid(ny)[0]
x_range, y_range = make_clustered_grid(nx, ny, x_cp, y_cp, x_cc, y_cc)
x_grid, y_grid = np.meshgrid(x_range, y_range)
f = _Flamelet2D(m, 'equilibrium', pressure, air, fuel1, fuel2, 10., 10., grid_1=x_range, grid_2=y_range)
# air_hot = m.copy_stream(air)
# air_hot.TP = 1400., pressure
# air_cool = m.copy_stream(air)
# air_cool.TP = 800., pressure
# dmech4 = m.mix_fuels_for_stoich_mixture_fraction(m.stream('X', 'CH3OCH3:1, CH4:1'), n2, 0.2, air_hot)
# dmech4.TP = 300., pressure
# f = Flamelet2D(m, 'unreacted', pressure, dmech4, air_cool, air_hot, 1., 1., grid_1=x_range, grid_2=y_range)
# ethy = m.stream('TPX', (300., pressure, 'C2H4:1'))
# coh2 = m.stream('TPX', (300., pressure, 'CO:1, H2:0.01'))
# f = Flamelet2D(m, 'equilibrium', pressure, air, ethy, coh2, 0.1, 0.1, grid_1=x_range, grid_2=y_range)
phi0 = np.copy(f._initial_state)
g = Governor()
g.log_rate = 25
g.termination_criteria = Steady(1.e-6)
g.clip_to_positive = True
g.norm_weighting = 1. / f._variable_scales
g.projector_setup_rate = 20
g.time_step_increase_factor_to_force_jacobian = 1.1
g.time_step_decrease_factor_to_force_jacobian = 0.8
data = SaveAllDataToList(initial_solution=phi0,
save_frequency=100,
file_prefix='ip',
file_first_and_last_only=True,
save_first_and_last_only=True)
g.custom_post_process_step = data.save_data
newton = SimpleNewtonSolver(evaluate_jacobian_every_iter=False,
norm_weighting=g.norm_weighting,
tolerance=1.e-10,
max_nonlinear_iter=8)
esdirk = ESDIRK64(norm_weighting=g.norm_weighting, nonlinear_solver=newton)
# esdirk = BackwardEulerWithError(norm_weighting=g.norm_weighting, nonlinear_solver=newton)
pi = PIController(first_step=1.e-6, target_error=1.e-8, max_step=1.e0)
# phi = g.integrate(right_hand_side=f.rhs,
# projector_setup=f.block_Jacobi_setup,
# projector_solve=f.block_Jacobi_solve,
# initial_condition=phi0,
# method=esdirk,
# controller=pi)[1]
# phi = g.integrate(right_hand_side=f.rhs,
# projector_setup=f.block_Jacobi_setup,
# projector_solve=f.block_Jacobi_prec_bicgstab_solve,
# initial_condition=phi0,
# method=esdirk,
# controller=pi)[1]
# phi = g.integrate(right_hand_side=f.rhs,
# initial_condition=phi0,
# method=AdaptiveERK54CashKarp(),
# controller=PIController(first_step=1.e-8, target_error=1.e-4))[1]
# np.save('t_sg_heptane_24.npy', data.t_list)
# np.save('q_sg_heptane_24.npy', data.solution_list)
# iq = 0
# nq = f._n_equations
# phi02d = phi0[iq::nq].reshape((ny, nx), order='F')
# phi2d = phi[iq::nq].reshape((ny, nx), order='F')
# rhs2d = f.rhs(0, phi)[iq::nq].reshape((ny, nx), order='F')
# phimphi02d = phi2d - phi02d
# c1 = f._state_1
# c2 = f._state_2
# c3 = f._state_3
# # second solve begin
#
# nx_1 = np.copy(nx)
# ny_1 = np.copy(nx)
# x_range1 = np.copy(x_range)
# y_range1 = np.copy(y_range)
# x_grid1, y_grid1 = np.meshgrid(x_range1, y_range1)
#
# nx = 42
# ny = nx
# # x_range = Flamelet._uniform_grid(nx)[0]
# # y_range = Flamelet._uniform_grid(ny)[0]
# x_range, y_range = make_clustered_grid(nx, ny, x_cp, y_cp, x_cc, y_cc)
# x_grid, y_grid = np.meshgrid(x_range, y_range)
#
# t_list1 = np.load('t_sg_heptane_24.npy')
# q_list1 = np.load('q_sg_heptane_24.npy')
#
# nt1 = t_list1.size
# ndof1 = q_list1.size // nt1
# nq = ndof1 // nx_1 // ny_1
#
# phi1d_2 = np.zeros(nq * nx * ny)
#
# for iq in range(nq):
# if nt1 == 1:
# phi2d_1 = q_list1[iq::nq].reshape((ny_1, nx_1), order='F')
# else:
# phi2d_1 = q_list1[-1, iq::nq].reshape((ny_1, nx_1), order='F')
# spl = RectBivariateSpline(x_range1, y_range1, phi2d_1, kx=1, ky=1)
# phi1d_2[iq::nq] = spl.ev(x_grid.ravel(), y_grid.ravel())
#
# f = Flamelet2D(m, phi1d_2, pressure, air, fuel1, fuel2, 10., 10., grid_1=x_range, grid_2=y_range)
#
# # air_hot = m.copy_stream(air)
# # air_hot.TP = 1400., pressure
# # air_cool = m.copy_stream(air)
# # air_cool.TP = 800., pressure
# # dmech4 = m.mix_fuels_for_stoich_mixture_fraction(m.stream('X', 'CH3OCH3:1, CH4:1'), n2, 0.2, air_hot)
# # dmech4.TP = 300., pressure
# # f = Flamelet2D(m, 'unreacted', pressure, dmech4, air_cool, air_hot, 1., 1., grid_1=x_range, grid_2=y_range)
#
# # ethy = m.stream('TPX', (300., pressure, 'C2H4:1'))
# # coh2 = m.stream('TPX', (300., pressure, 'CO:1, H2:0.01'))
# # f = Flamelet2D(m, 'equilibrium', pressure, air, ethy, coh2, 0.1, 0.1, grid_1=x_range, grid_2=y_range)
#
# phi0 = np.copy(f._initial_state)
#
# g = Governor()
# g.log_rate = 200
# g.termination_criteria = Steady(1.e-6)
# g.clip_to_positive = True
# g.norm_weighting = 1. / f._variable_scales
# g.projector_setup_rate = 20
# g.time_step_increase_factor_to_force_jacobian = 1.1
# g.time_step_decrease_factor_to_force_jacobian = 0.8
# data = SaveAllDataToList(initial_solution=phi0,
# save_frequency=100,
# file_prefix='ip',
# file_first_and_last_only=True,
# save_first_and_last_only=True)
# g.custom_post_process_step = data.save_data
# newton = SimpleNewtonSolver(evaluate_jacobian_every_iter=False,
# norm_weighting=g.norm_weighting,
# tolerance=1.e-10,
# max_nonlinear_iter=8)
# esdirk = ESDIRK64(norm_weighting=g.norm_weighting, nonlinear_solver=newton)
# # esdirk = BackwardEulerWithError(norm_weighting=g.norm_weighting, nonlinear_solver=newton)
# pi = PIController(first_step=1.e-6, target_error=1.e-8, max_step=1.e0)
# # phi = g.integrate(right_hand_side=f.rhs,
# # projector_setup=f.block_Jacobi_setup,
# # projector_solve=f.block_Jacobi_solve,
# # initial_condition=phi0,
# # method=esdirk,
# # controller=pi)[1]
# phi = g.integrate(right_hand_side=f.rhs,
# projector_setup=f.block_Jacobi_setup,
# projector_solve=f.block_Jacobi_prec_bicgstab_solve,
# initial_condition=phi0,
# method=esdirk,
# controller=pi)[1]
# # phi = g.integrate(right_hand_side=f.rhs,
# # initial_condition=phi0,
# # method=AdaptiveERK54CashKarp(),
# # controller=PIController(first_step=1.e-8, target_error=1.e-4))[1]
# np.save('t_sg_heptane_42.npy', data.t_list)
# np.save('q_sg_heptane_42.npy', data.solution_list)
# iq = 0
# nq = f._n_equations
# phi02d = phi0[iq::nq].reshape((ny, nx), order='F')
# phi2d = phi[iq::nq].reshape((ny, nx), order='F')
# rhs2d = f.rhs(0, phi)[iq::nq].reshape((ny, nx), order='F')
# phimphi02d = phi2d - phi02d
# c1 = f._state_1
# c2 = f._state_2
# c3 = f._state_3
#
# # second solve end
#
#
# # second solve begin
#
# nx_2 = np.copy(nx)
# ny_2 = np.copy(nx)
# x_range2 = np.copy(x_range)
# y_range2 = np.copy(y_range)
# x_grid2, y_grid2 = np.meshgrid(x_range2, y_range2)
#
# nx = 54
# ny = nx
# # x_range = Flamelet._uniform_grid(nx)[0]
# # y_range = Flamelet._uniform_grid(ny)[0]
# x_range, y_range = make_clustered_grid(nx, ny, x_cp, y_cp, x_cc, y_cc)
# x_grid, y_grid = np.meshgrid(x_range, y_range)
#
# t_list2 = np.load('t_sg_eg_36.npy')
# q_list2 = np.load('q_sg_eg_36.npy')
#
# nt2 = t_list2.size
# ndof2 = q_list2.size // nt2
# nq = ndof2 // nx_2 // ny_2
#
# phi1d_3 = np.zeros(nq * nx * ny)
#
# for iq in range(nq):
# if nt2 == 1:
# phi2d_2 = q_list2[iq::nq].reshape((ny_2, nx_2), order='F')
# else:
# phi2d_2 = q_list2[-1, iq::nq].reshape((ny_2, nx_2), order='F')
# spl = RectBivariateSpline(x_range2, y_range2, phi2d_2, kx=1, ky=1)
# phi1d_3[iq::nq] = spl.ev(x_grid.ravel(), y_grid.ravel())
#
# f = Flamelet2D(m, phi1d_3, pressure, air, fuel1, fuel2, 10., 10., grid_1=x_range, grid_2=y_range)
#
# # air_hot = m.copy_stream(air)
# # air_hot.TP = 1400., pressure
# # air_cool = m.copy_stream(air)
# # air_cool.TP = 800., pressure
# # dmech4 = m.mix_fuels_for_stoich_mixture_fraction(m.stream('X', 'CH3OCH3:1, CH4:1'), n2, 0.2, air_hot)
# # dmech4.TP = 300., pressure
# # f = Flamelet2D(m, 'unreacted', pressure, dmech4, air_cool, air_hot, 1., 1., grid_1=x_range, grid_2=y_range)
#
# # ethy = m.stream('TPX', (300., pressure, 'C2H4:1'))
# # coh2 = m.stream('TPX', (300., pressure, 'CO:1, H2:0.01'))
# # f = Flamelet2D(m, 'equilibrium', pressure, air, ethy, coh2, 0.1, 0.1, grid_1=x_range, grid_2=y_range)
#
# phi0 = np.copy(f._initial_state)
#
# g = Governor()
# g.log_rate = 200
# g.termination_criteria = Steady(1.e-6)
# g.clip_to_positive = True
# g.norm_weighting = 1. / f._variable_scales
# g.projector_setup_rate = 20
# g.time_step_increase_factor_to_force_jacobian = 1.1
# g.time_step_decrease_factor_to_force_jacobian = 0.8
# data = SaveAllDataToList(initial_solution=phi0,
# save_frequency=100,
# file_prefix='ip',
# file_first_and_last_only=True,
# save_first_and_last_only=True)
# g.custom_post_process_step = data.save_data
# newton = SimpleNewtonSolver(evaluate_jacobian_every_iter=False,
# norm_weighting=g.norm_weighting,
# tolerance=1.e-10,
# max_nonlinear_iter=8)
# esdirk = ESDIRK64(norm_weighting=g.norm_weighting, nonlinear_solver=newton)
# # esdirk = BackwardEulerWithError(norm_weighting=g.norm_weighting, nonlinear_solver=newton)
# pi = PIController(first_step=1.e-6, target_error=1.e-8, max_step=1.e0)
# # phi = g.integrate(right_hand_side=f.rhs,
# # projector_setup=f.block_Jacobi_setup,
# # projector_solve=f.block_Jacobi_solve,
# # initial_condition=phi0,
# # method=esdirk,
# # controller=pi)[1]
# phi = g.integrate(right_hand_side=f.rhs,
# projector_setup=f.block_Jacobi_setup,
# projector_solve=f.block_Jacobi_prec_bicgstab_solve,
# initial_condition=phi0,
# method=esdirk,
# controller=pi)[1]
# # phi = g.integrate(right_hand_side=f.rhs,
# # initial_condition=phi0,
# # method=AdaptiveERK54CashKarp(),
# # controller=PIController(first_step=1.e-8, target_error=1.e-4))[1]
# np.save('t_sg_eg_54.npy', data.t_list)
# np.save('q_sg_eg_54.npy', data.solution_list)
# iq = 0
# nq = f._n_equations
# phi02d = phi0[iq::nq].reshape((ny, nx), order='F')
# phi2d = phi[iq::nq].reshape((ny, nx), order='F')
# rhs2d = f.rhs(0, phi)[iq::nq].reshape((ny, nx), order='F')
# phimphi02d = phi2d - phi02d
# c1 = f._state_1
# c2 = f._state_2
# c3 = f._state_3
#
# # second solve end
# second solve begin
nx_3 = np.copy(nx)
ny_3 = np.copy(nx)
x_range3 = np.copy(x_range)
y_range3 = np.copy(y_range)
x_grid3, y_grid3 = np.meshgrid(x_range3, y_range3)
nx = 64
ny = nx
# x_range = Flamelet._uniform_grid(nx)[0]
# y_range = Flamelet._uniform_grid(ny)[0]
x_range, y_range = make_clustered_grid(nx, ny, x_cp, y_cp, x_cc, y_cc)
x_grid, y_grid = np.meshgrid(x_range, y_range)
t_list3 = np.load('t_sg_heptane_24.npy')
q_list3 = np.load('q_sg_heptane_24.npy')
nt3 = t_list3.size
ndof3 = q_list3.size // nt3
nq = ndof3 // nx_3 // ny_3
phi1d_4 = np.zeros(nq * nx * ny)
for iq in range(nq):
if nt3 == 1:
phi2d_3 = q_list3[iq::nq].reshape((ny_3, nx_3), order='F')
else:
phi2d_3 = q_list3[-1, iq::nq].reshape((ny_3, nx_3), order='F')
spl = RectBivariateSpline(x_range3, y_range3, phi2d_3, kx=1, ky=1)
phi1d_4[iq::nq] = spl.ev(x_grid.ravel(), y_grid.ravel())
f = _Flamelet2D(m, phi1d_4, pressure, air, fuel1, fuel2, 10., 10., grid_1=x_range, grid_2=y_range)
# air_hot = m.copy_stream(air)
# air_hot.TP = 1400., pressure
# air_cool = m.copy_stream(air)
# air_cool.TP = 800., pressure
# dmech4 = m.mix_fuels_for_stoich_mixture_fraction(m.stream('X', 'CH3OCH3:1, CH4:1'), n2, 0.2, air_hot)
# dmech4.TP = 300., pressure
# f = Flamelet2D(m, 'unreacted', pressure, dmech4, air_cool, air_hot, 1., 1., grid_1=x_range, grid_2=y_range)
# ethy = m.stream('TPX', (300., pressure, 'C2H4:1'))
# coh2 = m.stream('TPX', (300., pressure, 'CO:1, H2:0.01'))
# f = Flamelet2D(m, 'equilibrium', pressure, air, ethy, coh2, 0.1, 0.1, grid_1=x_range, grid_2=y_range)
phi0 = np.copy(f._initial_state)
g = Governor()
g.log_rate = 25
g.termination_criteria = Steady(1.e-6)
g.clip_to_positive = True
g.norm_weighting = 1. / f._variable_scales
g.projector_setup_rate = 20
g.time_step_increase_factor_to_force_jacobian = 1.1
g.time_step_decrease_factor_to_force_jacobian = 0.8
data = SaveAllDataToList(initial_solution=phi0,
save_frequency=100,
file_prefix='ip',
file_first_and_last_only=True,
save_first_and_last_only=True)
g.custom_post_process_step = data.save_data
newton = SimpleNewtonSolver(evaluate_jacobian_every_iter=False,
norm_weighting=g.norm_weighting,
tolerance=1.e-10,
max_nonlinear_iter=8)
esdirk = ESDIRK64(norm_weighting=g.norm_weighting, nonlinear_solver=newton)
# esdirk = BackwardEulerWithError(norm_weighting=g.norm_weighting, nonlinear_solver=newton)
pi = PIController(first_step=1.e-6, target_error=1.e-8, max_step=1.e0)
# phi = g.integrate(right_hand_side=f.rhs,
# projector_setup=f.block_Jacobi_setup,
# projector_solve=f.block_Jacobi_solve,
# initial_condition=phi0,
# method=esdirk,
# controller=pi)[1]
phi = g.integrate(right_hand_side=f.rhs,
linear_setup=f.block_Jacobi_setup,
linear_solve=f.block_Jacobi_prec_bicgstab_solve,
initial_condition=phi0,
method=esdirk,
controller=pi)[1]
# phi = g.integrate(right_hand_side=f.rhs,
# initial_condition=phi0,
# method=AdaptiveERK54CashKarp(),
# controller=PIController(first_step=1.e-8, target_error=1.e-4))[1]
np.save('t_sg_heptane_64.npy', data.t_list)
np.save('q_sg_heptane_64.npy', data.solution_list)
iq = 0
nq = f._n_equations
phi02d = phi0[iq::nq].reshape((ny, nx), order='F')
phi2d = phi[iq::nq].reshape((ny, nx), order='F')
rhs2d = f.rhs(0, phi)[iq::nq].reshape((ny, nx), order='F')
phimphi02d = phi2d - phi02d
c1 = f._state_1
c2 = f._state_2
c3 = f._state_3
# second solve end
ax = plt.subplot2grid((2, 3), (0, 2))
ax.plot(x_range, phi02d[0, :])
ax.plot(x_range, phi2d[0, :])
ax.yaxis.tick_right()
ax.set_xlabel('$Z_1$')
ax.set_xlim([0, 1])
ax.grid(True)
ax = plt.subplot2grid((2, 3), (1, 2))
ax.plot(y_range, phi02d[:, 0])
ax.plot(y_range, phi2d[:, 0])
ax.yaxis.tick_right()
ax.set_xlabel('$Z_2$')
ax.set_xlim([0, 1])
ax.grid(True)
ax = plt.subplot2grid((2, 3), (0, 0), rowspan=2, colspan=2)
ax.contourf(x_grid, y_grid, phi2d, cmap=plt.get_cmap('rainbow'))
t1 = plt.Polygon(np.array([[1, 0], [1, 1], [0, 1]]), color='w')
ax.add_patch(t1)
ax.text(0.03, 1.00, 'C2H4', fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7))
ax.text(0.98, 0.04, 'COH2', fontdict={'fontweight': 'bold'}, bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7))
ax.text(-0.08, 0.05, 'air', fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7))
ax.set_xlabel('$Z_1$')
ax.set_ylabel('$Z_2$', rotation=0)
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.grid(True)
plt.tight_layout()
plt.show()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x_grid, y_grid, phi2d, cmap=plt.get_cmap('rainbow'))
# ax.plot_wireframe(x_grid, y_grid, phimphi02d, linewidth=1)
ax.set_xlabel('z1')
ax.set_ylabel('z2')
ax.set_zlabel('f')
# ax.plot([0], [0], [c1[iq]], 'ko')
# ax.plot([0], [1], [c2[iq]], 'ko')
# ax.plot([1], [0], [c3[iq]], 'ko')
# ax.plot([1], [1], [c1[iq]], 'ko')
plt.show()
# ax = plt.subplot2grid((2, 3), (0, 2))
# ax.plot(x_range, rhs2d[0, :])
# ax.yaxis.tick_right()
# ax.set_xlabel('$Z_1$')
# ax.set_xlim([0, 1])
# ax.grid(True)
# ax = plt.subplot2grid((2, 3), (1, 2))
# ax.plot(y_range, rhs2d[:, 0])
# ax.yaxis.tick_right()
# ax.set_xlabel('$Z_2$')
# ax.set_xlim([0, 1])
# ax.grid(True)
# ax = plt.subplot2grid((2, 3), (0, 0), rowspan=2, colspan=2)
# ax.contourf(x_grid, y_grid, rhs2d, cmap=plt.get_cmap('rainbow'))
# t1 = plt.Polygon(np.array([[1, 0], [1, 1], [0, 1]]), color='w')
# ax.add_patch(t1)
# ax.text(0.03, 1.00, 'sg', fontdict={'fontweight': 'bold'}, bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7))
# ax.text(0.98, 0.04, 'h2', fontdict={'fontweight': 'bold'}, bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7))
# ax.text(-0.08, 0.05, 'air', fontdict={'fontweight': 'bold'}, bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7))
# ax.set_xlabel('$Z_1$')
# ax.set_ylabel('$Z_2$', rotation=0)
# ax.set_xlim([0, 1])
# ax.set_ylim([0, 1])
# ax.grid(True)
# plt.tight_layout()
# plt.show()
#
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# ax.plot_surface(x_grid, y_grid, rhs2d, cmap=plt.get_cmap('rainbow'))
# # ax.plot_wireframe(x_grid, y_grid, rhs2d, linewidth=1)
# ax.set_xlabel('z1')
# ax.set_ylabel('z2')
# ax.set_zlabel('f')
# # ax.plot([0], [0], [c1[iq]], 'ko')
# # ax.plot([0], [1], [c2[iq]], 'ko')
# # ax.plot([1], [0], [c3[iq]], 'ko')
# # ax.plot([1], [1], [c1[iq]], 'ko')
# plt.show()
<file_sep>import unittest
from numpy import exp, log, mean
from spitfire.time.methods import *
from spitfire.time.nonlinear import *
from spitfire import odesolve
def direct_solve(fun):
def append_iteration_count_of_one_and_converged(x, *args, **kwargs):
output = fun(x, *args, **kwargs)
return output, 1, True
return append_iteration_count_of_one_and_converged
class ExponentialDecayProblem(object):
def __init__(self):
self.decay_constant = -1.
self.lhs_inverse = None
def rhs(self, t, state):
return self.decay_constant * state
def setup(self, t, state, prefactor):
self.lhs_inverse = 1. / (prefactor * self.decay_constant - 1.)
@direct_solve
def solve(self, residual):
return self.lhs_inverse * residual
def validate_method(method):
edp = ExponentialDecayProblem()
rhs = edp.rhs
if method.is_implicit:
setup = edp.setup
solve = edp.solve
else:
setup = None
solve = None
dtlist = [0.1, 0.05, 0.025, 0.0125]
errors = []
tf = 1.0
for dt in dtlist:
qf = odesolve(rhs,
array([1.]),
array([tf]),
linear_setup=setup,
linear_solve=solve,
method=method,
step_size=dt)
errors.append(norm(exp(-tf) - qf))
order_list = []
for idx in range(len(errors) - 1):
order_list.append(log(errors[idx] / errors[idx + 1]) / log(dtlist[idx] / dtlist[idx + 1]))
observed_order = mean(array(order_list))
success = method.order - 0.1 < observed_order < method.order + 0.1
if not success:
print(method.name, method.order, observed_order)
return success
def create_test(m):
def test(self):
self.assertTrue(validate_method(m))
return test
class TestOrderOfAccuracy(unittest.TestCase):
pass
for method in [ForwardEulerS1P1,
ExpMidpointS2P2,
ExpTrapezoidalS2P2Q1,
ExpRalstonS2P2,
RK3KuttaS3P3,
RK4ClassicalS4P4,
BogackiShampineS4P3Q2,
ZonneveldS5P4Q3,
ExpKennedyCarpetnerS6P4Q3,
CashKarpS6P5Q4, ]:
setattr(TestOrderOfAccuracy, 'test_' + str(method().name), create_test(method()))
for method in [BackwardEulerS1P1Q1,
CrankNicolsonS2P2,
KennedyCarpenterS6P4Q3,
KennedyCarpenterS4P3Q2,
KvaernoS4P3Q2,
KennedyCarpenterS8P5Q4, ]:
for solver in [SimpleNewtonSolver]:
setattr(TestOrderOfAccuracy, 'test_' + str(method(solver()).name) + '_' + str(solver),
create_test(method(solver())))
if __name__ == '__main__':
unittest.main()
<file_sep>Custom Presumed PDF: log-mean PDF of the scalar dissipation rate
================================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - Building presumed PDF adiabatic and nonadiabatic SFLM
libraries for turbulent flows - Using Spitfire’s wrapper around the
Python interface of
```TabProps`` <https://multiscale.utah.edu/software/>`__ to easily
extend tables with clipped Gaussian and Beta PDFs
Tabulated chemistry models can often be split into two pieces: a
*reaction* model and a *mixing* model. The reaction model describes
small scale laminar flame structure, for instance equilibrium (fast
chemistry) or diffusion-reaction (SLFM), possibly perturbed by radiative
heat losses. A mixing model is unnecessary in a CFD simulation when the
flow is laminar or when all scales of turbulence are resolved as in
direct numerical simulation (DNS). In Reynolds-averaged Navier-Stokes
(RANS) or large eddy simulation (LES), however, small scales are modeled
instead of being resolved by the mesh. Here a mixing model is necessary
to account for turbulence-chemistry interaction on subgrid scales.
In RANS and LES, typically two statistical moments of conserved scalars
are transported on the mesh and the mixing model accounts for
unresolved, or subgrid, heterogeneity. A mixing model accomplishes this
by describing the statistical distribution of the subgrid scalar field.
Spitfire and the `Python interface of the ``TabProps``
code <https://multiscale.utah.edu/software/>`__ can be combined to build
reaction models and then incorporate presumed PDF mixing models.
Reaction Model
--------------
We’ll start by building a standard adiabatic SLFM library for an
n-heptane/air mixture, except in this case we’ll specify a very wide
range of the stoichiometric dissipation rate and set
``include_extinguished=True`` to keep non-burning states after
extinction in the library. You can verify this with the plots below,
where the discontinuity of extinction is clear.
.. code:: ipython3
from spitfire import (ChemicalMechanismSpec,
FlameletSpec,
build_adiabatic_slfm_library,
apply_mixing_model,
PDFSpec,
Library)
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
import numpy as np
mech = ChemicalMechanismSpec(cantera_xml='heptane-liu-hewson-chen-pitsch-highT.xml',
group_name='gas')
flamelet_specs = FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=mech.stream(stp_air=True),
fuel_stream=mech.stream('TPY', (372., 101325., 'NXC7H16:1')),
grid_points=64)
slfm = build_adiabatic_slfm_library(flamelet_specs,
diss_rate_values=np.logspace(-1, 4, 40),
diss_rate_ref='stoichiometric',
include_extinguished=True,
verbose=False)
plt.plot(slfm.mixture_fraction_values, slfm['temperature'][:, ::5])
plt.xlabel('$\\mathcal{Z}$')
plt.ylabel('T (K)')
plt.grid()
plt.show()
plt.semilogx(slfm.dissipation_rate_stoich_values, np.max(slfm['temperature'], axis=0),
'-', markersize=2)
plt.xlabel('$\\chi_{\\rm st}$ (1/s)')
plt.ylabel('max T (K)')
plt.grid()
plt.show()
plt.contourf(slfm.mixture_fraction_grid,
slfm.dissipation_rate_stoich_grid,
slfm['temperature'])
plt.yscale('log')
plt.xlabel('$\\mathcal{Z}$')
plt.ylabel('$\\chi_{\\rm st}$ (1/s)')
plt.title('laminar flamelet T(K)')
plt.colorbar()
plt.show()
.. image:: custom_pdf_logmean_chi_files/custom_pdf_logmean_chi_1_0.png
.. image:: custom_pdf_logmean_chi_files/custom_pdf_logmean_chi_1_1.png
.. image:: custom_pdf_logmean_chi_files/custom_pdf_logmean_chi_1_2.png
The User-Defined PDF Class
--------------------------
Here we use a one-parameter logarithmic mean PDF for the dissipation
rate (in addition to a clipped Gaussian PDF for the scalar variance).
The class below defines several key methods, some of which are required
for the integration in Spitfire.
- ``set_mean(self, mean)``: necessary API for Spitfire’s PDF
integration.
- ``set_variance(self, variance)``/``set_scalar_variance(self, variance)``:
one of these is needed, even though there isn’t a variance in this
PDF, as Spitfire will internally call one of the two methods
depending on which of ``variance_values`` or
``scalar_variance_values`` is provided as an argument to
``apply_mixing_model``.
- ``integrate(self, interpolant)``: necessary for the internal API,
which will provide a 1D interpolant with a call operator. The
integrand being integrated must be the PDF multiplied by the
interpolant. Here we simply use Simpson’s rule as the log mean PDF
seems pretty simple to integrate. In general, adaptive quadrature
should be used to guarantee accurate results.
- ``get_pdf(self, x)``: completely unnecessary for integration with the
PDF, but convenient for visualization
.. code:: ipython3
from scipy.integrate import simpson
class LogMean1ParamPDF:
def __init__(self, sigma):
self._sigma = sigma
self._mu = 0.
self._s2pi = np.sqrt(2. * np.pi)
self._xt = np.logspace(-6, 6, 1000)
self._pdft = np.zeros_like(self._xt)
def get_pdf(self, x):
s = self._sigma
m = self._mu
return 1. / (x * s * self._s2pi) * np.exp(-(np.log(x) - m) * (np.log(x) - m) / (2. * s * s))
def set_mean(self, mean):
self._mu = np.log(mean) - 0.5 * self._sigma * self._sigma
self._pdft = self.get_pdf(self._xt)
def set_variance(self, variance):
pass
def set_scaled_variance(self, variance):
raise ValueError('cannot use set_scaled_variance on LogMean1ParamPDF, use direct variance values')
def integrate(self, interpolant):
ig = interpolant(self._xt) * self._pdft
return simpson(ig, x=self._xt)
lm_pdf = LogMean1ParamPDF(1.0)
xtest = np.logspace(-3, np.log10(400), 10000)
for mean in [20., 50., 100.0, 200, 300]:
lm_pdf.set_mean(mean)
plt.plot(xtest, lm_pdf.get_pdf(xtest))
plt.grid()
plt.xlabel('input')
plt.ylabel('PDF')
plt.show()
.. image:: custom_pdf_logmean_chi_files/custom_pdf_logmean_chi_3_0.png
Integrating the Custom PDF
--------------------------
Now we simply provide our instance of the class, ``lm_pdf``, as the
``pdf`` argument to the ``PDFSpec`` for ``apply_mixing_model``. We just
set a single ``variance_value`` here because we’re not actually adding
an entire range of variances with the one-parameter log-mean PDF. Also,
note that the ``set_variance()`` method on the class above doesn’t
actually use the value, which is just set to ``1.`` for simplicity.
An important consequence of only specifying a single variance or scaled
variance value is that the resultant library will be ``squeeze``\ d so
that no additional dimensions are actually added. You can see this below
when we print the library - it doesn’t have a
``dissipation_rate_stoich_variance_mean`` dimension.
.. code:: ipython3
# remove the mass fractions to speed up the convolution integrals - we're only observing the temperature here
mass_fracs = slfm.props
mass_fracs.remove('temperature')
slfm.remove(*mass_fracs)
slfm_t = apply_mixing_model(
slfm,
verbose=True,
mixing_spec={'dissipation_rate_stoich': PDFSpec(pdf=lm_pdf, variance_values=np.array([1.])),
'mixture_fraction': PDFSpec(pdf='ClipGauss', scaled_variance_values=np.linspace(0, 1, 8))},
num_procs=4
)
print(slfm_t)
.. parsed-literal::
dissipation_rate_stoich_variance: computing 2560 integrals... completed in 1.1 seconds, average = 2374 integrals/s.
scaled_scalar_variance_mean: computing 20480 integrals... completed in 4.5 seconds, average = 4562 integrals/s.
Spitfire Library with 3 dimensions and 1 properties
------------------------------------------
1. Dimension "mixture_fraction_mean" spanning [0.0, 1.0] with 64 points
2. Dimension "dissipation_rate_stoich_mean" spanning [0.1, 10000.0] with 40 points
3. Dimension "scaled_scalar_variance_mean" spanning [0.0, 1.0] with 8 points
------------------------------------------
temperature , min = 299.99991531427054 max = 2144.707709229305
Extra attributes: {'mech_spec': <spitfire.chemistry.mechanism.ChemicalMechanismSpec object at 0x7f8b4393ee10>, 'mixing_spec': {'dissipation_rate_stoich': <spitfire.chemistry.tabulation.PDFSpec object at 0x7f8b3d2935d0>, 'mixture_fraction': <spitfire.chemistry.tabulation.PDFSpec object at 0x7f8b3d293590>}}
------------------------------------------
Visualizing the Result
----------------------
Now we finish up with some plots. Note especially the effect filtering
the dissipation rate has on the max temperature plot - we’ve actually
smoothed the extinction behavior over a much larger range of the mean
dissipation rate.
.. code:: ipython3
plt.plot(slfm_t.mixture_fraction_mean_values, np.squeeze(slfm_t['temperature'][:, :, 0]))
plt.xlabel('$\\overline{\\mathcal{Z}}$')
plt.ylabel('mean T (K)')
plt.title('mean temperature, $\\sigma_{\\mathcal{Z},s}=0$')
plt.grid()
plt.show()
plt.semilogx(slfm.dissipation_rate_stoich_values, np.max(slfm['temperature'], axis=0),
'-', markersize=2, label='laminar flamelet')
plt.semilogx(slfm_t.dissipation_rate_stoich_mean_values, np.max(slfm_t['temperature'], axis=0)[:, 0],
'--', markersize=2, label='filtered, $\\overline{\\sigma_{\\mathcal{Z},s}}=0$')
plt.semilogx(slfm_t.dissipation_rate_stoich_mean_values, np.max(slfm_t['temperature'], axis=0)[:, 1],
'--', markersize=2, label='filtered, $\\overline{\\sigma_{\\mathcal{Z},s}}=0.14$')
plt.ylabel('$\\overline{\\chi_{\\rm st}}$ (1/s)')
plt.ylabel('max mean T (K)')
plt.grid()
plt.legend()
plt.show()
plt.contourf(np.squeeze(slfm_t.mixture_fraction_mean_grid[:, :, 0]),
np.squeeze(slfm_t.dissipation_rate_stoich_mean_grid[:, :, 0]),
np.squeeze(slfm_t['temperature'][:, :, 0]),
norm=Normalize(slfm_t['temperature'].min(), slfm_t['temperature'].max()))
plt.colorbar()
plt.yscale('log')
plt.xlabel('$\\overline{\\mathcal{Z}}$')
plt.ylabel('$\\overline{\\chi_{\\rm st}}$ (1/s)')
plt.title('mean T (K) at $\\overline{\\sigma_{\\mathcal{Z},s}}=0$')
plt.show()
plt.contourf(np.squeeze(slfm_t.mixture_fraction_mean_grid[:, :, 0]),
np.squeeze(slfm_t.dissipation_rate_stoich_mean_grid[:, :, 0]),
np.squeeze(slfm_t['temperature'][:, :, 1]),
norm=Normalize(slfm_t['temperature'].min(), slfm_t['temperature'].max()))
plt.colorbar()
plt.yscale('log')
plt.xlabel('$\\overline{\\mathcal{Z}}$')
plt.ylabel('$\\overline{\\chi_{\\rm st}}$ (1/s)')
plt.title('mean T (K) at $\\overline{\\sigma_{\\mathcal{Z},s}}=0.14$')
plt.show()
.. image:: custom_pdf_logmean_chi_files/custom_pdf_logmean_chi_7_0.png
.. image:: custom_pdf_logmean_chi_files/custom_pdf_logmean_chi_7_1.png
.. image:: custom_pdf_logmean_chi_files/custom_pdf_logmean_chi_7_2.png
.. image:: custom_pdf_logmean_chi_files/custom_pdf_logmean_chi_7_3.png
.. code:: ipython3
from mpl_toolkits.mplot3d import axes3d
from matplotlib.colors import Normalize
.. code:: ipython3
fig = plt.figure()
ax = fig.gca(projection='3d')
z = np.squeeze(slfm_t.mixture_fraction_mean_grid[:, :, 0])
x = np.squeeze(np.log10(slfm_t.dissipation_rate_stoich_mean_grid[:, :, 0]))
v_list = slfm_t.scaled_scalar_variance_mean_values
for idx in [7, 6, 4, 2, 0]:
p = ax.contourf(z, x, np.squeeze(slfm_t['temperature'][:, :, idx]),
offset=v_list[idx],
cmap='inferno',
norm=Normalize(300, 2200))
plt.colorbar(p)
ax.view_init(elev=14, azim=-120)
ax.set_zlim([0, 1])
ax.set_xlabel('mean mixture fraction')
ax.set_ylabel('log mean dissipation rate')
ax.set_zlabel('mean scaled scalar variance')
ax.set_title('$\\mathcal{Z},\chi$-filtered mean T (K)')
plt.show()
.. image:: custom_pdf_logmean_chi_files/custom_pdf_logmean_chi_9_0.png
<file_sep>spitfire.chemistry package
==========================
Submodules
----------
spitfire.chemistry.analysis module
----------------------------------
.. automodule:: spitfire.chemistry.analysis
:members:
:undoc-members:
:show-inheritance:
spitfire.chemistry.ctversion module
-----------------------------------
.. automodule:: spitfire.chemistry.ctversion
:members:
:undoc-members:
:show-inheritance:
spitfire.chemistry.flamelet module
----------------------------------
.. automodule:: spitfire.chemistry.flamelet
:members:
:undoc-members:
:show-inheritance:
spitfire.chemistry.flamelet2d module
------------------------------------
.. automodule:: spitfire.chemistry.flamelet2d
:members:
:undoc-members:
:show-inheritance:
spitfire.chemistry.library module
---------------------------------
.. automodule:: spitfire.chemistry.library
:members:
:undoc-members:
:show-inheritance:
spitfire.chemistry.mechanism module
-----------------------------------
.. automodule:: spitfire.chemistry.mechanism
:members:
:undoc-members:
:show-inheritance:
spitfire.chemistry.reactors module
----------------------------------
.. automodule:: spitfire.chemistry.reactors
:members:
:undoc-members:
:show-inheritance:
spitfire.chemistry.tabulation module
------------------------------------
.. automodule:: spitfire.chemistry.tabulation
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: spitfire.chemistry
:members:
:undoc-members:
:show-inheritance:
<file_sep>import unittest
import pickle
from os.path import join, abspath
from cantera import Solution
from spitfire import ChemicalMechanismSpec, CanteraLoadError
class MechanismSpec(unittest.TestCase):
def test_create_valid_mechanism_spec_from_xml(self):
try:
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
m = ChemicalMechanismSpec(xml, 'h2-burke')
g = m.griffon
x = m.mech_file_path
s = m.gas
self.assertTrue(True)
except:
self.assertTrue(False)
def test_create_valid_mechanism_spec_from_solution(self):
try:
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
sol = Solution(xml)
m = ChemicalMechanismSpec.from_solution(sol)
g = m.griffon
x = m.mech_file_path
n = m.group_name
s = m.gas
self.assertTrue(True)
except:
self.assertTrue(False)
def test_create_invalid_mechanism_spec(self):
try:
ChemicalMechanismSpec('does not exist', 'at all')
self.assertTrue(False)
except CanteraLoadError:
self.assertTrue(True)
def test_create_invalid_mechanism_spec_bad_group(self):
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
try:
ChemicalMechanismSpec(xml, 'bad group')
self.assertTrue(False)
except CanteraLoadError:
self.assertTrue(True)
def test_create_valid_streams(self):
try:
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
m = ChemicalMechanismSpec(xml, 'h2-burke')
air = m.stream(stp_air=True)
h2o2 = m.stream('TPX', (300., 101325., 'H2:1, O2:1'))
air_copy = m.copy_stream(air)
mix = m.mix_streams([(h2o2, 1.), (air, 1.)], 'mass', 'HP')
mix = m.mix_streams([(h2o2, 1.), (air, 1.)], 'mole', 'TP')
mix = m.mix_streams([(h2o2, 1.), (air, 1.)], 'mass', 'UV')
self.assertTrue(True)
except:
self.assertTrue(False)
def test_create_invalid_stpair_streams(self):
try:
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
m = ChemicalMechanismSpec(xml, 'h2-burke')
m.stream(stp_air=False)
self.assertTrue(False)
except:
self.assertTrue(True)
def test_create_invalid_streams_no_property_values(self):
try:
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
m = ChemicalMechanismSpec(xml, 'h2-burke')
m.stream('TPX')
self.assertTrue(False)
except:
self.assertTrue(True)
def test_mechanism_simple_api_methods(self):
try:
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
sol = Solution(xml)
m = ChemicalMechanismSpec.from_solution(sol)
self.assertEqual(m.n_species, sol.n_species, 'ChemicalMechanismSpec.n_species vs ct.Solution.n_species')
self.assertEqual(m.n_reactions, sol.n_reactions,
'ChemicalMechanismSpec.n_reactions vs ct.Solution.n_reactions')
for i in range(m.n_species):
self.assertEqual(m.species_names[i], sol.species_names[i],
'ChemicalMechanismSpec.species_name[i] vs ct.Solution.species_name[i]')
for n in m.species_names:
self.assertEqual(m.species_index(n), sol.species_index(n),
'ChemicalMechanismSpec.species_index(name) vs ct.Solution.species_index(name)')
for i, n in enumerate(m.species_names):
self.assertEqual(m.species_index(n), i, 'species names and indices are consistent, index vs i')
self.assertEqual(n, m.species_names[i], 'species names and indices are consistent, name vs n')
self.assertEqual(m.molecular_weight(i), m.molecular_weight(n),
'ChemicalMechanismSpec molecular_weight(name) vs molecular_weight(idx)')
except:
self.assertTrue(False)
try:
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
m = ChemicalMechanismSpec.from_solution(Solution(xml))
m.molecular_weight(list())
self.assertTrue(False)
except:
self.assertTrue(True)
def test_mechanism_serialization(self):
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
sol = Solution(xml)
m1 = ChemicalMechanismSpec.from_solution(sol)
m1_pickle = pickle.dumps(m1)
m2 = pickle.loads(m1_pickle)
self.assertTrue(m1.mech_data['species'] == m2.mech_data['species'])
self.assertTrue(m1.mech_data['reactions'] == m2.mech_data['reactions'])
if __name__ == '__main__':
unittest.main()
<file_sep>A Time-Dependent Flow Reactor: Periodic Ignition/Extinction
===========================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - How to add time-dependence to a ``HomogeneousReactor``
model
Introduction
------------
This demonstration considers a reactor model with a slowly oscillating
feed temperature. The frequency of this oscillation is low enough that
it triggers repeated ignition/extinction events. Time-dependence is
introduced with a Python ``lambda`` function.
.. code:: ipython3
from spitfire import ChemicalMechanismSpec, HomogeneousReactor
import matplotlib.pyplot as plt
import numpy as np
.. code:: ipython3
mech = ChemicalMechanismSpec(cantera_xml='h2-burke.xml', group_name='h2-burke')
air = mech.stream(stp_air=True)
fuel = mech.stream('X', 'H2:1')
mix = mech.mix_for_equivalence_ratio(1.0, fuel, air)
mix.TP = 800., 101325.
Time-dependent Feed Temperature
-------------------------------
Unlike reactors in simpler demonstrations, this reactor involves flow
(``mass_transfer='open'``), and Spitfire requires the residence time
(``mixing_tau``) and feed stream, specified through the
``feed_temperature`` and ``feed_mass_fractions`` arguments. Any of these
arguments can be functions of time, as shown below for the feed
temperature.
Next we simply integrate this reactor over a time period - two periods
of oscillation of the feed temperature.
.. code:: ipython3
feed = mech.copy_stream(mix)
feed_temperature_fxn = lambda t: 800. + 400. * np.sin(2. * np.pi * 10. * t)
reactor = HomogeneousReactor(mech, mix,
configuration='isobaric',
heat_transfer='adiabatic',
mass_transfer='open',
mixing_tau=1.e-5,
feed_temperature=feed_temperature_fxn,
feed_mass_fractions=feed.Y)
output = reactor.integrate_to_time(0.2, transient_tolerance=1.e-10)
times = output.time_values
plt.plot(times * 1.e3, output['temperature'], '-', label='reactor')
plt.plot(times * 1.e3, feed_temperature_fxn(times), '--', label='feed')
plt.ylabel('T (K)')
plt.xlabel('t (ms)')
plt.legend()
plt.grid()
plt.show()
.. image:: oscillating_ignition_extinction_files/oscillating_ignition_extinction_5_0.png
While it’s clear that the reactor ignites on the upswing of the feed
temperature, and is extinguished on the downswing, we could also
visualize the chemcial composition. The output from the integration is a
``Library`` object, with a single dimension of time, which we can simply
print to see all the fields available.
.. code:: ipython3
print(output)
.. parsed-literal::
Spitfire Library with 1 dimensions and 13 properties
------------------------------------------
1. Dimension "time" spanning [0.0, 0.2] with 3400 points
------------------------------------------
temperature , min = 400.00023760816015 max = 1723.4172921512559
pressure , min = 101325.0 max = 101325.0
mass fraction HE , min = -5.551115123125783e-16 max = 7.771561172376096e-16
mass fraction H , min = 0.0 max = 0.004325863975340061
mass fraction H2 , min = 0.006810714712865773 max = 0.028634460764729135
mass fraction O , min = 0.0 max = 0.015190690085155157
mass fraction OH , min = 0.0 max = 0.01517887950146069
mass fraction H2O , min = 0.0 max = 0.15018436327110132
mass fraction O2 , min = 0.06530244961447292 max = 0.22726263049348533
mass fraction HO2 , min = 0.0 max = 0.00029422117189264844
mass fraction H2O2 , min = 0.0 max = 5.528833951840396e-06
mass fraction N2 , min = 0.7441029087417855 max = 0.7441029087417855
mass fraction AR , min = 0.0 max = 0.0
Extra attributes: {}
------------------------------------------
.. code:: ipython3
for s in ['H2', 'H2O', 'O2', 'H', 'OH']:
plt.plot(times * 1.e3, output[f'mass fraction {s}'], label=s)
plt.ylabel('mass fraction')
plt.xlabel('t (ms)')
plt.legend()
plt.grid()
plt.show()
.. image:: oscillating_ignition_extinction_files/oscillating_ignition_extinction_8_0.png
Conclusions
-----------
This notebook shows how to incorporate mass flow in a reactor model and
have the temperature of the feed stream vary with time.
<file_sep>import pickle
def run():
from spitfire import (odesolve,
BackwardEulerS1P1Q1,
KennedyCarpenterS6P4Q3,
KvaernoS4P3Q2,
KennedyCarpenterS4P3Q2,
KennedyCarpenterS8P5Q4, )
from spitfire.time.nonlinear import SimpleNewtonSolver
from scipy.linalg.lapack import dgetrf as lapack_lu_factor
from scipy.linalg.lapack import dgetrs as lapack_lu_solve
import scipy.sparse.linalg as spla
import numpy as np
class ChemistryProblem(object):
"""
This class defines the right-hand side, setup, and solve methods for implicit methods with custom linear solvers
"""
def __init__(self, k_ab, k_bc):
self._k_ab = k_ab
self._k_bc = k_bc
self._lhs_inverse_op = None
self._identity_matrix = np.eye(3)
self._gmres_iter = 0
def rhs(self, t, c):
c_a = c[0]
c_b = c[1]
q_1 = self._k_ab * c_a
q_2 = self._k_bc * c_a * c_b
return np.array([-q_1 - q_2,
q_1 - q_2,
2. * q_2])
def setup_lapack_lu(self, t, c, prefactor):
c_a = c[0]
c_b = c[1]
dq1_da = self._k_ab
dq1_db = 0.
dq1_dc = 0.
dq2_da = self._k_bc * c_b
dq2_db = self._k_bc * c_a
dq2_dc = 0.
J = np.array([[-dq1_da - dq2_da, -dq1_db - dq2_db, -dq1_dc - dq2_dc],
[dq1_da - dq2_da, dq1_db - dq2_db, dq1_dc - dq2_dc],
[2. * dq2_da, 2. * dq2_db, 2. * dq2_dc]])
linear_op = prefactor * J - self._identity_matrix
self._lhs_inverse_op = lapack_lu_factor(linear_op)[
:2] # this [:2] is just an implementation detail of scipy
def solve_lapack_lu(self, residual):
return lapack_lu_solve(self._lhs_inverse_op[0],
self._lhs_inverse_op[1],
residual)[
0], 1, True # the , 1, True parts are how many iterations and success/failure
def setup_diagonal(self, t, c, prefactor):
c_a = c[0]
c_b = c[1]
dq1_da = self._k_ab
dq1_db = 0.
dq1_dc = 0.
dq2_da = self._k_bc * c_b
dq2_db = self._k_bc * c_a
dq2_dc = 0.
J = np.array([[-dq1_da - dq2_da, -dq1_db - dq2_db, -dq1_dc - dq2_dc],
[dq1_da - dq2_da, dq1_db - dq2_db, dq1_dc - dq2_dc],
[2. * dq2_da, 2. * dq2_db, 2. * dq2_dc]])
linear_op = prefactor * J - self._identity_matrix
self._lhs_inverse_op = 1. / linear_op.diagonal()
def solve_diagonal(self, residual):
return self._lhs_inverse_op * residual, 1, True # the , 1, True parts are how many iterations and success/failure
def setup_gmres(self, t, c, prefactor):
c_a = c[0]
c_b = c[1]
dq1_da = self._k_ab
dq1_db = 0.
dq1_dc = 0.
dq2_da = self._k_bc * c_b
dq2_db = self._k_bc * c_a
dq2_dc = 0.
J = np.array([[-dq1_da - dq2_da, -dq1_db - dq2_db, -dq1_dc - dq2_dc],
[dq1_da - dq2_da, dq1_db - dq2_db, dq1_dc - dq2_dc],
[2. * dq2_da, 2. * dq2_db, 2. * dq2_dc]])
self._linear_op = prefactor * J - self._identity_matrix
self._lhs_op = spla.LinearOperator((3, 3), lambda x: self._linear_op.dot(x))
self._jacobi_preconditioner = spla.LinearOperator((3, 3),
lambda res: 1. / self._linear_op.diagonal() * res)
def _increment_gmres_iter(self, *args, **kwargs):
self._gmres_iter += 1
def solve_gmres(self, residual):
x, i = spla.gmres(self._lhs_op,
residual,
M=self._jacobi_preconditioner,
atol=1.e-8,
callback=self._increment_gmres_iter,
callback_type='legacy')
return x, self._gmres_iter, not i
c0 = np.array([1., 0., 0.]) # initial condition
k_ab = 1. # A -> B rate constant
k_bc = 0.2 # A + B -> 2C rate constant
problem = ChemistryProblem(k_ab, k_bc)
final_time = 10. # final time to integrate to
sol_dict = dict()
for method in [BackwardEulerS1P1Q1(SimpleNewtonSolver()),
KennedyCarpenterS6P4Q3(SimpleNewtonSolver()),
KvaernoS4P3Q2(SimpleNewtonSolver()),
KennedyCarpenterS4P3Q2(SimpleNewtonSolver()),
KennedyCarpenterS8P5Q4(SimpleNewtonSolver())]:
t, sol = odesolve(problem.rhs, c0, stop_at_time=final_time,
method=method,
linear_setup=problem.setup_lapack_lu,
linear_solve=problem.solve_lapack_lu,
save_each_step=True)
sol_dict['lapack-' + method.name] = (t.copy(), sol.copy())
t, sol = odesolve(problem.rhs, c0, stop_at_time=final_time,
method=method,
linear_setup=problem.setup_diagonal,
linear_solve=problem.solve_diagonal,
save_each_step=True)
sol_dict['diagonal-' + method.name] = (t.copy(), sol.copy())
t, sol = odesolve(problem.rhs, c0, stop_at_time=final_time,
method=method,
linear_setup=problem.setup_gmres,
linear_solve=problem.solve_gmres,
save_each_step=True)
sol_dict['gmres-' + method.name] = (t.copy(), sol.copy())
return sol_dict
if __name__ == '__main__':
output = run()
with open('gold.pkl', 'wb') as file_output:
pickle.dump(output, file_output)
<file_sep>import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import numpy as np
from spitfire.chemistry.flamelet import Flamelet
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
m = ChemicalMechanismSpec(cantera_xml='heptane-liu-hewson-chen-pitsch-highT.xml', group_name='gas')
pressure = 101325.
air = m.stream(stp_air=True)
air.TP = 298., pressure
fuel = m.stream('TPY', (488., pressure, 'NXC7H16:1'))
flamelet_specs = {'mech_spec': m, 'pressure': pressure, 'oxy_stream': air, 'fuel_stream': fuel}
def get_data(cpoint, ccoeff, npts):
z, dz = Flamelet._clustered_grid(npts, cpoint, ccoeff)
dz = np.hstack([dz, 1. - z[-2]])
return z, 1. / dz
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.Div([dcc.Graph(id='graph-dz', className='four columns'),
dcc.Graph(id='graph-T', className='four columns')]),
html.Div([html.Div([html.Label('Cluster point'),
html.Div(id='cluster-point-text'),
dcc.Slider(
id='cluster-point-slider',
min=0.01,
max=0.99,
value=0.06,
step=0.01,
className='four columns'
), ]),
html.Div([html.Label('Cluster intensity'),
html.Div(id='cluster-intensity-text'),
dcc.Slider(
id='cluster-coeff-slider',
min=0.1,
max=10.,
value=4,
step=0.3,
className='four columns'
)]),
html.Div([html.Label('Number of nodes'),
html.Div(id='npts-text'),
dcc.Slider(
id='npts-slider',
min=32,
max=192,
value=72,
step=8,
className='four columns'
)])]),
])
@app.callback(
[Output('graph-dz', 'figure'),
Output('graph-T', 'figure')],
[Input('cluster-point-slider', 'value'),
Input('cluster-coeff-slider', 'value'),
Input('npts-slider', 'value')])
def update_figure(cpoint, ccoeff, npts):
z, inv_dz = get_data(cpoint, ccoeff, npts)
traces_dz = [dict(
x=z,
y=inv_dz,
mode='lines+markers',
opacity=0.7,
line=dict(width=4, color='Black'),
marker={
'symbol': 'square',
'size': 8,
'color': 'RoyalBlue',
'line': dict(width=1, color='Black')
},
)]
fs = dict(flamelet_specs)
fs.update(dict({'grid_points': npts, 'grid_cluster_intensity': ccoeff, 'grid_cluster_point': cpoint,
'initial_condition': 'equilibrium'}))
f = Flamelet(**fs)
T_eq = f.initial_temperature
fs.update(dict({'initial_condition': 'Burke-Schumann'}))
f = Flamelet(**fs)
T_bs = f.initial_temperature
traces_T = [dict(
name='Equilibrium',
x=z,
y=T_eq,
mode='lines+markers',
opacity=0.7,
line=dict(width=4, color='Black'),
marker={
'symbol': 'square',
'size': 8,
'color': 'RoyalBlue',
'line': dict(width=1, color='Black')
},
),
dict(
name='Burke-Schumann',
x=z,
y=T_bs,
mode='lines+markers',
opacity=0.7,
line=dict(width=4, color='Black'),
marker={
'symbol': 'square',
'size': 8,
'color': 'Salmon',
'line': dict(width=1, color='Black')
},
)
]
return {
'data': traces_dz,
'layout': dict(
xaxis={'type': 'linear', 'title': 'mixture fraction', 'range': [0, 1]},
yaxis={'type': 'log', 'title': 'equivalent uniform grid points', 'range': [0, 4]},
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
legend={'x': 0, 'y': 1},
hovermode='closest',
transition={'duration': 1e-3},
)
}, \
{
'data': traces_T,
'layout': dict(
xaxis={'type': 'linear', 'title': 'mixture fraction', 'range': [0, 1]},
yaxis={'type': 'linear', 'title': 'T (K)', 'range': [298, 3000]},
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
legend={'x': 0, 'y': 1},
hovermode='closest',
transition={'duration': 1e-3},
)
}
@app.callback(
[Output('cluster-point-text', 'children'),
Output('cluster-intensity-text', 'children'),
Output('npts-text', 'children')],
[Input('cluster-point-slider', 'value'),
Input('cluster-coeff-slider', 'value'),
Input('npts-slider', 'value')])
def update_figure(cpoint, ccoeff, npts):
return f'{cpoint:.2f}', f'{ccoeff:.2f}', f'{npts}'
if __name__ == '__main__':
app.run_server(debug=True)
<file_sep>Introduction
------------
Objectives & Applications
=========================
Spitfire is a Python/C++ code for scientific computing that has several objectives:
- Solve canonical combustion problems with complex chemical kinetics using advanced time integration and continuation techniques.
- Build tabulated chemistry models for use in reacting flow simulation.
- Design and rapidly prototype solvers and time integration techniques for general-purpose ordinary and partial differential equations.
Spitfire has been used by researchers at Sandia National Laboratories and the University of Utah for a number of applications:
- construct adiabatic and nonadiabatic flamelet (tabulated chemistry) libraries for simulation of single- and multi-phase combustion
- investigate the design of specialized embedded pairs of explicit Runge-Kutta methods and advanced adaptive time stepping techniques
- generate homogeneous reactor, non-premixed flamelet, and general reaction-diffusion datasets for the training of low-dimensional surrogate models of chemical kinetics
- perform fundamental studies of combustion in the MILD regime
- study chemical explosive modes and low-temperature oxidation pathways of complex fuels in non-premixed systems
- study the formulation of state vectors and analytical Jacobian matrices for combustion simulation
For tabulated chemistry and reactor-based studies of chemical kinetics,
Spitfire provides several useful layers ultimately stacked into high-level constructs for simpler use.
At the lowest level, Spitfire provides optimized functions (written in Griffon, Spitfire's internal C++ engine) for evaluating quantities such as thermodynamic state functions and chemical reaction rates,
with a focus on reaction mechanisms up to hundreds of species and thousands of reactions.
With these an advanced researcher could compose high-level algorithms of their choosing with exact control over every detail.
However, Spitfire also provides higher-level classes for homogeneous reactors (all combinations of isochoric/isobaric, closed/open, adiabatic/isothermal/diathermal)
and non-premixed flamelets.
These classes provide methods needed to perform time integration and compute steady states of such systems.
While the `Flamelet` class allows a user to build tabulated chemistry libraries on their own,
Spitfire has tabulation routines with simpler interfaces for common types of libraries.
For time-stepping problems Spitfire employs a general abstraction of time integration appropriate for a range of integration techniques, nonlinear solvers, and linear solvers.
Design of this solver stack is important to the efficient solution of reacting flow problems with complex chemistry, and the exploration of solver algorithms and study of complex combustion chemistry were Spitfire's original purposes.
Combining NumPy, SciPy, and Cython with an internal C++ code called Griffon yields an experience with the convenience and extensibility of Python and the performance of precompiled languages like C/C++.
In this paradigm Python is used to drive abstract numerical algorithms at a high level while Griffon and C/Fortran routines wrapped by NumPy/SciPy are used in performance critical code.
Access
======
Spitfire is a BSD(3) open-sourced code that is hosted publicly on Sandia National Laboratory's GitHub page: https://github.com/sandialabs/Spitfire
Static documentation for Spitfire is hosted by Read the Docs: https://spitfire.readthedocs.io/en/latest/
A number of demonstrations can be seen on the "Using Spitfire" portion of the readme: https://github.com/sandialabs/Spitfire#using-spitfire
Authors
=======
<NAME> (<EMAIL>) is Spitfire's primary author and point of contact.
Others who have contributed to Spitfire are <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>.
<file_sep>"""
This module contains the time integration governor abstraction,
which combines time steppers, nonlinear solvers, and step controllers into a generic integration loop
that supports arbitrary in situ processing, logging, termination of the integration loop, and more.
For instance, evaluation of the linear operator (Jacobian/preconditioner evaluation and factorization)
in implicit methods is guided by the Governor, as it can oversee the entire integration.
In many cases the Jacobian/preconditioner can be lagged for several time steps to speed up the integration process substantially.
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
import numpy as np
from numpy import any, logical_or, isinf, isnan, min, max, array, Inf, diag_indices, zeros
from scipy.linalg import norm
from spitfire.time.stepcontrol import ConstantTimeStep, PIController
from spitfire.time.methods import KennedyCarpenterS6P4Q3
from spitfire.time.nonlinear import finite_difference_jacobian, SimpleNewtonSolver
from scipy.linalg.lapack import dgetrf as lapack_lu_factor
from scipy.linalg.lapack import dgetrs as lapack_lu_solve
import time as timer
import datetime
import logging
def _log_header(verbose,
method_name):
if verbose:
now = datetime.datetime.now()
print('\n', now.strftime('%Y-%m-%d %H:%M'), ': Spitfire running case with method:', method_name,
flush=True)
def _log_footer(verbose,
cputime):
if verbose:
now = datetime.datetime.now()
print('\n', now.strftime('%Y-%m-%d %H:%M'), ': Spitfire finished in {:.8e} seconds!\n'.format(cputime),
flush=True)
def _print_debug_mode(debug_verbose, statement):
if debug_verbose:
print('\n --> DEBUG:', statement, '\n')
def _check_state_update(debug_verbose, state, dstate,
time_error, target_error,
nonlinear_solve_converged,
strict_temporal_error_control,
nonlinear_solve_must_converge,
custom_update_check):
# check for NaN and Inf
# check for exceeding target error and strict_temporal_error_control
# check for nonlinear convergence
# check a custom rule that might check physical realizability (e.g. temperature bounds), for instance
#
# return False if we should NOT accept the update
if time_error > target_error and strict_temporal_error_control:
_print_debug_mode(debug_verbose, 'check_state_update(): strict error exceeded')
return False
elif any(logical_or(isinf(dstate), isnan(dstate))):
_print_debug_mode(debug_verbose, 'check_state_update(): NaN or Inf detected')
return False
elif nonlinear_solve_converged is not None and (
not nonlinear_solve_converged and nonlinear_solve_must_converge):
_print_debug_mode(debug_verbose, 'check_state_update(): required nonlinear solve failed to converge')
return False
elif custom_update_check is not None:
_print_debug_mode(debug_verbose, 'check_state_update(): running custom_rule...')
return custom_update_check(state, dstate, time_error, nonlinear_solve_converged)
else:
return True
def _process_failed_step(debug_verbose,
time_step_size,
return_on_failed_step,
time_step_reduction_factor_on_failure,
warn_on_failed_step):
if return_on_failed_step:
raise ValueError('Step failed and return_on_failed_step=True, stopping!')
else:
_print_debug_mode(debug_verbose,
f'failed step with dt = {time_step_size}, '
f'reducing by a factor of {time_step_reduction_factor_on_failure}')
time_step_size *= time_step_reduction_factor_on_failure
eval_linear_setup = True
if warn_on_failed_step:
print('Warning! Step failed! return_on_failed_step=False so continuing on... retrying step...')
return time_step_size, eval_linear_setup
def _check_linear_setup(debug_verbose,
nlsuccess,
nlslowness,
time_step_size,
recent_time_step_size,
linear_setup_count,
projector_setup_rate,
time_step_reduction_factor_on_slow_solve,
time_step_reduction_factor_on_failure,
time_step_increase_factor_to_force_jacobian,
time_step_decrease_factor_to_force_jacobian):
if linear_setup_count == projector_setup_rate:
_print_debug_mode(debug_verbose, 'check_projector(): count = rate')
linear_setup_count = 0
return True, time_step_size, linear_setup_count
elif nlslowness:
_print_debug_mode(debug_verbose, 'check_projector(): nonlinear solve converging slowly')
time_step_size *= time_step_reduction_factor_on_slow_solve
return True, time_step_size, linear_setup_count
elif not nlsuccess:
time_step_size *= time_step_reduction_factor_on_failure
_print_debug_mode(debug_verbose, 'check_projector(): nonlinear solve failed to converge')
return True, time_step_size, linear_setup_count
elif time_step_size > recent_time_step_size * time_step_increase_factor_to_force_jacobian:
_print_debug_mode(debug_verbose, 'check_projector(): time step increased by too much')
return True, time_step_size, linear_setup_count
elif time_step_size < recent_time_step_size * time_step_decrease_factor_to_force_jacobian:
_print_debug_mode(debug_verbose, 'check_projector(): time step decreased by too much')
return True, time_step_size, linear_setup_count
else:
return False, time_step_size, linear_setup_count
def _write_log(verbose,
show_solver_stats_in_situ,
log_count,
log_rate,
log_title_count,
lines_per_header,
extra_logger_title_line1,
extra_logger_title_line2,
extra_logger_log,
state,
current_time,
time_step_size,
residual,
number_of_time_steps,
number_nonlinear_iter,
number_linear_iter,
number_projector_setup,
cputime):
log_count += 1
sim_time_lines = [
(f'{"number of":<10}', f'{"time steps":<10}', f' {number_of_time_steps:<9}'),
(f'{"simulation":<10}', f'{"time (s)":<10}', f'{float(current_time):<10.2e}'),
(f'{"time step":<10}', f'{"size (s)":<10}', f'{float(time_step_size):<10.2e}'), ]
if number_nonlinear_iter == 'n/a':
nni_over_nts = 'n/a'
nli_over_nni = 'n/a'
nts_over_nps = 'n/a'
advanced_lines = [
(f'{"nlin. iter":<10}', f'{"per step":<10}', f'{nni_over_nts:<10}'),
(f'{"lin. iter":<10}', f'{"per nlin.":<10}', f'{nli_over_nni:<10}'),
(f'{"steps":<10}', f'{"per Jac.":<10}', f'{nts_over_nps:<10}')]
else:
nni_over_nts = number_nonlinear_iter / number_of_time_steps
nli_over_nni = number_linear_iter / number_nonlinear_iter
nts_over_nps = number_of_time_steps / number_projector_setup
advanced_lines = [
(f'{"nlin. iter":<10}', f'{"per step":<10}', f'{nni_over_nts:<10.2f}'),
(f'{"lin. iter":<10}', f'{"per nlin.":<10}', f'{nli_over_nni:<10.2f}'),
(f'{"steps":<10}', f'{"per Jac.":<10}', f'{nts_over_nps:<10.2f}')]
cput_over_nts = 1.e3 * cputime / float(number_of_time_steps)
residual_line = [(f'{"diff. eqn.":<10}', f'{"|residual|":<10}', f'{residual:<10.2e}')]
cpu_time_lines = [
(f'{"total cpu":<10}', f'{"time (s)":<10}', f'{cputime:<10.2e}'),
(f'{"cput per":<10}', f'{"step (ms)":<10}', f'{cput_over_nts:<10.2e}')]
if verbose:
log_lines = sim_time_lines
if show_solver_stats_in_situ:
log_lines += advanced_lines
log_lines += residual_line
log_lines += cpu_time_lines
extra_title_line1 = '' if extra_logger_title_line1 is None else extra_logger_title_line1
extra_title_line2 = '' if extra_logger_title_line2 is None else extra_logger_title_line2
title_line_1 = '|' + ' | '.join([a for (a, b, c) in log_lines])[:-1] + '|' + extra_title_line1
title_line_2 = '|' + ' | '.join([b for (a, b, c) in log_lines])[:-1] + '|' + extra_title_line2
log_str = '|' + ' | '.join([c for (a, b, c) in log_lines])[:-1] + '|'
line_of_dashes = '-' * (len(title_line_2) - 1)
log_title_str = '\n' + title_line_1 + '\n' + title_line_2 + '\n' + line_of_dashes + '|'
if extra_logger_log is not None:
log_str += extra_logger_log(state,
current_time,
number_of_time_steps,
number_nonlinear_iter,
number_linear_iter)
if number_of_time_steps == 1:
print(log_title_str)
if log_count == log_rate:
log_title_count += 1
log_count = 0
if log_title_count == lines_per_header:
print(line_of_dashes)
print(log_title_str)
log_title_count = 0
print(log_str, flush=True)
return log_count, log_title_count
def odesolve(right_hand_side,
initial_state,
output_times=None,
save_each_step=False,
initial_time=0.,
stop_criteria=None,
stop_at_time=None,
stop_at_steady=None,
minimum_time_step_count=0,
maximum_time_step_count=Inf,
pre_step_callback=None,
post_step_callback=None,
step_update_callback=None,
method=KennedyCarpenterS6P4Q3(SimpleNewtonSolver()),
step_size=PIController(),
linear_setup=None,
linear_solve=None,
linear_setup_rate=1,
mass_setup=None,
mass_matvec=None,
verbose=False,
debug_verbose=False,
log_rate=1,
log_lines_per_header=10,
extra_logger_title_line1=None,
extra_logger_title_line2=None,
extra_logger_log=None,
norm_weighting=1.,
strict_temporal_error_control=False,
nonlinear_solve_must_converge=False,
warn_on_failed_step=False,
return_on_failed_step=False,
time_step_reduction_factor_on_failure=0.8,
time_step_reduction_factor_on_slow_solve=0.8,
time_step_increase_factor_to_force_jacobian=1.05,
time_step_decrease_factor_to_force_jacobian=0.9,
show_solver_stats_in_situ=False,
return_info=False,
throw_on_failure=True,
print_exception_on_failure=True):
"""Solve a time integration problem with a wide variety of solvers, termination options, etc.
Parameters
----------
right_hand_side : callable f(t,q)->r
the right-hand side of the ODE system, in the form f(t, y)
initial_state : np.ndarray
the initial state vector
output_times : np.array
a collection of times at which the state will be returned
save_each_step : bool/Int
set to True to save all data at each time step, or set to a positive integer to specify a step frequency of saving data
initial_time : float
the initial time
stop_criteria : callable(q, t, dt, nt, res)->bool
any data with a call operator (state, t, dt, nt, residual) that returns True to stop time integration
stop_at_time : bool
force time integration to stop at exactly the provided final time
stop_at_steady : bool
force time integration to stop when a steady state is identified, provide either a boolean or a float for the tolerance
minimum_time_step_count : Int
minimum number of time steps that can be run (default: 0)
maximum_time_step_count : Int
maximum number of time steps that can be run (default: Inf)
pre_step_callback : callable f(t,q,nt)
method of the form f(current_time, current_state, number_of_time_steps) called before each step (default: None)
post_step_callback : callable f(t,q,r,nt)
method of the form f(current_time, current_state, residual, number_of_time_steps) called after each step, that can optionally return a modified state vector (default: None)
step_update_callback : callable f(q,dq,e,te,nsc)
method of the form f(state, dstate, time_error, target_error, nonlinear_solve_converged) that checks validity of a state update (default: None)
method : spitfire.time.methods.TimeStepper instance
the time stepper method, defaults to KennedyCarpenterS6P4Q3(SimpleNewtonSolver())
step_size : float/spitfire.time.stepcontrol
the time step controller, either a float (for constant time step) or spitfire.time.stepcontrol class
linear_setup : callable f(t,y,scale)
the linear system setup method, in the form f(t, y, scale), to set up a (scale * J - M) operator
linear_solve : callable f(res)->sol
the linear system solve method, in the form f(residual), to solve (scale * J - M)x = b
linear_setup_rate : Int
the largest number of steps that can occur before setting up the linear projector (default: 1 (every step))
mass_setup : callable f(t,y)
the setup method for the mass matrix/operator, in the form f(t, y), not supported yet, but hopefully soon...
mass_matvec : callabele f(x)->b
the matrix-vector product operator for the mass matrix, in the form f(x) to produce M.dot(x), not supported yet, but hopefully soon...
verbose : bool
whether or not to continually write out the integrator status and some statistics, turn off for best performance (default: False)
debug_verbose : bool
whether or not to write A LOT of information during integration, do not use in any normal situation (default: True)
log_rate : Int
how frequently verbose output should be written, increase or turn off output for best performance (default: 1 = every step)
log_lines_per_header : Int
how many log lines are written between rewriting the header (default: 10)
extra_logger_title_line1 : str
the first line to place above the extra_logger_log text
extra_logger_title_line2 : str
the second line to place above the extra_logger_log text
extra_logger_log : callable f(q,t,nt,nni,nli)
a method of form f(state, time, n_steps, number_nonlinear_iter, number_linear_iter) that adds to the log output
return_info : bool
whether or not to return solver statistics (default: False)
norm_weighting : float/np.ndarray
how the temporal error estimate is weighted in its norm calculation, can be a float or np.array (default: 1)
strict_temporal_error_control : bool
whether or not to enforce that error-controlled adaptive time stepping keeps the error estimate below the target (default: False)
nonlinear_solve_must_converge : bool
whether or not the nonlinear solver in each time step of implicit methods must converge (default: False)
warn_on_failed_step : bool
whether or not to print a warning when a step fails (default: False)
return_on_failed_step : bool
whether or not to return and stop integrating when a step fails (default: False)
time_step_reduction_factor_on_failure : float
factor used in reducing the step size after a step fails, if not returning on failure (default: 0.8)
time_step_reduction_factor_on_slow_solve : float
factor used in reducing the step size after a step is deemed slow by the nonlinear solver (default: 0.8)
time_step_increase_factor_to_force_jacobian : float
how much the time step size must increase on a time step to force setup of the projector (default: 1.05)
time_step_decrease_factor_to_force_jacobian : float
how much the time step size must decrease on a time step to force setup of the projector (default: 0.9)
show_solver_stats_in_situ : bool
whether or not to include the number of nonlinear iterations per step, linear iterations per nonlinear iteration, number of time steps per Jacobian evaluation (projector setup) in the logged output (default: False)
return_info : bool
whether or not to return a dictionary of solver statistics
throw_on_failure : bool
whether or not to throw an exception on integrator/model failure (default: True)
print_exception_on_failure : bool
whether or not to print an exception message on integrator/model failure (default: True)
Returns
-------
Depending on the inputs:
1. output_times is provided: returns an array of output states, and the solver stats dictionary if return_info is True
2. save_each_step is True (or a positive integer frequency): returns an array of times, and an array of output states, and the solver stats dictionary if return_info is True
3. else: returns the final state vector, final time, and final time step, and the solver stats dictionary if return_info is True
"""
if not isinstance(initial_state, np.ndarray):
raise TypeError('Error in Spitfire odesolve, the initial_state argument was not a NumPy array.')
if len(initial_state.shape) > 1:
raise TypeError('Error in Spitfire odesolve, the initial_state argument was not a 1-dimensional NumPy array'
', you may simply need to call ravel() on it.')
if not (isinstance(initial_time, float) or isinstance(initial_time, np.ndarray)):
if isinstance(initial_time, int):
initial_time = float(initial_time)
else:
raise TypeError(
f'Error in Spitfire odesolve, the initial_time, {initial_time}, must be provided as a float.')
if initial_time < 0.:
raise ValueError(f'Error in Spitfire odesolve - the initial time of {initial_time} is negative.')
if stop_at_time is not None:
if not isinstance(stop_at_time, float):
if isinstance(stop_at_time, int):
stop_at_time = float(stop_at_time)
else:
raise TypeError('Error in Spitfire odesolve, the stop_at_time argument must be provided as a float, '
'which is the final time at which integration will cease.')
if initial_time > stop_at_time:
raise ValueError(f'Error in Spitfire odesolve - the initial time of {initial_time} exceeds '
f'the specified final time of {final_time}')
if stop_at_steady is not None:
if not (isinstance(stop_at_steady, bool) or isinstance(stop_at_steady, float)):
raise TypeError('Error in Spitfire odesolve, the stop_at_time argument must be provided as '
'a boolean (default tolerance if True) or a float.')
if not (isinstance(save_each_step, bool) or isinstance(save_each_step, int)):
raise ValueError('Error in Spitfire odesolve, the save_each_step argument must be either True/False '
'or a positive integer (the step frequency at which data is saved).')
else:
if isinstance(save_each_step, int) and save_each_step < 0:
raise ValueError('Error in Spitfire odesolve, the save_each_step argument must be either True/False '
'or a positive integer (the step frequency at which data is saved).')
if output_times is not None:
if stop_at_time is not None:
raise ValueError('Error in Spitfire odesolve, the stop_at_time argument may not be provided if the '
'output_times argument is also in use.')
if stop_at_steady is not None:
raise ValueError('Error in Spitfire odesolve, the stop_at_steady argument may not be provided if the '
'output_times argument is also in use.')
if stop_criteria is not None:
raise ValueError('Error in Spitfire odesolve, the stop_criteria argument may not be provided if the '
'output_times argument is also in use.')
if save_each_step:
raise ValueError('Error in Spitfire odesolve, the save_each_step argument may not be provided if the '
'output_times argument is also in use.')
if np.min(output_times) < initial_time:
raise ValueError('Error in Spitfire odesolve, the provided output_times must be greater than or equal to'
' the initial_time (defaults to 0.)')
ot_list = output_times.tolist()
if len(set(ot_list)) != len(ot_list):
raise ValueError('Error in Spitfire odesolve, the provided output_times must be unique.')
if ot_list != sorted(ot_list):
raise ValueError('Error in Spitfire odesolve, the provided output_times must be increasing.')
if output_times is None and stop_at_time is None and stop_at_steady is None and stop_criteria is None:
raise ValueError('Error in Spitfire odesolve, you have not specified enough information to stop a simulation, '
'you must provide output_times, stop_at_time=tfinal, '
'stop_at_steady=[True or tolerance], '
'or stop_criteria as a function(t, state, residual, nsteps)')
if isinstance(step_size, PIController):
if not method.is_adaptive:
raise TypeError('The method provided {method.name} cannot be used with a PI controller'
' (the default step_size argument), you must set step_size equal to a constant value.')
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
try:
coerce_dt_at_final_step = False
if stop_at_time is not None:
coerce_dt_at_final_step = True
if output_times is not None:
coerce_dt_at_final_step = True
stop_at_time = output_times[-1]
output_states = zeros((output_times.size, initial_state.size))
output_time_idx = 0
if output_times[0] < 1e-14:
output_states[output_time_idx, :] = np.copy(initial_state)
output_time_idx += 1
stop_at_steady_state = stop_at_steady is not None
if stop_at_steady_state:
steady_tolerance = 1.e-4 if isinstance(stop_at_steady, bool) else stop_at_steady
use_finite_difference_jacobian = method.is_implicit and linear_setup is None
build_projector_in_governor = (method.is_implicit and method.nonlinear_solver.setup_projector_in_governor) or \
use_finite_difference_jacobian
eval_linear_setup = True
log_count = 0
log_title_count = 0
linear_setup_count = 0
if isinstance(step_size, float):
time_step_value = step_size
step_size = ConstantTimeStep(time_step_value)
_log_header(verbose, method.name)
current_state = np.copy(initial_state)
current_time = np.copy(initial_time)
if save_each_step:
t_list = [np.copy(current_time)]
solution_list = [np.copy(current_state)]
number_of_time_steps = 0
smallest_step_size = 1.e305
largest_step_size = 0.
time_step_size = step_size.first_step_size()
smallest_step_size = min([smallest_step_size, time_step_size])
largest_step_size = max([largest_step_size, time_step_size])
number_nonlinear_iter = 0
number_linear_iter = 0
number_projector_setup = 0
if use_finite_difference_jacobian:
rhs_from_state = lambda state: right_hand_side(current_time, state)
class DefaultLinearSolver:
def __init__(self):
self.lapack_lhs_factor = None
self.diag_indices = diag_indices(initial_state.size)
def setup(self, t, state, prefactor):
j = finite_difference_jacobian(rhs_from_state, rhs_from_state(state), state) * prefactor
j[self.diag_indices] -= 1.
self.lapack_lhs_factor = lapack_lu_factor(j)[:2]
def solve(self, residual):
return lapack_lu_solve(self.lapack_lhs_factor[0],
self.lapack_lhs_factor[1],
residual)[0], 1, True
dls = DefaultLinearSolver()
linear_setup = dls.setup
linear_solve = dls.solve
continue_time_stepping = True
if method.is_implicit:
method_coeff = method.implicit_coefficient
cpu_time_0 = timer.perf_counter()
while continue_time_stepping:
if output_times is not None and current_time + time_step_size > output_times[output_time_idx]:
time_step_size = output_times[output_time_idx] - current_time
if coerce_dt_at_final_step and current_time + time_step_size > stop_at_time:
time_step_size = stop_at_time - current_time
if pre_step_callback is not None:
pre_step_callback(current_time, current_state, number_of_time_steps)
if method.is_implicit:
if build_projector_in_governor and eval_linear_setup:
linear_setup(current_time, current_state, time_step_size * method_coeff)
number_projector_setup += 1
linear_setup_count += 1
if mass_matvec is None:
mass_matvec = lambda x, *args: x
step_output = method.single_step(current_state,
current_time,
time_step_size,
right_hand_side,
lambda t, x: linear_setup(t, x, time_step_size * method_coeff),
linear_solve,
mass_setup,
mass_matvec)
dstate = step_output.solution_update
time_error = step_output.temporal_error
nliter = step_output.nonlinear_iter
liter = step_output.linear_iter
nlsuccess = step_output.nonlinear_converged
nlisslow = step_output.slow_nonlinear_convergence
number_projector_setup += step_output.projector_setups if step_output.projector_setups is not None else 0
residual = norm(dstate * norm_weighting, ord=np.Inf) / time_step_size
recent_time_step_size = time_step_size
if _check_state_update(debug_verbose, current_state, dstate,
time_error, step_size.target_error(), nlsuccess,
strict_temporal_error_control,
nonlinear_solve_must_converge,
step_update_callback):
current_state += dstate
current_time += time_step_size
number_of_time_steps += 1
number_nonlinear_iter = number_nonlinear_iter + nliter if nliter is not None else 'n/a'
number_linear_iter = number_linear_iter + liter if liter is not None else 'n/a'
if post_step_callback is not None:
psco = post_step_callback(current_time, current_state, residual, number_of_time_steps)
current_state = current_state if psco is None else np.copy(psco)
if output_times is not None and current_time >= output_times[output_time_idx]:
output_states[output_time_idx, :] = np.copy(current_state)
output_time_idx += 1
if save_each_step:
if isinstance(save_each_step, bool) or \
(isinstance(save_each_step, int) and not (number_of_time_steps % save_each_step)):
t_list.append(np.copy(current_time))
solution_list.append(np.copy(current_state))
log_count, log_title_count = _write_log(verbose,
show_solver_stats_in_situ,
log_count,
log_rate,
log_title_count,
log_lines_per_header,
extra_logger_title_line1,
extra_logger_title_line2,
extra_logger_log,
current_state,
current_time,
time_step_size,
residual,
number_of_time_steps,
number_nonlinear_iter,
number_linear_iter,
number_projector_setup,
timer.perf_counter() - cpu_time_0)
time_step_size = step_size(number_of_time_steps, time_step_size, step_output)
if method.is_implicit:
eval_linear_setup, time_step_size, linear_setup_count = _check_linear_setup(debug_verbose,
nlsuccess,
nlisslow,
time_step_size,
recent_time_step_size,
linear_setup_count,
linear_setup_rate,
time_step_reduction_factor_on_slow_solve,
time_step_reduction_factor_on_failure,
time_step_increase_factor_to_force_jacobian,
time_step_decrease_factor_to_force_jacobian)
else:
time_step_size, eval_linear_setup = _process_failed_step(debug_verbose,
time_step_size,
return_on_failed_step,
time_step_reduction_factor_on_failure,
warn_on_failed_step)
smallest_step_size = min([smallest_step_size, time_step_size])
largest_step_size = max([largest_step_size, time_step_size])
if stop_criteria is not None:
continue_time_stepping = not stop_criteria(current_time, current_state,
residual, number_of_time_steps)
if number_of_time_steps < minimum_time_step_count:
continue_time_stepping = True
if number_of_time_steps > maximum_time_step_count:
continue_time_stepping = False
if coerce_dt_at_final_step and current_time >= stop_at_time:
continue_time_stepping = False
if stop_at_steady_state and residual < steady_tolerance:
continue_time_stepping = False
total_runtime = timer.perf_counter() - cpu_time_0
if verbose:
print('\nIntegration successfully completed!')
print('\nStatistics:')
print('- number of time steps :', number_of_time_steps)
print('- final simulation time:', current_time)
print('- smallest time step :', smallest_step_size)
print('- average time step :', current_time / number_of_time_steps)
print('- largest time step :', largest_step_size)
print('\n CPU time')
print('- total (s) : {:.6e}'.format(total_runtime))
print('- per step (ms): {:.6e}'.format(1.e3 * total_runtime / number_of_time_steps))
if method.is_implicit:
print('\n Nonlinear iterations')
print('- total : {:}'.format(number_nonlinear_iter))
print('- per step: {:.1f}'.format(number_nonlinear_iter / number_of_time_steps))
print('\n Linear iterations')
print('- total : {:}'.format(number_linear_iter))
print('- per step : {:.1f}'.format(number_linear_iter / number_of_time_steps))
print('- per nliter: {:.1f}'.format(number_linear_iter / number_nonlinear_iter))
print('\n Jacobian setups')
print('- total : {:}'.format(number_projector_setup))
print('- steps per : {:.1f}'.format(number_of_time_steps / number_projector_setup))
print('- nliter per: {:.1f}'.format(number_nonlinear_iter / number_projector_setup))
print('- liter per : {:.1f}'.format(number_linear_iter / number_projector_setup))
_log_footer(verbose, total_runtime)
stats_dict = {'success': True,
'time steps': number_of_time_steps,
'simulation time': current_time,
'total cpu time (s)': total_runtime}
if method.is_implicit:
stats_dict.update({'nonlinear iter': number_nonlinear_iter,
'linear iter': number_linear_iter,
'Jacobian setups': number_projector_setup})
except Exception as error:
stats_dict = {'success': False}
if print_exception_on_failure:
print(f'Spitfire odesolve caught the following Exception during time integration:\n')
logger.exception(error)
logging.disable(level=logging.DEBUG)
if throw_on_failure:
raise ValueError('odesolve failed to integrate the system due to an Exception being caught - see above')
logging.disable(level=logging.DEBUG)
if output_times is not None:
if return_info:
return output_states, stats_dict
else:
return output_states
elif save_each_step:
if return_info:
return array(t_list), array(solution_list), stats_dict
else:
return array(t_list), array(solution_list)
else:
if return_info:
return current_state, current_time, time_step_size, stats_dict
else:
return current_state, current_time, time_step_size
<file_sep>"""
This module defines containers for tabulated chemistry libraries and solution trajectories
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
import numpy as np
import pickle as pickle
from copy import copy, deepcopy
import shutil
import os
class Dimension(object):
"""A class to contain details of a particular independent variable in a structured library
**Constructor**: specify a name and list of values
Parameters
----------
name : str
the name of the mechanism - hyphens and spaces may not be used here, use underscore separators
values: np.array
the values of the independent variable in the grid
"""
def __init__(self, name: str, values: np.array, log_scaled=False):
self._name = name
self._values = np.copy(values)
self._min = np.min(values)
self._max = np.max(values)
self._npts = values.size
self._log_scaled = log_scaled
if not name.isidentifier():
raise ValueError(f'Error in building Dimension "{name}", the name cannot contain hyphens or spaces '
f'(it must be a valid Python variable name, '
f'note that you can check this with name.isidentifier())')
if len(self._values.shape) != 1:
raise ValueError(f'Error in building Dimension "{name}", the values object must be one-dimensional.'
f' Use the ravel() method to flatten your data.')
if self._values.size != np.unique(self._values).size:
raise ValueError(f'Error in building structured dimension "{name}"'
', duplicate values were identified!')
def __str__(self):
return f'Dimension "{self._name}" spanning [{self._min}, {self._max}] with {self._npts} points'
def __repr__(self):
return f'Spitfire Dimension(name="{self._name}", min={self._min}, max={self._max}, npts={self._npts})'
@property
def name(self):
"""Obtain the name of the independent variable"""
return self._name
@property
def values(self):
"""Obtain the one-dimensional np.array of the specified values of this independent variable"""
return self._values
@property
def min(self):
return self._min
@property
def max(self):
return self._max
@property
def npts(self):
return self._npts
@property
def log_scaled(self):
return self._log_scaled
def _get_dict_for_file_save(self):
return {'name': self._name, 'values': self._values, 'log_scaled': self._log_scaled}
class LibraryIndexError(IndexError):
pass
class Library(object):
"""A container class for tabulated datasets over structured grids.
Upon constructing the Library object, the following properties are made available on the instance for each Dimension
library.[dimension_name]_name
library.[dimension_name]_values
library.[dimension_name]_min
library.[dimension_name]_max
library.[dimension_name]_npts
library.[dimension_name]_grid = multidimensional meshgrid of the data
**Constructor**: specify the argument list of dimensions defining the grid
Parameters
----------
dimensions : argument list of Dimension instances and/or (name, values) tuples
the dimensions that define the grid
"""
def _set_grid(self):
grid = np.meshgrid(*[self._dims[d].values for d in self._dims], indexing='ij')
self._grid_shape = grid[0].shape
self._grid_size = grid[0].size
for i, d in enumerate(self._dims):
setattr(self, self._dims[d].name, d)
setattr(self, self._dims[d].name + '_grid', np.copy(grid[i]))
for a in self._dims[d].__dict__:
setattr(self, self._dims[d].name + a, getattr(self._dims[d], a))
def __init__(self, *dimensions):
self._dims = dict(
{d.name: (Dimension(d.name, d.values, d.log_scaled) if isinstance(d, Dimension) else Dimension(d[0], d[1], False if len(d) == 2 else d[2])) for d in
dimensions})
self._props = dict()
self._dims_ordering = dict()
for i, d in enumerate(dimensions):
self._dims_ordering[i] = d.name
if dimensions:
self._set_grid()
self._extra_attributes = dict()
def scale_dimension(self, dim_name, multiplier):
try:
self.remap_dimension(dim_name, lambda x: multiplier * x)
except KeyError:
raise KeyError(f'Invalid dimension name \"{dim_name}\" provided to scale_dimension() on library {self}.')
def remap_dimension(self, dim_name, mapping):
try:
self._dims[dim_name] = Dimension(dim_name, mapping(self._dims[dim_name].values))
self._set_grid()
except KeyError:
raise KeyError(f'Invalid dimension name \"{dim_name}\" provided to remap_dimension() on library {self}.')
@property
def extra_attributes(self):
"""Get the extra attributes dictionary of this Library,
which will be saved in the instance and in any pickle or text files.
Use this to retain any random information that you might like later,
such as authorship notes, dates, recommendations for use, etc."""
return self._extra_attributes
def __getstate__(self):
return dict(dimensions={d: self._dims[d]._get_dict_for_file_save() for d in self._dims},
dim_ordering=self._dims_ordering,
properties=self._props,
extra_attributes=self._extra_attributes)
def __setstate__(self, instance_dict):
ordered_dims = list([None] * len(instance_dict['dimensions'].keys()))
for index in instance_dict['dim_ordering']:
name = instance_dict['dim_ordering'][index]
d = instance_dict['dimensions'][name]
ordered_dims[index] = Dimension(d['name'], d['values'], log_scaled=(False if 'log_scaled' not in d else d['log_scaled']))
self.__init__(*ordered_dims)
for prop in instance_dict['properties']:
self[prop] = instance_dict['properties'][prop]
ea = dict() if 'extra_attributes' not in instance_dict else instance_dict['extra_attributes']
for p in ea:
self.extra_attributes[p] = ea[p]
def save_to_file(self, file_name):
"""Save a library to a specified file using pickle"""
with open(file_name, 'wb') as file_output:
pickle.dump(self, file_output)
def save_to_text_directory(self, output_directory, ravel_order='F', format='%.14e'):
"""
Dump the contents of a library to a set of easy-to-process text files in a directory.
Note that file names of property bulk data files will have spaces replaced by underscores.
Note that the preferred method of saving data for later use with Spitfire is the save_to_file method,
which dumps compressed data with pickle, Python's native serialization tool. The Library.load_from_file method
can then be used to reload data into Python, which is significantly faster than loading from text files.
This method of dumping data does not natively support reloading data from the text files,
and is simply meant to provide data that is easy to load in other codes (e.g., C++, Fortran, or Matlab codes).
Parameters
----------
output_directory: str
where to save the files (a new directory will be made, and an existing one will be removed with permission)
ravel_order: str
row-major ('C') or column-major ('F') flattening of multidimensional property arrays, default is 'F' for column-major,
which flattens the first dimension first, second dimension second, and so on
format: str
string format for numbers sent to NumPy savetxt function, default is '%.14e'
"""
out_dir_exists = os.path.isdir(output_directory)
proceed = input(
f'Library.save_to_text_directory(): remove existing directory {output_directory}? (y/any=no) ') if out_dir_exists else 'y'
if proceed != 'y':
print('Library.save_to_text_directory(): cannot override existing output directory, aborting!')
return
if out_dir_exists:
shutil.rmtree(output_directory)
os.mkdir(output_directory)
md_iv_file_name = os.path.join(output_directory, 'metadata_independent_variables.txt')
md_dv_file_name = os.path.join(output_directory, 'metadata_dependent_variables.txt')
md_ea_file_name = os.path.join(output_directory, 'metadata_user_defined_attributes.txt')
bd_prefix = 'bulkdata'
prop_names_underscored = dict({p: p.replace(' ', '_') for p in self.props})
with open(md_iv_file_name, 'w') as f:
for d in self.dims:
f.write(d.name + '\n')
with open(md_dv_file_name, 'w') as f:
for p in self.props:
f.write(prop_names_underscored[p] + '\n')
with open(md_ea_file_name, 'w') as f:
f.write(str(self._extra_attributes))
for d in self.dims:
np.savetxt(os.path.join(output_directory, f'{bd_prefix}_ivar_{d.name}.txt'),
d.values, fmt=format)
for p in self.props:
np.savetxt(os.path.join(output_directory, f'{bd_prefix}_dvar_{prop_names_underscored[p]}.txt'),
self[p].ravel(order=ravel_order), fmt=format)
@classmethod
def load_from_file(cls, file_name):
"""Load a library from a specified file name with pickle (following save_to_file)"""
with open(file_name, 'rb') as file_input:
pickled_data = pickle.load(file_input)
if isinstance(pickled_data, dict): # for compatibility with v1.0 outputs that were pickled as dictionaries
library = Library()
library.__setstate__(pickled_data)
return library
else:
return pickled_data
def __copy__(self):
new_dimensions = []
for d in self.dims:
new_d = Dimension(d.name, d.values, d.log_scaled)
new_dimensions.append(new_d)
new_library = Library(*new_dimensions)
for p in self.props:
new_library[p] = self[p]
for ea in self.extra_attributes:
new_library.extra_attributes[ea] = self.extra_attributes[ea]
return new_library
def __deepcopy__(self, *args, **kwargs):
new_dimensions = []
for d in self.dims:
new_d = Dimension(d.name, np.copy(d.values), d.log_scaled)
new_dimensions.append(new_d)
new_library = Library(*new_dimensions)
for p in self.props:
new_library[p] = np.copy(self[p])
for ea in self.extra_attributes:
new_library.extra_attributes[ea] = self.extra_attributes[ea]
return new_library
@classmethod
def copy(cls, library):
"""Shallow copy of a library into a new one"""
return copy(library)
@classmethod
def deepcopy(cls, library):
"""Deep copy of a library into a new one"""
return deepcopy(library)
@classmethod
def squeeze(cls, library):
"""Produce a new library from another by removing dimensions with only one value,
for instance after slicing, lib_new = Library.squeeze(library[:, 0]).
Note that if all dimensions are removed, for instance in Library.squeeze(library[0, 1]),
a dictionary of the scalar values in the following form is returned instead of a new library:
{'dimensions': {name1: value1, name2: value2, ...}, 'properties': {prop1: value1, ...}, 'extra_attributes': {...}}"""
new_dimensions = []
for d in library.dims:
if d.values.size > 1:
new_d = Dimension(d.name, d.values, d.log_scaled)
new_dimensions.append(new_d)
if not new_dimensions:
return dict(properties=dict({p: np.squeeze(library[p]) for p in library.props}),
dimensions=dict({d.name: (np.squeeze(d.values), d.log_scaled) for d in library.dims}),
extra_attributes=library.extra_attributes)
else:
new_library = Library(*new_dimensions)
for p in library.props:
new_library[p] = np.squeeze(library[p])
for ea in library.extra_attributes:
new_library.extra_attributes[ea] = library.extra_attributes[ea]
return new_library
def __setitem__(self, quantity, values):
"""Use the bracket operator, as in lib['myprop'] = values, to add a property defined on the grid
The np.ndarray of values must be shaped correctly"""
if isinstance(values, np.ndarray):
if values.shape != self._grid_shape:
raise ValueError(f'The shape of the "{quantity}" array does not conform to that of the library. '
f'Given shape = {values.shape}, grid shape = {self._grid_shape}')
if quantity not in self._props:
self._props[quantity] = values.view()
else:
self._props[quantity][:] = values
elif isinstance(values, float) or isinstance(values, int):
values = float(values) if isinstance(values, int) else values
if quantity not in self._props:
self._props[quantity] = self.get_empty_dataset()
self._props[quantity].fill(values)
else:
raise TypeError(f'In Library[arg] = values, values must be a np.ndarray or float, received {values}')
def __getitem__(self, *slices):
"""Either return the data for a property, as in lib['myprop'], when a single string is provided,
or obtain an entirely new library that is sliced according to the arguments, as in lib[:, 1:-1, 0, :].
Only standard slice operations are allowed.
Note that this will preserve the full dimensionality of a library, even if a dimension has a single value.
Use the Library.squeeze(lib) class method to remove single-value dimensions if desired.
Furthermore, this will return a view to the original data. To copy a library, use the copy() and deepcopy()
methods from the Python copy package or on the Library class (l2 = Library.copy(l1), same for deepcopy)."""
arg1 = slices[0]
if isinstance(arg1, str):
if len(slices) == 1:
return self._props[arg1]
else:
raise LibraryIndexError(f'Library[...] can either take a single string or standard Python slices, '
f'you provided it {slices}')
else:
if isinstance(slices[0], slice):
slices = slices
if slices[0] == slice(None, None, None) and len(self.dims) > 1:
slices = tuple([slice(None, None, None)] * len(self.dims))
else:
slices = slices[0]
if len(slices) != len(self.dims):
raise LibraryIndexError(
f'Library[...] slicing must be given the same number of arguments as there are dimensions, '
f'you provided {len(slices)} slices to a Library of dimension {len(self.dims)}')
new_dimensions = []
for d, s in zip(self.dims, slices):
if not isinstance(s, slice) and not isinstance(s, int):
raise LibraryIndexError(f'Library[...] can either take a single string or standard Python slices, '
f'you provided it {slices}')
new_d = Dimension(d.name, np.array([d.values[s]]) if isinstance(d.values[s], float) else d.values[s], d.log_scaled)
new_dimensions.append(new_d)
new_library = Library(*new_dimensions)
for p in self.props:
new_library[p] = self._props[p][slices].reshape(new_library.shape)
for ea in self.extra_attributes:
new_library.extra_attributes[ea] = self.extra_attributes[ea]
return new_library
def __contains__(self, prop):
return prop in self._props
def __str__(self):
return f'\nSpitfire Library with {len(self.dims)} dimensions ' + \
f'and {len(list(self._props.keys()))} properties\n' + \
f'------------------------------------------\n' + \
f'\n'.join([f'{i + 1}. {str(d)}' for (i, d) in enumerate(self.dims)]) + \
f'\n------------------------------------------\n' + \
f'\n'.join([f'{k:20}, min = {np.min(self._props[k])} max = {np.max(self._props[k])}' for k in
self._props.keys()]) + \
f'\nExtra attributes: {self.extra_attributes}' + \
f'\n------------------------------------------\n'
def __repr__(self):
return f'\nSpitfire Library(ndim={len(self.dims)}, nproperties={len(list(self._props.keys()))})\n' + \
'\n'.join([f'{i + 1}. {str(d)}' for (i, d) in enumerate(self.dims)]) + \
f'\nProperties: [{", ".join(list(self._props.keys()))}]' + \
f'\nExtra attributes: {self.extra_attributes}'
@property
def size(self):
return self._grid_size
@property
def shape(self):
return self._grid_shape
@property
def props(self):
"""Obtain a list of the names of properties set on the library"""
return list(self._props.keys())
@property
def dims(self):
"""Obtain the ordered list of the Dimension objects associated with the library"""
dims = []
for d in self._dims_ordering:
dims.append(self._dims[self._dims_ordering[d]])
return dims
@property
def dim_names(self):
"""Obtain the ordered list of the Dimension object names"""
return [d.name for d in self.dims]
def dim(self, name):
"""Obtain a Dimension object by name"""
return self._dims[name]
def get_empty_dataset(self):
"""Obtain an empty dataset in the shape of the grid, to enable filling one point, line, plane, etc. at a time,
before then possibly setting a library property with the data"""
return np.ndarray(self._grid_shape)
def add_empty_property(self, name):
self._props[name] = self.get_empty_dataset()
def remove(self, *quantities):
"""Remove quantities (argument list of strings) from the library"""
for quantity in quantities:
self._props.pop(quantity)
<file_sep>import pickle
from os.path import abspath, join
def run():
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.chemistry.reactors import HomogeneousReactor
import numpy as np
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
mechanism = ChemicalMechanismSpec(cantera_input=xml, group_name='h2-burke')
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
mix = mechanism.mix_for_equivalence_ratio(1.0, fuel, air)
mix.TP = 1200., 101325.
reactor_dict = {'cp, adiabatic': HomogeneousReactor(mechanism, mix, 'isobaric', 'adiabatic', 'closed'),
'cp, isothermal': HomogeneousReactor(mechanism, mix, 'isobaric', 'isothermal', 'closed'),
'cv, adiabatic': HomogeneousReactor(mechanism, mix, 'isochoric', 'adiabatic', 'closed'),
'cv, isothermal': HomogeneousReactor(mechanism, mix, 'isochoric', 'isothermal', 'closed')}
sol_dict = dict()
for r in reactor_dict:
output = reactor_dict[r].integrate_to_steady()
Y = np.array([output['mass fraction ' + s].copy() for s in mechanism.species_names])
sol_dict[r] = (output.time_values.copy(), output['temperature'], Y)
return sol_dict
if __name__ == '__main__':
output = run()
gold_pkl = abspath(join('tests', 'reactor', 'closed_reactors', 'gold.pkl'))
with open(gold_pkl, 'wb') as file_output:
pickle.dump(output, file_output)
<file_sep>import unittest
import numpy as np
from scipy import integrate as scipy_integrate
from spitfire.time.integrator import odesolve
class TestComparisonToSciPyIntegrate(unittest.TestCase):
def test_lotka_volterra(self):
a = 1.
b = 0.1
c = 1.5
d = 0.75
def rhs(t, x):
return np.array([a * x[0] - b * x[0] * x[1],
-c * x[1] + d * b * x[0] * x[1]])
t = np.linspace(0., 10., 40)
X0 = np.array([10., 5.])
X, infodict = scipy_integrate.odeint(lambda xv, tv: rhs(tv, xv), X0, t, full_output=True)
Xs, stats = odesolve(rhs, X0, t, return_info=True)
self.assertTrue(np.max(np.abs((X - Xs) / X)) < 1e-6)
if __name__ == '__main__':
unittest.main()
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
// an inexact Jacobian option, magic number = 1
// this one does not consider sensitivities of the three-body enhancement term or falloff terms
#include "combustion_kernels.h"
#include <cmath>
#include <stdexcept>
#define GRIFFON_SUM2(prop) (prop(0) + prop(1))
#define GRIFFON_SUM3(prop) (GRIFFON_SUM2(prop) + prop(2))
#define GRIFFON_SUM4(prop) (GRIFFON_SUM3(prop) + prop(3))
#define GRIFFON_SUM5(prop) (GRIFFON_SUM4(prop) + prop(4))
#define GRIFFON_SUM6(prop) (GRIFFON_SUM5(prop) + prop(5))
#define GRIFFON_SUM7(prop) (GRIFFON_SUM6(prop) + prop(6))
#define GRIFFON_SUM8(prop) (GRIFFON_SUM7(prop) + prop(7))
#define ARRHENIUS(coef) ((coef)[0] * std::exp((coef)[1] * logT - (coef)[2] * invT))
#define ARRHENIUS_SENS_OVER_K(coef) (invT * ((coef)[1] + (coef)[2] * invT)) // \frac{1}{k}\pder{k}{T}
#define THD_BDY(i) (tb_efficiencies[(i)] * y[tb_indices[(i)]])
#define THD_BDY_NOY(i) (tb_efficiencies[(i)])
#define GIBBS(i) (net_stoich[(i)] * specG[net_indices[(i)]])
#define DBDT(i) (net_stoich[(i)] * dBdTSpec[net_indices[(i)]])
namespace griffon
{
void CombustionKernels::prod_rates_sens_no_tbaf(const double &temperature, const double &density, const double &mmw,
const double *y, double *out_prodrates, double *out_prodratessens) const
{
const double T = temperature;
const double rho = density;
const double Mmix = mmw;
const int ns = mechanismData.phaseData.nSpecies;
const int nr = mechanismData.reactionData.nReactions;
const double standardStatePressure = mechanismData.phaseData.referencePressure;
const double invGasConstant = 1. / mechanismData.phaseData.Ru;
const auto Msp = mechanismData.phaseData.molecularWeights.data();
const auto invMsp = mechanismData.phaseData.inverseMolecularWeights.data();
double kf = 0, Kc = 0, kr = 0, Rr = 0, Rnet = 0, q = 0, Ctbaf = 0, pr = 0, fCent = 0, flfConc = 0, fTroe = 0, gTroe = 0;
double dRnetdrho = 0, dRnetdT = 0, dKcdToverKc = 0;
double dqdrho = 0, dqdT = 0, aTroe = 0, bTroe = 0;
double nsTmp = 0;
double specG[ns];
double dBdTSpec[ns];
double dRnetdY[ns - 1];
double dqdY[ns - 1];
for (int i = 0; i < ns; ++i)
{
out_prodrates[i] = 0.;
specG[i] = 0.;
}
for (int i = 0; i < (ns + 1) * (ns + 1); ++i)
{
out_prodratessens[i] = 0.;
}
const double invT = 1. / T;
const double logT = std::log(T);
const double invM = 1. / Mmix;
const double ct = rho * invM;
const double invRu = invGasConstant;
const double Ru = 1. / invRu;
for (int n = 0; n < ns; ++n)
{
const auto polyType = mechanismData.heatCapacityData.types[n];
const auto &c = mechanismData.heatCapacityData.coefficients[n];
const auto &c9 = mechanismData.heatCapacityData.nasa9Coefficients[n];
switch (polyType)
{
case CpType::NASA7:
if (T <= c[0])
{
specG[n] = c[13] + T * (c[8] - c[14] - c[8] * logT - T * (c[9] + T * (c[10] + T * (c[11] + T * c[12]))));
dBdTSpec[n] = invRu * ((c[8] - Ru) * invT + c[9] + T * (2 * c[10] + T * (3 * c[11] + T * 4 * c[12])) + c[13] * invT * invT);
}
else
{
specG[n] = c[6] + T * (c[1] - c[7] - c[1] * logT - T * (c[2] + T * (c[3] + T * (c[4] + T * c[5]))));
dBdTSpec[n] = invRu * ((c[1] - Ru) * invT + c[2] + T * (2 * c[3] + T * (3 * c[4] + T * 4 * c[5])) + c[6] * invT * invT);
}
break;
case CpType::NASA9:
{
const auto nregions = static_cast<int>(c9[0]);
for(int k=0; k<nregions; ++k)
{
const int region_start_idx = 1 + k * 11;
if(T < c9[region_start_idx + 1] || k == nregions - 1)
{
const auto *a = &(c9[region_start_idx + 2]);
specG[n] = a[7] - 0.5 * a[0] * invT + a[1] * (logT + 1.0) - T * (a[2] * (logT - 1.0) + a[8] + T * (0.5 * a[3] + T * (0.1666666666666666 * a[4] + T * (0.0833333333333333 * a[5] + T * 0.05 * a[6]))));
dBdTSpec[n] = invRu * (invT * (a[2] - Ru + invT * (a[7] + a[1] * logT - invT * a[0])) + 0.5 * a[3] + T * (a[4] * 0.3333333333333333 + T * (0.25 * a[5] + T * 0.2 * a[6])));
break;
}
}
}
break;
case CpType::CONST:
specG[n] = c[1] + c[3] * (T - c[0]) - T * (c[2] + c[3] * (logT - std::log(c[0])));
dBdTSpec[n] = invT * (Msp[n] * invRu * (c[3] - invT * (c[3] * c[0] - c[1])) - 1);
break;
default:
{
throw std::runtime_error("unsupported thermo model");
}
}
}
for (int r = 0; r < nr; ++r)
{
const auto &rxnData = mechanismData.reactionData.reactions[r];
const auto &tb_indices = rxnData.tb_indices;
const auto &tb_efficiencies = rxnData.tb_efficiencies;
const auto n_tb = rxnData.n_tb;
const auto &rc_indices = rxnData.reactant_indices;
const auto &rc_stoich = rxnData.reactant_stoich;
const auto &rc_invmw = rxnData.reactant_invmw;
const auto n_rc = rxnData.n_reactants;
const auto &pd_indices = rxnData.product_indices;
const auto &pd_stoich = rxnData.product_stoich;
const auto &pd_invmw = rxnData.product_invmw;
const auto n_pd = rxnData.n_products;
const auto &net_indices = rxnData.net_indices;
const auto &net_stoich = rxnData.net_stoich;
const auto &net_mw = rxnData.net_mw;
const auto n_net = rxnData.n_net;
const auto &kCoefs = rxnData.kFwdCoefs;
const auto &kPCoefs = rxnData.kPressureCoefs;
const auto baseEff = rxnData.thdBdyDefault;
const auto &troe = rxnData.troeParams;
Rnet = 0.;
dRnetdrho = 0.;
dRnetdT = 0.;
dqdrho = 0.;
dqdT = 0.;
for (int i = 0; i < ns - 1; ++i)
{
dqdY[i] = 0.0;
dRnetdY[i] = 0.0;
}
switch (rxnData.kForm)
{
case RateConstantTForm::CONSTANT:
kf = kCoefs[0];
break;
case RateConstantTForm::LINEAR:
kf = kCoefs[0] * T;
break;
case RateConstantTForm::QUADRATIC:
kf = kCoefs[0] * T * T;
break;
case RateConstantTForm::RECIPROCAL:
kf = kCoefs[0] * invT;
break;
case RateConstantTForm::ARRHENIUS:
kf = ARRHENIUS(kCoefs);
break;
}
#define C_R(i) (y[rc_indices[i]] * rho * rc_invmw[i])
#define C_P(i) (y[pd_indices[i]] * rho * pd_invmw[i])
switch (rxnData.forwardOrder)
{
case ReactionOrder::ONE:
Rnet = kf * C_R(0);
break;
case ReactionOrder::TWO:
Rnet = kf * C_R(0) * C_R(0);
break;
case ReactionOrder::ONE_ONE:
Rnet = kf * C_R(0) * C_R(1);
break;
case ReactionOrder::ONE_ONE_ONE:
Rnet = kf * C_R(0) * C_R(1) * C_R(2);
break;
case ReactionOrder::TWO_ONE:
Rnet = kf * C_R(0) * C_R(0) * C_R(1);
break;
case ReactionOrder::ONE_TWO:
Rnet = kf * C_R(0) * C_R(1) * C_R(1);
break;
default:
Rnet = kf;
for (int i = 0; i != n_rc; ++i)
{
switch (rc_stoich[i])
{
case 1:
Rnet *= C_R(i);
break;
case 2:
Rnet *= C_R(i) * C_R(i);
break;
case 3:
Rnet *= C_R(i) * C_R(i) * C_R(i);
break;
}
}
break;
}
dRnetdrho = Rnet / ct * invM * rxnData.sumReactantStoich;
dRnetdT = Rnet * ARRHENIUS_SENS_OVER_K(kCoefs);
bool nsIsReactant = false;
int nsReactantIdx = -1;
for (int sridx = 0; sridx < n_rc; ++sridx)
{
int s = rc_indices[sridx];
if (s != ns - 1)
{
switch (rxnData.forwardOrder)
{
case ReactionOrder::ONE:
dRnetdY[s] = kf * rho * invMsp[s];
break;
case ReactionOrder::TWO:
dRnetdY[s] = kf * rho * invMsp[s] * 2. * C_R(sridx);
break;
case ReactionOrder::ONE_ONE:
switch (sridx)
{
case 0:
dRnetdY[s] = kf * rho * invMsp[s] * C_R(1);
break;
case 1:
dRnetdY[s] = kf * rho * invMsp[s] * C_R(0);
break;
}
break;
case ReactionOrder::ONE_ONE_ONE:
switch (sridx)
{
case 0:
dRnetdY[s] = kf * rho * invMsp[s] * C_R(1) * C_R(2);
break;
case 1:
dRnetdY[s] = kf * rho * invMsp[s] * C_R(0) * C_R(2);
break;
case 2:
dRnetdY[s] = kf * rho * invMsp[s] * C_R(0) * C_R(1);
break;
}
break;
case ReactionOrder::TWO_ONE:
switch (sridx)
{
case 0:
dRnetdY[s] = kf * rho * invMsp[s] * 2. * C_R(0) * C_R(1);
break;
case 1:
dRnetdY[s] = kf * rho * invMsp[s] * C_R(0) * C_R(0);
break;
}
break;
case ReactionOrder::ONE_TWO:
switch (sridx)
{
case 0:
dRnetdY[s] = kf * rho * invMsp[s] * C_R(1) * C_R(1);
break;
case 1:
dRnetdY[s] = kf * rho * invMsp[s] * 2. * C_R(1) * C_R(0);
break;
}
break;
default:
switch (rc_stoich[sridx])
{
case 1:
dRnetdY[s] = kf * rho * invMsp[s];
break;
case 2:
dRnetdY[s] = kf * rho * invMsp[s] * 2. * C_R(sridx);
break;
case 3:
dRnetdY[s] = kf * rho * invMsp[s] * 3. * C_R(sridx) * C_R(sridx);
break;
}
for (int i = 0; i < n_rc; ++i)
{
if (!(i == sridx))
{
switch (rc_stoich[i])
{
case 1:
dRnetdY[s] *= C_R(i);
break;
case 2:
dRnetdY[s] *= C_R(i) * C_R(i);
break;
case 3:
dRnetdY[s] *= C_R(i) * C_R(i) * C_R(i);
break;
}
}
}
}
}
else
{
nsIsReactant = true;
nsReactantIdx = sridx;
}
}
if (nsIsReactant)
{
switch (rxnData.forwardOrder)
{
case ReactionOrder::ONE:
nsTmp = kf * rho * invMsp[ns - 1];
break;
case ReactionOrder::TWO:
nsTmp = kf * rho * invMsp[ns - 1] * 2. * C_R(nsReactantIdx);
break;
case ReactionOrder::ONE_ONE:
switch (nsReactantIdx)
{
case 0:
nsTmp = kf * rho * invMsp[ns - 1] * C_R(1);
break;
case 1:
nsTmp = kf * rho * invMsp[ns - 1] * C_R(0);
break;
}
break;
case ReactionOrder::ONE_ONE_ONE:
switch (nsReactantIdx)
{
case 0:
nsTmp = kf * rho * invMsp[ns - 1] * C_R(1) * C_R(2);
break;
case 1:
nsTmp = kf * rho * invMsp[ns - 1] * C_R(0) * C_R(2);
break;
case 2:
nsTmp = kf * rho * invMsp[ns - 1] * C_R(0) * C_R(1);
break;
}
break;
case ReactionOrder::TWO_ONE:
switch (nsReactantIdx)
{
case 0:
nsTmp = kf * rho * invMsp[ns - 1] * 2. * C_R(0) * C_R(1);
break;
case 1:
nsTmp = kf * rho * invMsp[ns - 1] * C_R(0) * C_R(0);
break;
}
break;
case ReactionOrder::ONE_TWO:
switch (nsReactantIdx)
{
case 0:
nsTmp = kf * rho * invMsp[ns - 1] * C_R(1) * C_R(1);
break;
case 1:
nsTmp = kf * rho * invMsp[ns - 1] * 2. * C_R(1) * C_R(0);
break;
}
break;
default:
nsTmp = kf * rho * invMsp[ns - 1];
switch (rc_stoich[nsReactantIdx])
{
case 1:
break;
case 2:
nsTmp *= 2. * C_R(nsReactantIdx);
break;
case 3:
nsTmp *= 3. * C_R(nsReactantIdx) * C_R(nsReactantIdx);
break;
}
for (int i = 0; i < n_rc; ++i)
{
if (!(i == nsReactantIdx))
{
switch (rc_stoich[i])
{
case 1:
nsTmp *= C_R(i);
break;
case 2:
nsTmp *= C_R(i) * C_R(i);
break;
case 3:
nsTmp *= C_R(i) * C_R(i) * C_R(i);
break;
}
}
}
}
for (int s = 0; s < ns - 1; ++s)
{
dRnetdY[s] -= nsTmp;
}
}
if (rxnData.reversible)
{
const int sumStoich = rxnData.sumStoich;
switch (n_net)
{
case 3:
Kc = std::exp(
-(sumStoich * std::log(standardStatePressure * invT * invRu) - invT * invRu * (GRIFFON_SUM3(GIBBS))));
dKcdToverKc = -GRIFFON_SUM3(DBDT);
break;
case 2:
Kc = std::exp(
-(sumStoich * std::log(standardStatePressure * invT * invRu) - invT * invRu * (GRIFFON_SUM2(GIBBS))));
dKcdToverKc = -GRIFFON_SUM2(DBDT);
break;
case 4:
Kc = std::exp(
-(sumStoich * std::log(standardStatePressure * invT * invRu) - invT * invRu * (GRIFFON_SUM4(GIBBS))));
dKcdToverKc = -GRIFFON_SUM4(DBDT);
break;
case 5:
Kc = std::exp(
-(sumStoich * std::log(standardStatePressure * invT * invRu) - invT * invRu * (GRIFFON_SUM5(GIBBS))));
dKcdToverKc = -GRIFFON_SUM5(DBDT);
break;
}
kr = kf / Kc;
switch (rxnData.reverseOrder)
{
case ReactionOrder::ONE:
Rr = kr * C_P(0);
break;
case ReactionOrder::TWO:
Rr = kr * C_P(0) * C_P(0);
break;
case ReactionOrder::ONE_ONE:
Rr = kr * C_P(0) * C_P(1);
break;
case ReactionOrder::ONE_ONE_ONE:
Rr = kr * C_P(0) * C_P(1) * C_P(2);
break;
case ReactionOrder::TWO_ONE:
Rr = kr * C_P(0) * C_P(0) * C_P(1);
break;
case ReactionOrder::ONE_TWO:
Rr = kr * C_P(0) * C_P(1) * C_P(1);
break;
default:
Rr = kr;
for (int i = 0; i < n_pd; ++i)
{
switch (abs(pd_stoich[i]))
{
case 1:
Rr *= C_P(i);
break;
case 2:
Rr *= C_P(i) * C_P(i);
break;
case 3:
Rr *= C_P(i) * C_P(i) * C_P(i);
break;
}
}
break;
}
Rnet -= Rr;
dRnetdrho -= Rr / ct * invM * rxnData.sumProductStoich;
dRnetdT -= Rr * (ARRHENIUS_SENS_OVER_K(kCoefs) - dKcdToverKc);
bool nsIsProduct = false;
int nsProductIdx = -1;
for (int sridx = 0; sridx < n_pd; ++sridx)
{
int s = pd_indices[sridx];
if (s != ns - 1)
{
switch (rxnData.reverseOrder)
{
case ReactionOrder::ONE:
dRnetdY[s] -= kr * rho * invMsp[s];
break;
case ReactionOrder::TWO:
dRnetdY[s] -= kr * rho * invMsp[s] * 2. * C_P(sridx);
break;
case ReactionOrder::ONE_ONE:
switch (sridx)
{
case 0:
dRnetdY[s] -= kr * rho * invMsp[s] * C_P(1);
break;
case 1:
dRnetdY[s] -= kr * rho * invMsp[s] * C_P(0);
break;
}
break;
case ReactionOrder::ONE_ONE_ONE:
switch (sridx)
{
case 0:
dRnetdY[s] -= kr * rho * invMsp[s] * C_P(1) * C_P(2);
break;
case 1:
dRnetdY[s] -= kr * rho * invMsp[s] * C_P(0) * C_P(2);
break;
case 2:
dRnetdY[s] -= kr * rho * invMsp[s] * C_P(0) * C_P(1);
break;
}
break;
case ReactionOrder::TWO_ONE:
switch (sridx)
{
case 0:
dRnetdY[s] -= kr * rho * invMsp[s] * 2. * C_P(0) * C_P(1);
break;
case 1:
dRnetdY[s] -= kr * rho * invMsp[s] * C_P(0) * C_P(0);
break;
}
break;
case ReactionOrder::ONE_TWO:
switch (sridx)
{
case 0:
dRnetdY[s] -= kr * rho * invMsp[s] * C_P(1) * C_P(1);
break;
case 1:
dRnetdY[s] -= kr * rho * invMsp[s] * 2. * C_P(1) * C_P(0);
break;
}
break;
default:
// first: build the part sensitive to species s
switch (std::abs(pd_stoich[sridx]))
{
case 1:
nsTmp = kr * rho * invMsp[s];
break;
case 2:
nsTmp = kr * rho * invMsp[s] * 2. * C_P(sridx);
break;
case 3:
nsTmp = kr * rho * invMsp[s] * 3. * C_P(sridx) * C_P(sridx);
break;
default:
nsTmp = kr * rho * invMsp[s] * std::abs(pd_stoich[sridx]) * std::pow(C_P(sridx), std::abs(pd_stoich[sridx]) - 1);
break;
}
// second: build the rest of the rate law product
for (int i = 0; i < n_pd; ++i)
{
if (!(i == sridx))
{
switch (std::abs(pd_stoich[i]))
{
case 1:
nsTmp *= C_P(i);
break;
case 2:
nsTmp *= C_P(i) * C_P(i);
break;
case 3:
nsTmp *= C_P(i) * C_P(i) * C_P(i);
break;
default:
nsTmp *= std::pow(C_P(i), std::abs(pd_stoich[i]));
break;
}
}
}
// finally: offset the sensitivity
dRnetdY[s] -= nsTmp;
}
}
else
{
nsIsProduct = true;
nsProductIdx = sridx;
}
}
if (nsIsProduct)
{
switch (rxnData.reverseOrder)
{
case ReactionOrder::ONE:
nsTmp = kr * rho * invMsp[ns - 1];
break;
case ReactionOrder::TWO:
nsTmp = kr * rho * invMsp[ns - 1] * 2. * C_P(nsProductIdx);
break;
case ReactionOrder::ONE_ONE:
switch (nsProductIdx)
{
case 0:
nsTmp = kr * rho * invMsp[ns - 1] * C_P(1);
break;
case 1:
nsTmp = kr * rho * invMsp[ns - 1] * C_P(0);
break;
}
break;
case ReactionOrder::ONE_ONE_ONE:
switch (nsProductIdx)
{
case 0:
nsTmp = kr * rho * invMsp[ns - 1] * C_P(1) * C_P(2);
break;
case 1:
nsTmp = kr * rho * invMsp[ns - 1] * C_P(0) * C_P(2);
break;
case 2:
nsTmp = kr * rho * invMsp[ns - 1] * C_P(0) * C_P(1);
break;
}
break;
case ReactionOrder::TWO_ONE:
switch (nsProductIdx)
{
case 0:
nsTmp = kr * rho * invMsp[ns - 1] * 2. * C_P(0) * C_P(1);
break;
case 1:
nsTmp = kr * rho * invMsp[ns - 1] * C_P(0) * C_P(0);
break;
}
break;
case ReactionOrder::ONE_TWO:
switch (nsProductIdx)
{
case 0:
nsTmp = kr * rho * invMsp[ns - 1] * C_P(1) * C_P(1);
break;
case 1:
nsTmp = kr * rho * invMsp[ns - 1] * 2. * C_P(1) * C_P(0);
break;
}
break;
default:
switch (std::abs(pd_stoich[nsProductIdx]))
{
case 1:
nsTmp = kr * rho * invMsp[ns - 1];
break;
case 2:
nsTmp = kr * rho * invMsp[ns - 1] * 2. * C_P(nsProductIdx);
break;
case 3:
nsTmp *= kr * rho * invMsp[ns - 1] * 3. * C_P(nsProductIdx) * C_P(nsProductIdx);
break;
}
for (int i = 0; i != n_pd; ++i)
{
if (!(i == nsProductIdx))
{
switch (std::abs(pd_stoich[i]))
{
case 1:
nsTmp *= C_P(i);
break;
case 2:
nsTmp *= C_P(i) * C_P(i);
break;
case 3:
nsTmp *= C_P(i) * C_P(i) * C_P(i);
break;
}
}
}
}
for (int s = 0; s < ns - 1; ++s)
{
dRnetdY[s] += nsTmp;
}
}
}
double t1exp = 0;
double t2exp = 0;
double t3exp = 0;
double log10pr = 0;
double log10fcent = 0;
double kp_over_kf = 0;
switch (rxnData.type)
{
case RateType::SIMPLE:
Ctbaf = 1.0;
break;
case RateType::THIRD_BODY:
Ctbaf = baseEff * ct;
for (int i = 0; i < n_tb; ++i)
Ctbaf += rho * THD_BDY(i);
break;
case RateType::LINDEMANN:
flfConc = baseEff * ct;
for (int i = 0; i < n_tb; ++i)
flfConc = flfConc + rho * THD_BDY(i);
kp_over_kf = ARRHENIUS(kPCoefs) / kf;
pr = kp_over_kf * flfConc;
Ctbaf = pr / (1. + pr);
break;
case RateType::TROE:
t1exp = std::exp(-T / troe[1]);
t2exp = std::exp(-T / troe[2]);
t3exp = std::exp(-invT * troe[3]);
switch (rxnData.troeForm)
{
case TroeTermsPresent::T123:
fCent = (1 - troe[0]) * t1exp + troe[0] * t2exp + t3exp;
break;
case TroeTermsPresent::T12:
fCent = (1 - troe[0]) * t1exp + troe[0] * t2exp;
break;
case TroeTermsPresent::T1:
fCent = (1 - troe[0]) * t1exp;
break;
case TroeTermsPresent::T23:
fCent = troe[0] * t2exp + t3exp;
break;
case TroeTermsPresent::T2:
fCent = troe[0] * t2exp;
break;
case TroeTermsPresent::T13:
fCent = (1 - troe[0]) * t1exp + t3exp;
break;
case TroeTermsPresent::T3:
fCent = t3exp;
break;
case TroeTermsPresent::NO_TROE_TERMS:
default:
{
throw std::runtime_error("no troe terms flagged for evaluation");
}
}
flfConc = baseEff * ct;
for (int i = 0; i < n_tb; ++i)
flfConc = flfConc + rho * THD_BDY(i);
kp_over_kf = ARRHENIUS(kPCoefs) / kf;
pr = kp_over_kf * flfConc;
log10pr = std::log10(std::max(pr, 1.e-300));
log10fcent = std::log10(std::max(fCent, 1.e-300));
aTroe = log10pr - 0.67 * log10fcent - 0.4;
bTroe = -0.14 * log10pr - 1.1762 * log10fcent + 0.806;
gTroe = 1 / (1 + (aTroe / bTroe) * (aTroe / bTroe));
fTroe = std::pow(fCent, gTroe);
Ctbaf = fTroe * pr / (1 + pr);
break;
default:
{
throw std::runtime_error("unidentified reaction");
}
}
q = Rnet * Ctbaf;
dqdrho = dRnetdrho * Ctbaf;
dqdT = dRnetdT * Ctbaf;
for (int s = 0; s < ns - 1; ++s)
{
dqdY[s] = dRnetdY[s] * Ctbaf;
}
for (int i = 0; i < n_net; ++i)
{
const int index = net_indices[i];
const double factor = net_stoich[i] * net_mw[i];
out_prodrates[index] -= factor * q;
out_prodratessens[index] -= factor * dqdrho;
out_prodratessens[index + (ns + 1)] -= factor * dqdT;
for (int s = 0; s < ns - 1; ++s)
{
out_prodratessens[index + (ns + 1) * (2 + s)] -= factor * dqdY[s];
}
}
}
}
} // namespace griffon
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
/*
* This file includes Griffon's combustion chemistry kernels, predominantly methods
* for reaction rates of large mechanisms and ODE/PDE methods needed for solving
* reactor and flamelet models.
*/
#ifndef GRIFFON_COMBUSTION_H
#define GRIFFON_COMBUSTION_H
#include <map>
#include <string>
#include <vector>
#include <array>
#include "blas_lapack_kernels.h"
namespace griffon
{
/*
* @class CombustionKernels
* @brief objects of this class contain mechanism data and do thermodynamics, kinetics, reactor, and flamelet calculations
*/
class CombustionKernels
{
public:
/*
* @enum CpType
* @brief types of heat capacity polynomials
*
* - CONSTANT: constant heat capacity (calorically perfect gas)
* - NASA7 : 7-coefficient polynomial form heat capacity
*/
enum class CpType
{
UNKNOWN,
CONST,
NASA7,
NASA9
};
/*
* @enum RateType
* @brief types of reaction rates
*
* - SIMPLE: simple reactions with a canonical mass-action rate law
* - THIRD_BODY: third-body-enhanced reactions
* - LINDEMANN: pressure falloff reaction of a Lindemann form
* - TROE: pressure falloff reaction with a Troe parameterization
*/
enum class RateType
{
UNKNOWN,
SIMPLE,
THIRD_BODY,
LINDEMANN,
TROE
};
/*
* @class RateConstantTForm
* @brief type of rate constant temperature dependence
* This is important in preventing unnecessary expensive exponential evaluations,
* such as when the activation energy is zero.
*/
enum class RateConstantTForm
{
CONSTANT,
LINEAR,
QUADRATIC,
RECIPROCAL,
ARRHENIUS
};
/*
* @class TroeTermsPresent
* @brief which of the Troe terms are present in a Troe falloff reaction rate
*/
enum class TroeTermsPresent
{
NO_TROE_TERMS,
T1,
T2,
T12,
T3,
T13,
T23,
T123
};
/*
* @class ReactionOrder
* @brief special versions of stoichiometry coefficients in a reaction
* This is helpful in avoiding exponentiation of concentrations and simplifies Jacobian calculation as well.
*/
enum class ReactionOrder
{
ONE,
TWO,
ONE_ONE,
TWO_ONE,
ONE_TWO,
ONE_ONE_ONE,
OTHER
};
/*
* @brief get a map from element names to element molecular weights
* This is used in computing species molecular weights.
*/
std::map<std::string, double>
get_element_mw_map();
/*
* @class PhaseData
* @brief data describing elements and species present in a gas model
*/
struct PhaseData
{
int nElements;
int nSpecies;
std::vector<std::string> elementNames;
std::vector<std::string> speciesNames;
std::map<std::string, int> speciesIndices;
std::vector<double> molecularWeights;
std::vector<double> inverseMolecularWeights;
double referenceTemperature;
double referencePressure;
double Ru;
};
/*
* @class HeatCapacityData
* @brief heat capacity polynomial coefficients
*
* template parameters:
* NCP: maximum allowed number of coefficients
*/
template <int NCP>
struct HeatCapacityData
{
std::vector<std::array<double, NCP>> coefficients;
std::vector<std::vector<double>> nasa9Coefficients;
std::vector<double> minTemperatures;
std::vector<double> maxTemperatures;
std::vector<CpType> types;
};
/*
* @class ReactionData
* @brief reaction data, just a container for ReactionRateData objects
*
* template parameters:
* NSR: maximum allowed number of reactants, products, net species in a reaction, or of species in a nonelementary rate expression
*/
template <int NSR>
struct ReactionData
{
/*
* @class ReactionRateData
* @brief data and setters for single chemical reactions
*
* reactant_*: data corresponding to reactants (consumed in the forward reaction)
* product_*: data correspodning to products (consumed in the reverse reaction, if reversible)
* net_*: data corresponding to species that do not appear equally on each side of the reaction (net production/consumption)
* tb_*: data corresponding to species with specified three-body efficiencies
* special_*: data corresponding to species with specified orders in a nonelementary reaction
*
* hasOrders: true if the reaction is nonelementary, false if elementary
*/
struct ReactionRateData
{
std::array<int, NSR> reactant_indices;
std::array<int, NSR> reactant_stoich;
std::array<double, NSR> reactant_invmw;
int n_reactants = 0;
std::array<int, NSR> product_indices;
std::array<int, NSR> product_stoich;
std::array<double, NSR> product_invmw;
int n_products = 0;
std::array<int, NSR> net_indices;
std::array<int, NSR> net_stoich;
std::array<double, NSR> net_mw;
int n_net = 0;
std::vector<int> tb_indices;
std::vector<double> tb_invmw;
std::vector<double> tb_efficiencies;
int n_tb = 0;
bool hasOrders = false;
std::array<int, NSR> special_indices;
std::array<double, NSR> special_orders;
std::array<bool, NSR> special_nonzero;
std::array<double, NSR> special_invmw;
int n_special = 0;
bool is_dense = false;
int n_sens = 0;
std::vector<int> sens_indices;
double thdBdyDefault;
std::array<double, 3> kFwdCoefs;
std::array<double, 3> kPressureCoefs;
std::array<double, 4> troeParams;
bool reversible;
RateType type;
RateConstantTForm kForm;
TroeTermsPresent troeForm;
ReactionOrder forwardOrder;
ReactionOrder reverseOrder;
int sumStoich;
int sumReactantStoich;
int sumProductStoich;
void
set_fwd_pre_exponential(const double &v);
void
set_fwd_temp_exponent(const double &v);
void
set_fwd_activation_energy(const double &v);
void
set_falloff_pre_exponential(const double &v);
void
set_falloff_temp_exponent(const double &v);
void
set_falloff_activation_energy(const double &v);
void
set_reactants(const std::map<std::string, int> &reactants_stoich, const PhaseData &pd);
void
set_products(const std::map<std::string, int> &products_stoich, const PhaseData &pd);
void
set_reactants_or_products(const std::map<std::string, int> &ss_map, const PhaseData &pd,
const bool is_reactants);
void
set_special_orders(const std::map<std::string, double> &orders, const PhaseData &pd);
void
set_three_body_efficiencies(const std::map<std::string, double> &eff_map, const double &default_efficiency,
const PhaseData &pd);
void
set_troe_parameters(const std::vector<double> &troe_params);
void
finalize(const PhaseData &phaseData);
};
int nReactions;
std::vector<ReactionData::ReactionRateData> reactions;
};
/*
* @class MechanismData
* @brief collection of phase, heat capacity, and reaction data
*/
template <int NSRn, int NCPn>
struct MechanismData
{
PhaseData phaseData;
HeatCapacityData<NCPn> heatCapacityData;
ReactionData<NSRn> reactionData;
static constexpr int NSR = NSRn;
static constexpr int NCP = NCPn;
};
public:
/*
* mechanism data setter methods
*
* To set mechanism data:
* 0. set the reference temperature, pressure, and universal gas constant
* 1. set the elemental molecular weight map (mechanism_set_element_mw_map)
* 2. add elements (mechanism_add_element)
* 3. set reference pressure and temperature (mechanism_set_ref_pressure, mechanism_set_ref_temperature)
* 4. add species with atom maps (mechanism_add_species)
* 5. call mechanism_resize_heat_capacity_data()
* 6. add the heat capacity polynomials with either mechanism_add_const_cp, mechanism_add_nasa7_cp, or mechanism_add_nasa9_cp
* 7. add reactions with the methods below. The *_with_special_orders methods are for nonelementary reactions.
*/
void
mechanism_set_element_mw_map(const std::map<std::string, double> element_mw_map);
void
mechanism_add_element(const std::string &element_name);
void
mechanism_add_species(const std::string &species_name, const std::map<std::string, double> atom_map);
void
mechanism_set_gas_constant(const double &Ru);
void
mechanism_set_ref_pressure(const double &p_ref);
void
mechanism_set_ref_temperature(const double &T_ref);
void
mechanism_resize_heat_capacity_data();
void
mechanism_add_const_cp(const std::string &spec_name, const double &Tmin, const double &Tmax, const double &T0,
const double &h0, const double &s0, const double &cp);
void
mechanism_add_nasa7_cp(const std::string &spec_name, const double &Tmin, const double &Tmid, const double &Tmax,
const std::vector<double> &low_coeffs, const std::vector<double> &high_coeffs);
void
mechanism_add_nasa9_cp(const std::string &spec_name, const double &Tmin, const double &Tmax, const std::vector<double> &coeffs);
void
mechanism_add_reaction_simple(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich, const bool reversible,
const double &fwd_pre_exp_value, const double &fwd_temp_exponent,
const double &fwd_act_energy);
void
mechanism_add_reaction_three_body(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich, const bool reversible,
const double &fwd_pre_exp_value, const double &fwd_temp_exponent,
const double &fwd_act_energy,
const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency);
void
mechanism_add_reaction_Lindemann(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich, const bool reversible,
const double fwd_pre_exp_value, const double fwd_temp_exponent,
const double fwd_act_energy,
const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency, const double flf_pre_exp_value,
const double flf_temp_exponent, const double flf_act_energy);
void
mechanism_add_reaction_Troe(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich, const bool reversible,
const double fwd_pre_exp_value, const double fwd_temp_exponent,
const double fwd_act_energy,
const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency, const double flf_pre_exp_value,
const double flf_temp_exponent, const double flf_act_energy,
const std::vector<double> &troe_parameters);
void
mechanism_add_reaction_simple_with_special_orders(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich,
const bool reversible, const double &fwd_pre_exp_value,
const double &fwd_temp_exponent, const double &fwd_act_energy,
const std::map<std::string, double> &special_orders);
void
mechanism_add_reaction_three_body_with_special_orders(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich,
const bool reversible, const double &fwd_pre_exp_value,
const double &fwd_temp_exponent, const double &fwd_act_energy,
const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency,
const std::map<std::string, double> &special_orders);
void
mechanism_add_reaction_Lindemann_with_special_orders(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich,
const bool reversible, const double fwd_pre_exp_value,
const double fwd_temp_exponent, const double fwd_act_energy,
const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency,
const double flf_pre_exp_value, const double flf_temp_exponent,
const double flf_act_energy,
const std::map<std::string, double> &special_orders);
void
mechanism_add_reaction_Troe_with_special_orders(const std::map<std::string, int> &reactants_stoich,
const std::map<std::string, int> &products_stoich,
const bool reversible, const double fwd_pre_exp_value,
const double fwd_temp_exponent, const double fwd_act_energy,
const std::map<std::string, double> &three_body_efficiencies,
const double &default_efficiency, const double flf_pre_exp_value,
const double flf_temp_exponent, const double flf_act_energy,
const std::vector<double> &troe_parameters,
const std::map<std::string, double> &special_orders);
/*
* general-purpose thermodynamics evaluations
*/
inline double
mixture_molecular_weight(const double *y) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
const auto invMolecularWeights = mechanismData.phaseData.inverseMolecularWeights.data();
return 1. / blas::inner_product(nSpec, y, invMolecularWeights);
}
void
mole_fractions(const double *y, double *x) const;
double
ideal_gas_density(const double &pressure, const double &temperature, const double *y) const;
double
ideal_gas_pressure(const double &density, const double &temperature, const double *y) const;
double
cp_mix(const double &temperature, const double *y) const;
double
cv_mix(const double &temperature, const double *y) const;
double
enthalpy_mix(const double &temperature, const double *y) const;
double
energy_mix(const double &temperature, const double *y) const;
void
species_cp(const double &temperature, double *out_cpspecies) const;
void
cp_sens_T(const double &temperature, const double *y, double *out_cpmixsens, double *out_cpspeciessens) const;
void
species_cv(const double &temperature, double *out_cvspecies) const;
void
species_enthalpies(const double &temperature, double *out_enthalpies) const;
void
species_energies(const double &temperature, double *out_energies) const;
/*
* general-purpose kinetics evaluations
*/
void
production_rates(const double &temperature, const double &density, const double *y, double *out_prodrates) const;
void
prod_rates_primitive_sensitivities(const double &density, const double &temperature, const double *y,
int rates_sensitivity_option, double *out_prodratessens) const;
/*
* reactor RHS and Jacobian methods
*/
void
reactor_rhs_isobaric(const double *state, const double &pressure, const double &inflowTemperature,
const double *inflowY, const double &tau, const double &fluidTemperature,
const double &surfTemperature, const double &hConv, const double &epsRad,
const double &surfaceAreaOverVolume, const int heat_transfer_option, const bool open,
double *out_rhs) const;
void
reactor_jac_isobaric(const double *state, const double &pressure, const double &inflowTemperature,
const double *inflowY, const double &tau, const double &fluidTemperature,
const double &surfTemperature, const double &hConv, const double &epsRad,
const double &surfaceAreaOverVolume, const int heat_transfer_option, const bool open,
const int rates_sensitivity_option, const int sensitivity_transform_option, double *out_rhs,
double *out_jac) const;
void
reactor_rhs_isochoric(const double *state, const double &inflowDensity, const double &inflowTemperature,
const double *inflowY, const double &tau, const double &fluidTemperature,
const double &surfTemperature, const double &hConv, const double &epsRad,
const double &surfaceAreaOverVolume, const int heatTransferOption, const bool open,
double *out_rhs) const;
void
reactor_jac_isochoric(const double *state, const double &inflowDensity, const double &inflowTemperature,
const double *inflowY, const double &tau, const double &fluidTemperature,
const double &surfTemperature, const double &hConv, const double &epsRad,
const double &surfaceAreaOverVolume, const int heatTransferOption, const bool open,
const int rates_sensitivity_option, double *out_rhs, double *out_jac) const;
/*
* flamelet RHS, Jacobian, and post-processor methods
*/
void
flamelet_rhs(const double *state, const double &pressure, const double *oxyState, const double *fuelState,
const bool adiabatic, const double *T_convection, const double *h_convection,
const double *T_radiation, const double *h_radiation, const int &nzi, const double *cmajor,
const double *csub, const double *csup, const double *mcoeff, const double *ncoeff,
const double *dissipationRate, const bool include_enthalpy_flux, const bool include_variable_cp,
const bool use_scaled_heat_loss, double *out_rhs) const;
void
flamelet_jacobian(const double *state, const double &pressure, const double *oxyState, const double *fuelState,
const bool adiabatic, const double *T_convection, const double *h_convection,
const double *T_radiation, const double *h_radiation, const int &nzi, const double *cmajor,
const double *csub, const double *csup, const double *mcoeff, const double *ncoeff,
const double *chi, const bool compute_eigenvalues, const double diffterm,
const bool scale_and_offset, const double prefactor, const int &rates_sensitivity_option,
const int &sensitivity_transform_option, const bool include_enthalpy_flux,
const bool include_variable_cp, const bool use_scaled_heat_loss, double *out_expeig,
double *out_jac) const;
void
flamelet_stencils(const double *dz, const int &nzi, const double *dissipationRate, const double *invLewisNumbers,
double *out_cmajor, double *out_csub, double *out_csup, double *out_mcoeff,
double *out_ncoeff) const;
void
flamelet_jac_indices(const int &nzi, int *out_row_indices, int *out_col_indices) const;
/*
* 2d flamelet methods (preliminary, serial implementation for block-Jacobi PBiCGStab)
*/
void
flamelet2d_rhs(const double *state, const double &pressure, const int &nx, const int &ny, const double *xcp,
const double *xcl, const double *xcr, const double *ycp, const double *ycb, const double *yct,
double *out_rhs) const;
void
flamelet2d_factored_block_diag_jacobian(const double *state, const double &pressure, const int &nx, const int &ny,
const double *xcp, const double *ycp, const double &prefactor,
double *out_values, double *out_factors, int *out_pivots) const;
void
flamelet2d_offdiag_matvec(const double *vec, const int &nx, const int &ny, const double *xcp, const double *xcl,
const double *xcr, const double *ycp, const double *ycb, const double *yct,
const double &prefactor, double *out_matvec) const;
void
flamelet2d_matvec(const double *vec, const int &nx, const int &ny, const double *xcp, const double *xcl,
const double *xcr, const double *ycp, const double *ycb, const double *yct,
const double &prefactor, const double *block_diag_values, double *out_matvec) const;
void
flamelet2d_block_diag_solve(const int &nx, const int &ny, const double *factors, const int *pivots, const double *b,
double *out_x) const;
inline void
extract_y(const double *ynm1, const int n, double *y) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
y[nSpec - 1] = 1.;
for (int j = 0; j < nSpec - 1; ++j)
{
y[j] = ynm1[j];
y[nSpec - 1] -= y[j];
}
}
private:
using MechData = MechanismData<8, 15>;
MechData mechanismData; // note: moving the template integers to CombustionKernels causes Cython problems...
std::map<std::string, double> element_mw_map_;
static constexpr int NSR = MechData::NSR;
static constexpr int NCP = MechData::NCP;
inline void
ideal_gas_density(const double &pressure, const double &temperature, const double &mmw, double *out_density) const
{
*out_density = pressure * mmw / (temperature * mechanismData.phaseData.Ru);
}
inline void
ideal_gas_pressure(const double &density, const double &temperature, const double &mmw, double *out_pressure) const
{
*out_pressure = density * temperature * mechanismData.phaseData.Ru / mmw;
}
void
cp_mix_and_species(const double &temperature, const double *y, double *out_cvmix, double *out_cvspecies) const;
void
cv_mix_and_species(const double &temperature, const double *y, const double &mmw, double *out_cvmix,
double *out_cvspecies) const;
inline void
cv_sens_T(const double &temperature, const double *y, double *out_cvmixsens, double *out_cvspeciessens) const
{
cp_sens_T(temperature, y, out_cvmixsens, out_cvspeciessens);
}
void
production_rates(const double &temperature, const double &density, const double &mmw, const double *y,
double *out_prodrates) const;
void
prod_rates_sens_exact(const double &temperature, const double &density, const double &mmw, const double *y,
double *out_prodrates, double *out_prodratessens) const;
void
prod_rates_sens_no_tbaf(const double &temperature, const double &density, const double &mmw, const double *y,
double *out_prodrates, double *out_prodratessens) const;
void
prod_rates_sens_sparse(const double &temperature, const double &density, const double &mmw, const double *y,
double *out_prodrates, double *out_prodratessens) const;
void
chem_rhs_isobaric(const double &rho, const double &cp, const double *h, const double *w, double *out_rhs) const;
void
heat_rhs_isobaric(const double &temperature, const double &rho, const double &cp, const double &fluidTemperature,
const double &surfTemperature, const double &hConv, const double &epsRad,
const double &surfaceAreaOverVolume, double *out_heatTransferRate) const;
void
mass_rhs_isobaric(const double *y, const double *enthalpies, const double *inflowEnthalpies, const double &rho,
const double &cp, const double *inflowY, const double &tau, double *out_rhs) const;
void
chem_jac_isobaric(const double &pressure, const double &temperature, const double *y, const double &mmw,
const double &rho, const double &cp, const double *cpi, const double &cpsensT, const double *h,
const double *w, const double *wsens, double *out_rhs, double *out_primJac) const;
void
mass_jac_isobaric(const double &pressure, const double &temperature, const double *y, const double &rho,
const double &cp, const double &cpsensT, const double *cpi, const double *enthalpies,
const double *inflowEnthalpies, const double &inflowTemperature, const double *inflowY,
const double &tau, double *out_rhs, double *out_primJac) const;
void
heat_jac_isobaric(const double &temperature, const double &rho, const double &cp, const double &cpsensT,
const double *cpi, const double &convectionTemperature, const double &radiationTemperature,
const double &convectionCoefficient, const double &radiativeEmissivity,
const double &surfaceAreaOverVolume, double *out_heatTransferRate,
double *out_heatTransferRatePrimJac) const;
void
transform_isobaric_primitive_jacobian(const double &rho, const double &pressure, const double &temperature,
const double &mmw, const double *primJac, double *out_jac) const;
void
chem_rhs_isochoric(const double &rho, const double &cv, const double *e, const double *w, double *out_rhs) const;
void
heat_rhs_isochoric(const double &temperature, const double &rho, const double &cv, const double &fluidTemperature,
const double &surfTemperature, const double &hConv, const double &epsRad,
const double &surfaceAreaOverVolume, double *out_heatTransferRate) const;
void
mass_rhs_isochoric(const double *y, const double *energies, const double *inflowEnergies, const double &rho,
const double &inflowRho, const double &pressure, const double &inflowPressure, const double &cv,
const double *inflowY, const double &tau, double *out_rhs) const;
void
chem_jac_isochoric(const double &temperature, const double *y, const double &rho, const double &cv,
const double *cvi, const double &cvsensT, const double *e, const double *w, const double *wsens,
double *out_rhs, double *out_jac) const;
void
mass_jac_isochoric(const double &pressure, const double &inflowPressure, const double &temperature, const double *y,
const double &rho, const double &inflowRho, const double &cv, const double &cvsensT,
const double *cvi, const double *energies, const double *inflowEnergies,
const double &inflowTemperature, const double *inflowY, const double &tau, double *out_rhs,
double *out_jac) const;
void
heat_jac_isochoric(const double &temperature, const double &rho, const double &cv, const double &cvsensT,
const double *cvi, const double &convectionTemperature, const double &radiationTemperature,
const double &convectionCoefficient, const double &radiativeEmissivity,
const double &surfaceAreaOverVolume, double *out_heatTransferRate,
double *out_heatTransferRateJac) const;
public:
void
flamelet_rhs_test1(const double *state, const double &pressure, const double *oxyState, const double *fuelState,
const bool adiabatic, const double *T_convection, const double *h_convection,
const double *T_radiation, const double *h_radiation, const int &nzi, const double *cmajor,
const double *csub, const double *csup, const double *mcoeff, const double *ncoeff,
const double *dissipationRate, const bool include_enthalpy_flux, const bool include_variable_cp,
const bool use_scaled_heat_loss, double *out_rhs) const;
inline const MechData &get_mechanism_data() const
{
return mechanismData;
}
};
} // namespace griffon
#endif // GRIFFON_CALCULATOR_H
<file_sep>Tabulation API Example: Nonadiabatic Flamelet Models
====================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - using ``build_nonadiabatic*`` methods in Spitfire to
build nonadiabatic equilibrium, Burke-Schumann, and SLFM models
This example builds nonadiabatic flamelet models and compares profiles
of the temperature, mass fractions, and enthalpy defect of several
nonadiabatic flamelet tabulation techniques for n-heptane chemistry.
.. code:: ipython3
from spitfire import (ChemicalMechanismSpec,
FlameletSpec,
build_nonadiabatic_defect_eq_library,
build_nonadiabatic_defect_bs_library,
build_nonadiabatic_defect_transient_slfm_library,
build_nonadiabatic_defect_steady_slfm_library)
import matplotlib.pyplot as plt
import numpy as np
mech = ChemicalMechanismSpec(cantera_xml='heptane-liu-hewson-chen-pitsch-highT.xml', group_name='gas')
pressure = 101325.
air = mech.stream(stp_air=True)
air.TP = 300., pressure
fuel = mech.stream('TPX', (485., pressure, 'NXC7H16:1'))
flamelet_specs = {'mech_spec': mech, 'oxy_stream': air, 'fuel_stream': fuel, 'grid_points': 128}
.. code:: ipython3
l_eq = build_nonadiabatic_defect_eq_library(FlameletSpec(**flamelet_specs), verbose=False)
l_bs = build_nonadiabatic_defect_bs_library(FlameletSpec(**flamelet_specs), verbose=False)
.. code:: ipython3
l_ts = build_nonadiabatic_defect_transient_slfm_library(FlameletSpec(**flamelet_specs),
verbose=True,
diss_rate_values=np.array([1e-2, 1e-1, 1e0, 1e1, 1e2]),
diss_rate_log_scaled=True)
.. parsed-literal::
----------------------------------------------------------------------------------
building nonadiabatic (defect) SLFM library
----------------------------------------------------------------------------------
- mechanism: heptane-liu-hewson-chen-pitsch-highT.xml
- 38 species, 105 reactions
- stoichiometric mixture fraction: 0.062
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
building adiabatic SLFM library
----------------------------------------------------------------------------------
- mechanism: heptane-liu-hewson-chen-pitsch-highT.xml
- 38 species, 105 reactions
- stoichiometric mixture fraction: 0.062
----------------------------------------------------------------------------------
1/ 5 (chi_stoich = 1.0e-02 1/s) converged in 7.67 s, T_max = 2249.2
2/ 5 (chi_stoich = 1.0e-01 1/s) converged in 0.52 s, T_max = 2186.1
3/ 5 (chi_stoich = 1.0e+00 1/s) converged in 1.46 s, T_max = 2109.4
4/ 5 (chi_stoich = 1.0e+01 1/s) converged in 3.72 s, T_max = 1998.4
5/ 5 (chi_stoich = 1.0e+02 1/s) converged in 0.18 s, T_max = 1768.7
----------------------------------------------------------------------------------
library built in 13.91 s
----------------------------------------------------------------------------------
expanding (transient) enthalpy defect dimension ...
chi_st = 1.0e-02 1/s converged in 20.59 s
chi_st = 1.0e-01 1/s converged in 19.66 s
chi_st = 1.0e+00 1/s converged in 16.75 s
chi_st = 1.0e+01 1/s converged in 14.22 s
chi_st = 1.0e+02 1/s converged in 12.63 s
----------------------------------------------------------------------------------
enthalpy defect dimension expanded in 83.85 s
----------------------------------------------------------------------------------
Structuring enthalpy defect dimension ...
Initializing ... Done.
Interpolating onto structured grid ...
Progress: 0%--10%--20%--30%--40%--50%--100%
Structured enthalpy defect dimension built in 9.68 s
----------------------------------------------------------------------------------
library built in 107.46 s
----------------------------------------------------------------------------------
.. code:: ipython3
l_ss = build_nonadiabatic_defect_steady_slfm_library(FlameletSpec(**flamelet_specs),
verbose=True,
diss_rate_values=np.array([1e-2, 1e-1, 1e0, 1e1, 1e2]),
diss_rate_log_scaled=True,
solver_verbose=False,
h_stoich_spacing=1.e-3)
.. parsed-literal::
----------------------------------------------------------------------------------
building nonadiabatic (defect) SLFM library
----------------------------------------------------------------------------------
- mechanism: heptane-liu-hewson-chen-pitsch-highT.xml
- 38 species, 105 reactions
- stoichiometric mixture fraction: 0.062
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
building adiabatic SLFM library
----------------------------------------------------------------------------------
- mechanism: heptane-liu-hewson-chen-pitsch-highT.xml
- 38 species, 105 reactions
- stoichiometric mixture fraction: 0.062
----------------------------------------------------------------------------------
1/ 5 (chi_stoich = 1.0e-02 1/s) converged in 7.15 s, T_max = 2249.2
2/ 5 (chi_stoich = 1.0e-01 1/s) converged in 0.45 s, T_max = 2186.1
3/ 5 (chi_stoich = 1.0e+00 1/s) converged in 1.41 s, T_max = 2109.4
4/ 5 (chi_stoich = 1.0e+01 1/s) converged in 3.27 s, T_max = 1998.4
5/ 5 (chi_stoich = 1.0e+02 1/s) converged in 0.17 s, T_max = 1768.7
----------------------------------------------------------------------------------
library built in 12.83 s
----------------------------------------------------------------------------------
expanding (steady) enthalpy defect dimension ...
chi_st = 1.0e-02 1/s converged in 124.93 s
chi_st = 1.0e-01 1/s converged in 47.30 s
chi_st = 1.0e+00 1/s converged in 27.73 s
chi_st = 1.0e+01 1/s converged in 19.77 s
chi_st = 1.0e+02 1/s converged in 35.97 s
----------------------------------------------------------------------------------
enthalpy defect dimension expanded in 255.75 s
----------------------------------------------------------------------------------
Structuring enthalpy defect dimension ...
Initializing ... Done.
Interpolating onto structured grid ...
Progress: 0%--10%--20%--30%--40%--50%--100%
Structured enthalpy defect dimension built in 10.35 s
----------------------------------------------------------------------------------
library built in 278.96 s
----------------------------------------------------------------------------------
.. code:: ipython3
c_ts = 'SpringGreen'
c_ss = 'Indigo'
c_eq = 'DodgerBlue'
c_bs = 'DarkOrange'
ichi1 = 1
ichi2 = 4
fig, axarray = plt.subplots(1, 6, sharex=True, sharey=True)
axarray[0].plot(l_eq.mixture_fraction_values, l_eq['enthalpy_defect'][:, ::2] * 1e-6, '-.', color=c_eq)
axarray[1].plot(l_bs.mixture_fraction_values, l_bs['enthalpy_defect'][:, ::2] * 1e-6, ':', color=c_bs)
axarray[2].plot(l_ts.mixture_fraction_values, l_ts['enthalpy_defect'][:, ichi1, ::4] * 1e-6, '-', color=c_ts)
axarray[3].plot(l_ts.mixture_fraction_values, l_ts['enthalpy_defect'][:, ichi2, ::4] * 1e-6, '-', color=c_ts)
axarray[4].plot(l_ss.mixture_fraction_values, l_ss['enthalpy_defect'][:, ichi1, ::4] * 1e-6, '--', color=c_ss)
axarray[5].plot(l_ss.mixture_fraction_values, l_ss['enthalpy_defect'][:, ichi2, ::4] * 1e-6, '--', color=c_ss)
axarray[0].set_ylabel('enthalpy defect (MJ/kg)')
axarray[0].set_title('equilibrium')
axarray[1].set_title('Burke-Schumann')
axarray[2].set_title('transient SLFM chi_2')
axarray[3].set_title('transient SLFM chi_4')
axarray[4].set_title('steady SLFM chi_2')
axarray[5].set_title('steady SLFM chi_4')
for ax in axarray:
ax.set_xlim([0, 1])
ax.grid()
ax.set_xlabel('$\\mathcal{Z}$')
fig.set_size_inches(16, 6)
plt.show()
fig, axarray = plt.subplots(1, 6, sharex=True, sharey=True)
axarray[0].plot(l_eq.mixture_fraction_values, l_eq['temperature'][:, ::2], '-.', color=c_eq)
axarray[1].plot(l_bs.mixture_fraction_values, l_bs['temperature'][:, ::2], ':', color=c_bs)
axarray[2].plot(l_ts.mixture_fraction_values, l_ts['temperature'][:, ichi1, ::4], '-', color=c_ts)
axarray[3].plot(l_ts.mixture_fraction_values, l_ts['temperature'][:, ichi2, ::4], '-', color=c_ts)
axarray[4].plot(l_ss.mixture_fraction_values, l_ss['temperature'][:, ichi1, ::4], '--', color=c_ss)
axarray[5].plot(l_ss.mixture_fraction_values, l_ss['temperature'][:, ichi2, ::4], '--', color=c_ss)
axarray[0].set_ylabel('temperature (K)')
axarray[0].set_title('equilibrium')
axarray[1].set_title('Burke-Schumann')
axarray[2].set_title('transient SLFM chi_2')
axarray[3].set_title('transient SLFM chi_4')
axarray[4].set_title('steady SLFM chi_2')
axarray[5].set_title('steady SLFM chi_4')
for ax in axarray:
ax.set_xlim([0, 0.4])
ax.grid()
ax.set_xlabel('$\\mathcal{Z}$')
fig.set_size_inches(16, 6)
plt.show()
fig, axarray = plt.subplots(1, 6, sharex=True, sharey=True)
axarray[0].plot(l_eq.mixture_fraction_values, l_eq['mass fraction C2H2'][:, ::2], '-.', color=c_eq)
axarray[1].plot(l_bs.mixture_fraction_values, l_bs['mass fraction C2H2'][:, ::2], ':', color=c_bs)
axarray[2].plot(l_ts.mixture_fraction_values, l_ts['mass fraction C2H2'][:, ichi1, ::4], '-', color=c_ts)
axarray[3].plot(l_ts.mixture_fraction_values, l_ts['mass fraction C2H2'][:, ichi2, ::4], '-', color=c_ts)
axarray[4].plot(l_ss.mixture_fraction_values, l_ss['mass fraction C2H2'][:, ichi1, ::4], '--', color=c_ss)
axarray[5].plot(l_ss.mixture_fraction_values, l_ss['mass fraction C2H2'][:, ichi2, ::4], '--', color=c_ss)
axarray[0].set_ylabel('temperature (K)')
axarray[0].set_title('equilibrium')
axarray[1].set_title('Burke-Schumann')
axarray[2].set_title('transient SLFM chi_2')
axarray[3].set_title('transient SLFM chi_4')
axarray[4].set_title('steady SLFM chi_2')
axarray[5].set_title('steady SLFM chi_4')
axarray[0].set_ylabel('mass fraction C2H2')
for ax in axarray:
ax.set_xlim([0, 1])
ax.grid()
ax.set_xlabel('$\\mathcal{Z}$')
fig.set_size_inches(16, 6)
plt.show()
.. image:: example_nonadiabatic_flamelets_files/example_nonadiabatic_flamelets_5_0.png
.. image:: example_nonadiabatic_flamelets_files/example_nonadiabatic_flamelets_5_1.png
.. image:: example_nonadiabatic_flamelets_files/example_nonadiabatic_flamelets_5_2.png
.. code:: ipython3
from mpl_toolkits.mplot3d import axes3d
from matplotlib.colors import Normalize
fig = plt.figure()
ax = fig.gca(projection='3d')
z = l_ts.mixture_fraction_grid[:, :, 0]
x = np.log10(l_ts.dissipation_rate_stoich_grid[:, :, 0])
for ih in range(0, l_ts.enthalpy_defect_stoich_npts, 6):
dh = l_ts.enthalpy_defect_stoich_values[ih]
ax.contourf(z, x, l_ts['temperature'][:, :, ih], offset=dh / 1.e6,
cmap='inferno', levels=30, norm=Normalize(vmin=300, vmax=2400))
ax.set_zlim([0, 0.7])
ax.set_xlabel('$\\mathcal{Z}$')
ax.set_ylabel('$\\log_{10}\\chi_{\\rm st}$ (Hz)')
ax.set_zlabel('$\\gamma$ (MJ/kg)')
ax.set_zticks([-2.0, -1.5, -1.0, -0.5, 0.0])
ax.set_title('gas temperature (K)')
fig.set_size_inches(8, 8)
plt.show()
fig = plt.figure()
ax = fig.gca(projection='3d')
for ih in range(0, l_ts.enthalpy_defect_stoich_npts, 6):
dh = l_ts.enthalpy_defect_stoich_values[ih]
ax.contourf(z, x, l_ts['mass fraction OH'][:, :, ih], offset=dh / 1.e6,
cmap='Oranges', levels=30, norm=Normalize(vmin=0, vmax=5e-3), alpha=0.8)
ax.set_zlim([0, 0.7])
ax.set_xlabel('$\\mathcal{Z}$')
ax.set_ylabel('$\\log_{10}\\chi_{\\rm st}$ (Hz)')
ax.set_zlabel('$\\gamma$ (MJ/kg)')
ax.set_zticks([-2.0, -1.5, -1.0, -0.5, 0.0])
ax.set_xlim([0, 0.2])
ax.set_title('mass fraction OH')
fig.set_size_inches(8, 8)
plt.show()
.. image:: example_nonadiabatic_flamelets_files/example_nonadiabatic_flamelets_6_0.png
.. image:: example_nonadiabatic_flamelets_files/example_nonadiabatic_flamelets_6_1.png
.. code:: ipython3
fig = plt.figure()
ax = fig.gca(projection='3d')
z = l_ts.mixture_fraction_grid[:, 0, :]
g = l_ts.enthalpy_defect_stoich_grid[:, 0, :] / 1.e6
for ichi in range(0, l_ts.dissipation_rate_stoich_npts):
lchi = np.log10(l_ts.dissipation_rate_stoich_values[ichi])
ax.contourf(z, g + lchi/2, l_ts['temperature'][:, ichi, :], offset=lchi,
cmap='inferno', levels=30, norm=Normalize(vmin=300, vmax=2400), alpha=0.8)
ax.set_zlim([0, 0.7])
ax.set_xlabel('$\\mathcal{Z}$')
ax.set_ylabel('$\\gamma$ (MJ/kg) + $\\log_{10}\\chi_{\\rm st}/2$ (Hz)')
ax.set_zlabel('$\\log_{10}\\chi_{\\rm st}$ (Hz)')
ax.set_zticks([-2, -1, 0, 1, 2])
ax.set_title('gas temperature (K)')
fig.set_size_inches(8, 8)
plt.show()
.. image:: example_nonadiabatic_flamelets_files/example_nonadiabatic_flamelets_7_0.png
<file_sep>import pickle
def run():
from spitfire.time.integrator import odesolve
from spitfire.time.methods import RK4ClassicalS4P4
import numpy as np
def right_hand_side(c, k_ab, k_bc):
"""
Computes the right-hand side function for the ODE system.
Note that time integration requires a function that takes (t, y) as arguments.
To accomodate this, we will write a lambda after defining the rate constants,
which passes the appropriate y value and rate constant to this function (and ignores the time).
:param c: current concentration vector
:param k_ab: the rate constant of the reaction A -> B
:param k_bc: the rate constant of the reaction A + B -> 2C
:return: right-hand side of the ODE system
"""
c_a = c[0]
c_b = c[1]
c_c = c[2]
q_1 = k_ab * c_a
q_2 = k_bc * c_a * c_b
return np.array([-q_1 - q_2, q_1 - q_2, 2. * q_2])
c0 = np.array([1., 0., 0.]) # initial condition
k_ab = 1. # A -> B rate constant
k_bc = 0.2 # A + B -> 2C rate constant
final_time = 10. # final time to integrate to
time_step_size = 0.1 # size of the time step used
t, sol = odesolve(lambda t, y: right_hand_side(y, k_ab, k_bc),
c0,
stop_at_time=final_time,
step_size=time_step_size,
method=RK4ClassicalS4P4(),
save_each_step=True)
return dict({'t': t.copy(), 'sol': sol.copy()})
if __name__ == '__main__':
output = run()
with open('gold.pkl', 'wb') as file_output:
pickle.dump(output, file_output)
<file_sep>"""
This module contains controllers for adaptive time stepping based on embedded temporal error estimation.
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
from numpy import zeros, min, copy
class ConstantTimeStep(object):
"""A simple wrapper class for a constant time step.
**Constructor**:
Parameters
----------
step_size : float
the size of the time step
"""
def __init__(self, step_size):
self.step_size = step_size
def __call__(self, *args, **kwargs):
return self.step_size
def first_step_size(self):
"""Obtain the initial step size"""
return self.step_size
def last_step_size(self):
"""Obtain the most recent step size"""
return self.step_size
def target_error(self):
"""Obtain the most target error, needed here just to avoid a base class"""
return -1.
def step_size_is_constant(self):
"""Whether or not this controller has a constant or variable step size"""
return True
class PIController(object):
"""A PI controller on the embedded temporal error estimate
**Constructor**:
Parameters
----------
kp : float
the modal gain of the proportional control mode (default: 0.06666666667)
ki : float
the modal gain of the integral control mode (default: 0.1333333333)
target_error : float
the target error for the controller (default: 1.e-10)
max_step : float
the maximum allowable time step (default: 1.e-3)
max_ramp : float
the maximum allowable rate of increase of the time step (default: 1.1)
first_step : float
the initial step size (default: 1.e-6)
"""
def __init__(self, kp=0.06666666667, ki=0.1333333333,
target_error=1.e-4, max_step=1.e4,
max_ramp=1.1, first_step=1.e-3):
self._kp = kp
self._ki = ki
self._target_error = target_error
self._max_step = max_step
self._max_ramp = max_ramp
self._first_step = first_step
self._number_of_old_values = 2
self._err_history = zeros(self._number_of_old_values)
self._step_history = zeros(self._number_of_old_values)
def __call__(self, step_count, step, step_output, *args, **kwargs):
error = step_output.temporal_error
if error < 1.e-16:
return min([step * self._max_ramp, self._max_step])
if step_count < self._number_of_old_values - 1:
self._err_history[step_count] = error
self._step_history[step_count] = step
else:
self._err_history[:-1] = self._err_history[1:]
self._step_history[:-1] = self._step_history[1:]
self._err_history[-1] = error
self._step_history[-1] = step
if step_count == 0:
mod = min([self._max_ramp, (self._target_error / error) ** self._ki])
else:
mod = min([self._max_ramp,
(self._target_error / error) ** self._ki * (self._err_history[-1] / error) ** self._kp])
return min([step * mod, self._max_step])
def first_step_size(self):
"""Obtain the initial step size"""
return self._first_step
def last_step_size(self):
"""Obtain the most recent step size"""
return self._step_history[-1]
def target_error(self):
"""Obtain the most target error, needed here just to avoid a base class"""
return self._target_error
def step_size_is_constant(self):
"""Whether or not this controller has a constant or variable step size"""
return False
class CascadeController(object):
"""A two-level cascade control system on the embedded temporal error estimate and the ratio of two estimates.
The stepper method must support multiple embedded error estimates.
**Constructor**:
Parameters
----------
kp : float
the modal gain of the proportional control mode for the error controller (default: 0.06666666667)
ki : float
the modal gain of the integral control mode for the error controller (default: 0.1333333333)
ratio_kp : float
the modal gain of the proportional control mode for the ratio controller (default: 0.1)
ratio_ki : float
the modal gain of the integral control mode for the ratio controller (default: 0.3)
target_ratio : float
the value of the target ratio for the controller (default: 1.e-2)
initial_target_error : float
the initial value of the target error for the controller (default: 1.e-10)
max_step : float
the maximum allowable time step (default: 1.e-3)
max_ramp : float
the maximum allowable rate of increase of the time step (default: 1.1)
first_step : float
the initial step size (default: 1.e-6)
"""
def __init__(self, kp=0.06666666667, ki=0.1333333333,
ratio_kp=0.1, ratio_ki=0.3,
initial_target_error=1.e-10, target_ratio=1.e-2,
max_step=1.e-3, max_ramp=1.1, first_step=1.e-6):
self._kp = kp
self._ki = ki
self._ratio_kp = ratio_kp
self._ratio_ki = ratio_ki
self._target_ratio = target_ratio
self._initial_target_error = initial_target_error
self._target_error = copy(initial_target_error)
self._max_step = max_step
self._max_ramp = max_ramp
self._first_step = first_step
self._number_of_old_values = 2
self._ratio_history = zeros(self._number_of_old_values)
self._err_history = zeros(self._number_of_old_values)
self._step_history = zeros(self._number_of_old_values)
def __call__(self, step_count, step, step_output, *args, **kwargs):
error = step_output.temporal_error
ratio = error / (1.e-12 + step_output.extra_errors[0])
if error < 1.e-16:
return min([step * self._max_ramp, self._max_step])
if step_count < self._number_of_old_values - 1:
self._err_history[step_count] = error
self._ratio_history[step_count] = ratio
self._step_history[step_count] = step
else:
self._err_history[:-1] = self._err_history[1:]
self._ratio_history[:-1] = self._ratio_history[1:]
self._step_history[:-1] = self._step_history[1:]
self._err_history[-1] = error
self._ratio_history[-1] = ratio
self._step_history[-1] = step
if step_count == 0:
mod = min([self._max_ramp, (self._target_error / error) ** self._ki])
err_mod = (self._target_ratio / ratio) ** self._ratio_ki
else:
mod = min([self._max_ramp,
(self._target_error / error) ** self._ki * (self._err_history[-1] / error) ** self._kp])
err_mod = min([self._max_ramp, (self._target_ratio / ratio) ** self._ratio_ki * (
self._ratio_history[-1] / ratio) ** self._ratio_kp])
self._target_error *= err_mod
return min([step * mod, self._max_step])
def first_step_size(self):
"""Obtain the initial step size"""
return self._first_step
def last_step_size(self):
"""Obtain the most recent step size"""
return self._step_history[-1]
def target_error(self):
"""Obtain the most target error, needed here just to avoid a base class"""
return self._target_error
def step_size_is_constant(self):
"""Whether or not this controller has a constant or variable step size"""
return False
class RatioController(object):
"""A PI controller on the ratio of two embedded temporal error estimates
The stepper method must support multiple embedded error estimates.
**Constructor**:
Parameters
----------
kp : float
the modal gain of the proportional control mode (default: 0.1)
ki : float
the modal gain of the integral control mode (default: 0.3)
target_ratio : float
the target error ratio for the controller (default: 1.e-2)
max_step : float
the maximum allowable time step (default: 1.e-3)
max_ramp : float
the maximum allowable rate of increase of the time step (default: 1.1)
first_step : float
the initial step size (default: 1.e-6)
"""
def __init__(self, kp=0.1, ki=0.3,
target_ratio=1.e-2, max_step=1.e-3,
max_ramp=1.1, first_step=1.e-6):
self._kp = kp
self._ki = ki
self._target_ratio = target_ratio
self._max_step = max_step
self._max_ramp = max_ramp
self._first_step = first_step
self._number_of_old_values = 2
self._ratio_history = zeros(self._number_of_old_values)
self._step_history = zeros(self._number_of_old_values)
def __call__(self, step_count, step, step_output, *args, **kwargs):
error = step_output.temporal_error
ratio = error / (1.e-12 + step_output.extra_errors[0])
if error < 1.e-16:
return min([step * self._max_ramp, self._max_step])
if step_count < self._number_of_old_values - 1:
self._ratio_history[step_count] = ratio
self._step_history[step_count] = step
else:
self._ratio_history[:-1] = self._ratio_history[1:]
self._step_history[:-1] = self._step_history[1:]
self._ratio_history[-1] = ratio
self._step_history[-1] = step
if step_count == 0:
mod = min([self._max_ramp, (self._target_ratio / ratio) ** self._ki])
else:
mod = min([self._max_ramp,
(self._target_ratio / ratio) ** self._ki * (self._ratio_history[-1] / ratio) ** self._kp])
return min([step * mod, self._max_step])
def first_step_size(self):
"""Obtain the initial step size"""
return self._first_step
def last_step_size(self):
"""Obtain the most recent step size"""
return self._step_history[-1]
def target_error(self):
"""Obtain the most target error, needed here just to avoid a base class"""
return 1.e305
def step_size_is_constant(self):
"""Whether or not this controller has a constant or variable step size"""
return False
<file_sep>import unittest
import numpy as np
import cantera as ct
import pickle
from os.path import join, abspath
from spitfire import ChemicalMechanismSpec as Mechanism
from spitfire.chemistry.ctversion import check as cantera_version_check
T_range = [300, 1200, 1800]
p_range = [101325, 1013250]
def verify_rates_mechanism(ctsol: ct.Solution, serialize_mech: bool):
mech = Mechanism.from_solution(ctsol)
if serialize_mech:
serialized = pickle.dumps(mech)
mech = pickle.loads(serialized)
tolerance = 1.e-14
def verify_T_p(temp, pres):
valid = True
for mix in [np.ones(ctsol.n_species),
np.array([1., 1.e-8, 1.e-8, 1.e-8, 1.e-8, 1.e-8]),
np.array([1.e-8, 1., 1.e-8, 1.e-8, 1.e-8, 1.e-8]),
np.array([1.e-8, 1.e-8, 1., 1.e-8, 1.e-8, 1.e-8]),
np.array([1.e-8, 1.e-8, 1.e-8, 1., 1.e-8, 1.e-8]),
np.array([1.e-8, 1.e-8, 1.e-8, 1.e-8, 1., 1.e-8]),
np.array([1.e-8, 1.e-8, 1.e-8, 1.e-8, 1.e-8, 1.]),
np.array([1., 1.e-16, 1.e-16, 1.e-16, 1.e-16, 1.e-16]),
np.array([1.e-16, 1., 1.e-16, 1.e-16, 1.e-16, 1.e-16]),
np.array([1.e-16, 1.e-16, 1., 1.e-16, 1.e-16, 1.e-16]),
np.array([1.e-16, 1.e-16, 1.e-16, 1., 1.e-16, 1.e-16]),
np.array([1.e-16, 1.e-16, 1.e-16, 1.e-12, 1., 1.e-16]),
np.array([1.e-16, 1.e-16, 1.e-16, 1.e-12, 1.e-16, 1.])]:
ns = ctsol.n_species
ctsol.TPY = temp, pres, mix
rho = ctsol.density_mass
w_ct = ctsol.net_production_rates * ctsol.molecular_weights
w_gr = np.zeros(ns)
mech.griffon.production_rates(T, rho, ctsol.Y, w_gr)
valid = valid and np.max(np.abs(w_gr - w_ct) / (np.abs(w_ct) + 1.e0)) < tolerance
return valid
pass_test = True
for T in T_range:
for p in p_range:
pass_test = pass_test and verify_T_p(T, p)
return pass_test
def verify_sensitivities_mechanism(ctsol: ct.Solution, serialize_mech: bool):
mech = Mechanism.from_solution(ctsol)
if serialize_mech:
serialized = pickle.dumps(mech)
mech = pickle.loads(serialized)
tolerance = 1.e-2
def verify_T_p(temp, pres):
valid = True
for mix in [np.ones(ctsol.n_species)]:
ns = ctsol.n_species
ctsol.TPY = temp, pres, mix
rho = ctsol.density_mass
jacGR = np.zeros((ns + 1) * (ns + 1))
mech.griffon.prod_rates_primitive_sensitivities(rho, T, ctsol.Y, 0, jacGR)
jacGR = jacGR.reshape((ns + 1, ns + 1), order='F')[:-1, :]
jacFD = np.zeros_like(jacGR)
rhsGR1 = np.zeros(ns)
rhsGR2 = np.zeros(ns)
dT = 1.e-4
dr = 1.e-4
dY = 1.e-4
mech.griffon.production_rates(T, rho + dr, ctsol.Y, rhsGR1)
mech.griffon.production_rates(T, rho - dr, ctsol.Y, rhsGR2)
jacFD[:, 0] = (rhsGR1 - rhsGR2) / dr * 0.5
mech.griffon.production_rates(T + dT, rho, ctsol.Y, rhsGR1)
mech.griffon.production_rates(T - dT, rho, ctsol.Y, rhsGR2)
jacFD[:, 1] = (rhsGR1 - rhsGR2) / dT * 0.5
for spec_idx in range(ns - 1):
Yp = np.copy(ctsol.Y)
Yp[spec_idx] += dY
Yp[-1] -= dY
Ym = np.copy(ctsol.Y)
Ym[spec_idx] -= dY
Ym[-1] += dY
mech.griffon.production_rates(T, rho, Yp, rhsGR1)
mech.griffon.production_rates(T, rho, Ym, rhsGR2)
jacFD[:, 2 + spec_idx] = (rhsGR1 - rhsGR2) / dY * 0.5
scale = np.abs(jacFD) + 1.0
error = np.max(np.abs((jacFD - jacGR) / scale)) > tolerance
if error:
print(f'T = {T}, p = {p}, Y = {mix}')
print('fd:')
for i in range(ns):
for j in range(ns + 1):
print(f'{jacFD[i, j]:12.2e}', end=', ')
print('')
print('gr:')
for i in range(ns):
for j in range(ns + 1):
print(f'{jacGR[i, j]:12.2e}', end=', ')
print('')
print('gr-fd:')
for i in range(ns):
for j in range(ns + 1):
print(f'{jacGR[i, j] - jacFD[i, j]:12.2e}', end=', ')
print('')
valid = valid and not error
return valid
pass_test = True
for T in T_range:
for p in p_range:
pass_test = pass_test and verify_T_p(T, p)
return pass_test
reaction_indices = dict({
'elem_irr_11_11_noN_constant': 0,
'nonelem_lt1_irr_11_11_noN_constant': 1,
'nonelem_lt1gtq_irr_11_11_noN_constant': 2,
'nonelem_gt1_irr_11_11_noN_constant': 3,
'elem_irr_11_11_noN_linear': 4,
'elem_irr_11_11_noN_quadratic': 5,
'elem_irr_11_11_noN_reciprocal': 6,
'elem_irr_11_11_noN_Arrhenius': 7,
'elem_rev_11_11_noN_constant': 8,
'elem_rev_11_11_noN_linear': 9,
'elem_rev_11_11_noN_quadratic': 10,
'elem_rev_11_11_noN_reciprocal': 11,
'elem_rev_11_11_noN_Arrhenius': 12,
'3body_rev_11_11_noN_Arrhenius': 13,
'Lindemann_rev_11_11_noN_Arrhenius': 14,
'Troe_rev_11_11_noN_Arrhenius': 15})
xml = abspath(join('tests', 'test_mechanisms', 'reaction_test_mechanism.yaml'))
def create_test(reaction_key, type, serialize_mech):
def test(self):
if cantera_version_check('pre', 2, 6, None):
species = ct.Species.listFromFile(xml)
ref = ct.Solution(thermo='IdealGas',
kinetics='GasKinetics',
species=species)
reactions = ct.Reaction.listFromFile(xml, ref)[reaction_indices[reaction_key]]
else:
species = ct.Species.list_from_file(xml)
ref = ct.Solution(thermo='IdealGas',
kinetics='GasKinetics',
species=species)
reactions = ct.Reaction.list_from_file(xml, ref)[reaction_indices[reaction_key]]
sol = ct.Solution(thermo='IdealGas',
kinetics='GasKinetics',
species=species,
reactions=[reactions])
if type == 'rates':
self.assertTrue(verify_rates_mechanism(sol, serialize_mech))
elif type == 'sensitivities':
self.assertTrue(verify_sensitivities_mechanism(sol, serialize_mech))
return test
class Accuracy(unittest.TestCase):
pass
for reaction_key in reaction_indices:
for quantity in ['rates', 'sensitivities']:
for serialize_mech in [False, True]:
setattr(Accuracy, 'test_' + quantity + '_' + reaction_key + \
f'{"_serialized_mech" if serialize_mech else ""}',
create_test(reaction_key,
quantity,
serialize_mech))
if __name__ == '__main__':
unittest.main()
<file_sep>Tabulation API Example: Methane Shear Layer
===========================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
In this demonstration we show how to build several adiabatic chemistry
models for running a flow-resolved shear layer DNS calculation. We can
easily dilute the methane fuel with Nitrogen to set the stoichiometric
mixture fraction to 0.5, and further set the density of the air stream
to control the momentum ratio across the shear layer. Spitfire and
Cantera make it easy to set this up. After generating the tables we use
Cantera to compute quantities like the density and the chemical heat
release rate.
.. code:: ipython3
from spitfire import (ChemicalMechanismSpec,
FlameletSpec,
build_adiabatic_eq_library,
build_adiabatic_bs_library,
build_adiabatic_slfm_library)
import matplotlib.pyplot as plt
import numpy as np
.. code:: ipython3
mech = ChemicalMechanismSpec(cantera_xml='methane-lu30.xml', group_name='methane-lu30')
pressure = 101325.
ch4 = mech.stream('TPY', (298., pressure, 'CH4:1'))
n2 = mech.stream('TPY', (298., pressure, 'N2:1'))
air = mech.stream(stp_air=True)
Next we mix the methane and nitrogen streams so that the stoichiometric
mixture fraction (with air as the oxidizer) is 0.5, using a built-in
Spitfire method.
Then the densities of the fuel and air streams are equated with the
Cantera ``DP`` (density and pressure) setting, allowing the temperature
to change.
.. code:: ipython3
fuel = mech.mix_fuels_for_stoich_mixture_fraction(ch4, n2, 0.5, air)
air.DP = fuel.density, pressure
Next we set up our flamelet specifications and build equilibrium,
Burke-Schumann, and SLFM libraries with the high-level API.
Note that in this example we set ``verbose=True``, which shows
tabulation progress, and ``solver_verbose=False``, which hides internal
details of the solvers, on the SLFM call. Setting
``solver_verbose=True`` to see internal solver details would show that
this configuration, because the high stoichiometric mixture fraction
leads to an extremely weak flame, is challenging to solve. The most
aggressive solvers try and fail on this problem and it ultimately is
solved (less quickly) by a transient approach to the steady state with
implicit Runge-Kutta methods. Typically this is unnecessary.
.. code:: ipython3
flamelet_specs = FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,
fuel_stream=fuel,
grid_points=128)
l_eq = build_adiabatic_eq_library(flamelet_specs, verbose=False)
l_bs = build_adiabatic_bs_library(flamelet_specs, verbose=False)
l_sl = build_adiabatic_slfm_library(flamelet_specs,
diss_rate_values=np.logspace(-4, np.log10(2), 36),
diss_rate_ref='stoichiometric',
verbose=True,
solver_verbose=False)
.. parsed-literal::
----------------------------------------------------------------------------------
building adiabatic SLFM library
----------------------------------------------------------------------------------
- mechanism: methane-lu30.xml
- 30 species, 184 reactions
- stoichiometric mixture fraction: 0.500
----------------------------------------------------------------------------------
1/ 36 (chi_stoich = 1.0e-04 1/s) converged in 2.26 s, T_max = 1505.4
2/ 36 (chi_stoich = 1.3e-04 1/s) converged in 0.03 s, T_max = 1504.8
3/ 36 (chi_stoich = 1.8e-04 1/s) converged in 0.03 s, T_max = 1504.5
4/ 36 (chi_stoich = 2.3e-04 1/s) converged in 0.03 s, T_max = 1504.1
5/ 36 (chi_stoich = 3.1e-04 1/s) converged in 0.93 s, T_max = 1503.7
6/ 36 (chi_stoich = 4.1e-04 1/s) converged in 0.05 s, T_max = 1503.3
7/ 36 (chi_stoich = 5.5e-04 1/s) converged in 6.99 s, T_max = 1502.8
8/ 36 (chi_stoich = 7.2e-04 1/s) converged in 0.04 s, T_max = 1502.2
9/ 36 (chi_stoich = 9.6e-04 1/s) converged in 0.04 s, T_max = 1501.6
10/ 36 (chi_stoich = 1.3e-03 1/s) converged in 0.04 s, T_max = 1501.0
11/ 36 (chi_stoich = 1.7e-03 1/s) converged in 0.04 s, T_max = 1500.2
12/ 36 (chi_stoich = 2.2e-03 1/s) converged in 0.04 s, T_max = 1499.4
13/ 36 (chi_stoich = 3.0e-03 1/s) converged in 0.04 s, T_max = 1498.6
14/ 36 (chi_stoich = 4.0e-03 1/s) converged in 0.04 s, T_max = 1497.6
15/ 36 (chi_stoich = 5.3e-03 1/s) converged in 0.04 s, T_max = 1496.5
16/ 36 (chi_stoich = 7.0e-03 1/s) converged in 0.04 s, T_max = 1495.2
17/ 36 (chi_stoich = 9.3e-03 1/s) converged in 0.04 s, T_max = 1493.8
18/ 36 (chi_stoich = 1.2e-02 1/s) converged in 0.04 s, T_max = 1492.2
19/ 36 (chi_stoich = 1.6e-02 1/s) converged in 0.04 s, T_max = 1490.6
20/ 36 (chi_stoich = 2.2e-02 1/s) converged in 0.04 s, T_max = 1488.9
21/ 36 (chi_stoich = 2.9e-02 1/s) converged in 0.04 s, T_max = 1487.0
22/ 36 (chi_stoich = 3.8e-02 1/s) converged in 0.04 s, T_max = 1485.0
23/ 36 (chi_stoich = 5.1e-02 1/s) converged in 0.04 s, T_max = 1482.8
24/ 36 (chi_stoich = 6.7e-02 1/s) converged in 0.05 s, T_max = 1480.4
25/ 36 (chi_stoich = 8.9e-02 1/s) converged in 0.04 s, T_max = 1477.8
26/ 36 (chi_stoich = 1.2e-01 1/s) converged in 0.04 s, T_max = 1475.2
27/ 36 (chi_stoich = 1.6e-01 1/s) converged in 0.05 s, T_max = 1472.2
28/ 36 (chi_stoich = 2.1e-01 1/s) converged in 0.04 s, T_max = 1468.7
29/ 36 (chi_stoich = 2.8e-01 1/s) converged in 0.04 s, T_max = 1464.8
30/ 36 (chi_stoich = 3.7e-01 1/s) converged in 0.04 s, T_max = 1460.2
31/ 36 (chi_stoich = 4.9e-01 1/s) converged in 0.04 s, T_max = 1455.2
32/ 36 (chi_stoich = 6.4e-01 1/s) converged in 0.05 s, T_max = 1449.6
33/ 36 (chi_stoich = 8.6e-01 1/s) converged in 0.05 s, T_max = 1442.6
34/ 36 (chi_stoich = 1.1e+00 1/s) converged in 0.05 s, T_max = 1434.7
35/ 36 (chi_stoich = 1.5e+00 1/s) converged in 0.06 s, T_max = 1424.6
36/ 36 (chi_stoich = 2.0e+00 1/s) converged in 0.06 s, T_max = 1411.1
----------------------------------------------------------------------------------
library built in 11.94 s
----------------------------------------------------------------------------------
.. code:: ipython3
from spitfire import get_ct_solution_array
from cantera import gas_constant as Ru
def add_density_to_library(lib):
ctsol, shape = get_ct_solution_array(mech, lib)
lib['density'] = ctsol.density_mass.reshape(shape)
def add_hrr_to_library(lib):
ctsol, shape = get_ct_solution_array(mech, lib)
w = ctsol.net_production_rates
h = ctsol.standard_enthalpies_RT * Ru * np.array([ctsol.T]).T
lib['heat_release_rate'] = - np.sum(w * h, axis=1).reshape(shape)
.. code:: ipython3
for l in [l_bs, l_eq, l_sl]:
add_density_to_library(l)
add_hrr_to_library(l)
.. code:: ipython3
chi_indices_plot = [0, 12, 24, 35]
chi_values = l_sl.dim('dissipation_rate_stoich').values
z = l_sl.dim('mixture_fraction').values
for ix, marker in zip(chi_indices_plot, ['s', 'o', 'd', '^']):
plt.plot(z, l_sl['temperature'][:, ix], 'c-',
marker=marker, markevery=4, markersize=5, markerfacecolor='w',
label='SLFM, $\\chi_{\\mathrm{st}}$=' + '{:.0e} 1/s'.format(chi_values[ix]))
plt.plot(z, l_eq['temperature'], 'P-', markevery=4, markersize=5, markerfacecolor='w', label='EQ')
plt.plot(z, l_bs['temperature'], 'H-', markevery=4, markersize=5, markerfacecolor='w', label='BS')
plt.xlabel('mixture fraction')
plt.ylabel('T (K)')
plt.grid(True)
plt.legend(loc='best')
plt.show()
for ix, marker in zip(chi_indices_plot, ['s', 'o', 'd', '^']):
plt.plot(z, l_sl['density'][:, ix], 'c-',
marker=marker, markevery=4, markersize=5, markerfacecolor='w',
label='SLFM, $\\chi_{\\mathrm{st}}$=' + '{:.0e} 1/s'.format(chi_values[ix]))
plt.plot(z, l_eq['density'], 'P-', markevery=4, markersize=5, markerfacecolor='w', label='EQ')
plt.plot(z, l_bs['density'], 'H-', markevery=4, markersize=5, markerfacecolor='w', label='BS')
plt.xlabel('mixture fraction')
plt.ylabel('density (kg/m3)')
plt.grid(True)
plt.legend(loc='best')
plt.show()
for ix, marker in zip(chi_indices_plot, ['s', 'o', 'd', '^']):
plt.plot(z, l_sl['heat_release_rate'][:, ix] / 1.e6, 'c-',
marker=marker, markevery=4, markersize=5, markerfacecolor='w',
label='SLFM, $\\chi_{\\mathrm{st}}$=' + '{:.0e} 1/s'.format(chi_values[ix]))
plt.plot(z, l_eq['heat_release_rate'] / 1.e6, 'P-', markevery=4, markersize=5, markerfacecolor='w', label='EQ')
plt.plot(z, l_bs['heat_release_rate'] / 1.e6, 'H-', markevery=4, markersize=5, markerfacecolor='w', label='BS')
plt.yscale('log')
plt.ylim([1e-6, 1e2])
plt.xlabel('mixture fraction')
plt.ylabel('heat release rate (MJ/m3/s)')
plt.grid(True)
plt.legend(loc='best')
plt.show()
plt.figure()
for ix, marker in zip(chi_indices_plot, ['s', 'o', 'd', '^']):
plt.plot(z, l_sl['mass fraction OH'][:, ix], 'c-',
marker=marker, markevery=4, markersize=5, markerfacecolor='w',
label='SLFM, $\\chi_{\\mathrm{st}}$=' + '{:.0e} 1/s'.format(chi_values[ix]))
plt.plot(z, l_eq['mass fraction OH'], 'P-', markevery=4, markersize=5, markerfacecolor='w', label='EQ')
plt.plot(z, l_bs['mass fraction OH'], 'H-', markevery=4, markersize=5, markerfacecolor='w', label='BS')
plt.yscale('log')
plt.ylim([1e-8, 1e-3])
plt.xlabel('mixture fraction')
plt.ylabel('mass fraction OH')
plt.grid(True)
plt.legend(loc='best')
plt.show()
.. image:: methane_shear_layer_tabulation_files/methane_shear_layer_tabulation_9_0.png
.. image:: methane_shear_layer_tabulation_files/methane_shear_layer_tabulation_9_1.png
.. image:: methane_shear_layer_tabulation_files/methane_shear_layer_tabulation_9_2.png
.. image:: methane_shear_layer_tabulation_files/methane_shear_layer_tabulation_9_3.png
<file_sep>import unittest
from os.path import join, abspath
from numpy.testing import assert_allclose
from tests.tabulation.nonadiabatic_defect_equilibrium.rebless import run
from spitfire.chemistry.library import Library
from spitfire.chemistry.ctversion import check as cantera_version_check
if cantera_version_check('atleast', 2, 5, None):
tol_args = {'atol': 1e-14} if cantera_version_check('pre', 2, 6, None) else {'atol': 1e-7, 'rtol': 3e-3}
class Test(unittest.TestCase):
def test(self):
output_library = run()
gold_file = abspath(join('tests',
'tabulation',
'nonadiabatic_defect_equilibrium',
'gold.pkl'))
gold_library = Library.load_from_file(gold_file)
for prop in gold_library.props:
self.assertIsNone(assert_allclose(gold_library[prop], output_library[prop], **tol_args))
if __name__ == '__main__':
unittest.main()
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
/*
* This file includes matrix operations related to "BTDDOD" matrices,
* or block-tridiagonal, diagonal-off-diagonal matrices. This means that along
* the major diagonal there are nxn blocks (all the same size), and that
* on the super- and sub-block off block diagonal matrices are diagonal.
*/
#ifndef GRIFFON_BTDDOD_MATRIX_KERNELS_H
#define GRIFFON_BTDDOD_MATRIX_KERNELS_H
namespace griffon
{
namespace btddod
{
void btddod_full_factorize(double *out_d_factors, const int num_blocks, const int block_size, double *out_l_values,
int *out_d_pivots);
void btddod_full_solve(const double *d_factors, const double *l_values, const int *d_pivots, const double *rhs,
const int num_blocks, const int block_size, double *out_solution);
void btddod_full_matvec(const double *matrix_values, const double *vec, const int num_blocks, const int block_size,
double *out_matvec);
void btddod_blockdiag_matvec(const double *matrix_values, const double *vec, const int num_blocks, const int block_size,
double *out_matvec);
void btddod_offdiag_matvec(const double *matrix_values, const double *vec, const int num_blocks, const int block_size,
double *out_matvec);
void btddod_lowerfulltriangle_matvec(const double *matrix_values, const double *vec, const int num_blocks,
const int block_size, double *out_matvec);
void btddod_upperfulltriangle_matvec(const double *matrix_values, const double *vec, const int num_blocks,
const int block_size, double *out_matvec);
void btddod_lowerofftriangle_matvec(const double *matrix_values, const double *vec, const int num_blocks,
const int block_size, double *out_matvec);
void btddod_upperofftriangle_matvec(const double *matrix_values, const double *vec, const int num_blocks,
const int block_size, double *out_matvec);
void btddod_blockdiag_factorize(const double *matrix_values, const int num_blocks, const int block_size, int *out_pivots,
double *out_factors);
void btddod_blockdiag_solve(const int *pivots, const double *factors, const double *rhs, const int num_blocks,
const int block_size, double *out_solution);
void btddod_lowerfulltriangle_solve(const int *pivots, const double *factors, const double *matrix_values,
const double *rhs, const int num_blocks, const int block_size, double *out_solution);
void btddod_upperfulltriangle_solve(const int *pivots, const double *factors, const double *matrix_values,
const double *rhs, const int num_blocks, const int block_size, double *out_solution);
// A <- matrix_scale * A + diag_scale * block_diag
void btddod_scale_and_add_scaled_block_diagonal(double *in_out_matrix_values, const double matrix_scale,
const double *block_diag, const double diag_scale, const int num_blocks,
const int block_size);
// A <- matrix_scale * A + diag_scale * diagonal
void btddod_scale_and_add_diagonal(double *in_out_matrix_values, const double matrix_scale, const double *diagonal,
const double diag_scale, const int num_blocks, const int block_size);
// TODO: add block row and column scaling
} // namespace btddod
} // namespace griffon
#endif //GRIFFON_BTDDOD_MATRIX_KERNELS_H
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
#include "combustion_kernels.h"
#include "blas_lapack_kernels.h"
#include "btddod_matrix_kernels.h"
#include <cmath>
#include <numeric>
namespace griffon
{
void CombustionKernels::flamelet2d_rhs(const double *state, const double &pressure, const int &nx, const int &ny,
const double *xcp, const double *xcl, const double *xcr, const double *ycp,
const double *ycb, const double *yct, double *out_rhs) const
{
const int nq = mechanismData.phaseData.nSpecies;
const int nyq = ny * nq;
for (int ix = 1; ix < nx - 1; ++ix)
{
const int i = ix * nyq;
const int isx = (ix - 1) * nq;
for (int iy = 1; iy < ny - 1; ++iy)
{
const int ij = i + iy * nq;
double rho;
double enthalpies[nq];
double w[nq];
const double T = state[ij];
double y[nq];
extract_y(&state[ij + 1], nq, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_density(pressure, T, mmw, &rho);
const double cp = cp_mix(T, y);
species_enthalpies(T, enthalpies);
production_rates(T, rho, mmw, y, w);
chem_rhs_isobaric(rho, cp, enthalpies, w, &out_rhs[ij]);
const int ijm1 = ij - nq;
const int ijp1 = ij + nq;
const int im1j = ij - nyq;
const int ip1j = ij + nyq;
const int isy = (iy - 1) * nq;
for (int iq = 0; iq < nq; ++iq)
{
out_rhs[ij + iq] += xcr[isx + iq] * state[ip1j + iq] + xcl[isx + iq] * state[im1j + iq] + xcp[isx + iq] * state[ij + iq] + yct[isy + iq] * state[ijp1 + iq] + ycb[isy + iq] * state[ijm1 + iq] + ycp[isy + iq] * state[ij + iq];
}
}
const int ij_1 = ix * nyq;
const int im1j_1 = ij_1 - nyq;
const int ip1j_1 = ij_1 + nyq;
const int ij_2 = ix * nyq + (ny - 1) * nq;
const int im1j_2 = ij_2 - nyq;
const int ip1j_2 = ij_2 + nyq;
double rho_1, rho_2;
double enthalpies_1[nq], enthalpies_2[nq];
double w_1[nq], w_2[nq];
double rhs_1[nq], rhs_2[nq];
const double T_1 = state[ij_1];
const double T_2 = state[ij_2];
double y_1[nq];
double y_2[nq];
extract_y(&state[ij_1 + 1], nq, y_1);
extract_y(&state[ij_2 + 1], nq, y_2);
const double mmw_1 = mixture_molecular_weight(y_1);
const double mmw_2 = mixture_molecular_weight(y_2);
ideal_gas_density(pressure, T_1, mmw_1, &rho_1);
ideal_gas_density(pressure, T_2, mmw_2, &rho_2);
const double cp_1 = cp_mix(T_1, y_1);
const double cp_2 = cp_mix(T_2, y_2);
species_enthalpies(T_1, enthalpies_1);
production_rates(T_1, rho_1, mmw_1, y_1, w_1);
chem_rhs_isobaric(rho_1, cp_1, enthalpies_1, w_1, rhs_1);
species_enthalpies(T_2, enthalpies_2);
production_rates(T_2, rho_2, mmw_2, y_2, w_2);
chem_rhs_isobaric(rho_2, cp_2, enthalpies_2, w_2, rhs_2);
for (int iq = 0; iq < nq; ++iq)
{
out_rhs[ij_1 + iq] += xcr[isx + iq] * state[ip1j_1 + iq] + xcl[isx + iq] * state[im1j_1 + iq] + xcp[isx + iq] * state[ij_1 + iq] + rhs_1[iq];
out_rhs[ij_2 + iq] += xcr[isx + iq] * state[ip1j_2 + iq] + xcl[isx + iq] * state[im1j_2 + iq] + xcp[isx + iq] * state[ij_2 + iq] + rhs_2[iq];
}
}
for (int iy = 1; iy < ny - 1; ++iy)
{
const int ij_1 = iy * nq;
const int ijm1_1 = ij_1 - nq;
const int ijp1_1 = ij_1 + nq;
const int ij_2 = (nx - 1) * nyq + iy * nq;
const int ijm1_2 = ij_2 - nq;
const int ijp1_2 = ij_2 + nq;
const int isy = (iy - 1) * nq;
double rho_1, rho_2;
double enthalpies_1[nq], enthalpies_2[nq];
double w_1[nq], w_2[nq];
double rhs_1[nq], rhs_2[nq];
const double T_1 = state[ij_1];
const double T_2 = state[ij_2];
double y_1[nq];
double y_2[nq];
extract_y(&state[ij_1 + 1], nq, y_1);
extract_y(&state[ij_2 + 1], nq, y_2);
const double mmw_1 = mixture_molecular_weight(y_1);
const double mmw_2 = mixture_molecular_weight(y_2);
ideal_gas_density(pressure, T_1, mmw_1, &rho_1);
ideal_gas_density(pressure, T_2, mmw_2, &rho_2);
const double cp_1 = cp_mix(T_1, y_1);
const double cp_2 = cp_mix(T_2, y_2);
species_enthalpies(T_1, enthalpies_1);
production_rates(T_1, rho_1, mmw_1, y_1, w_1);
chem_rhs_isobaric(rho_1, cp_1, enthalpies_1, w_1, rhs_1);
species_enthalpies(T_2, enthalpies_2);
production_rates(T_2, rho_2, mmw_2, y_2, w_2);
chem_rhs_isobaric(rho_2, cp_2, enthalpies_2, w_2, rhs_2);
for (int iq = 0; iq < nq; ++iq)
{
out_rhs[ij_1 + iq] += yct[isy + iq] * state[ijp1_1 + iq] + ycb[isy + iq] * state[ijm1_1 + iq] + ycp[isy + iq] * state[ij_1 + iq] + rhs_1[iq];
out_rhs[ij_2 + iq] += yct[isy + iq] * state[ijp1_2 + iq] + ycb[isy + iq] * state[ijm1_2 + iq] + ycp[isy + iq] * state[ij_2 + iq] + rhs_2[iq];
}
}
for (int iq = 0; iq < nq; ++iq)
{
out_rhs[iq] = 0.;
out_rhs[(ny - 1) * nq + iq] = 0.;
out_rhs[(nx - 1) * nyq + iq] = 0.;
out_rhs[(nx - 1) * nyq + (ny - 1) * nq + iq] = 0.;
}
}
void CombustionKernels::flamelet2d_factored_block_diag_jacobian(const double *state, const double &pressure, const int &nx,
const int &ny, const double *xcp, const double *ycp,
const double &prefactor, double *out_values,
double *out_factors, int *out_pivots) const
{
const int nq = mechanismData.phaseData.nSpecies;
const int nyq = ny * nq;
const int nyqq = nyq * nq;
const int nqq = nq * nq;
for (int ix = 1; ix < nx - 1; ++ix)
{
const int i = ix * nyq;
const int ijac = ix * nyqq;
const int isx = (ix - 1) * nq;
for (int iy = 1; iy < ny - 1; ++iy)
{
const int ij = i + iy * nq;
const int ijjac = ijac + iy * nqq;
const int isy = (iy - 1) * nq;
double rho, cp, cpsensT;
double cpi[nq], cpisensT[nq], rhsTemp[nq], enthalpies[nq], w[nq], wsens[(nq + 1) * (nq + 1)], primJac[nq * (nq + 1)];
double jac[nqq];
const double T = state[ij];
double y[nq];
extract_y(&state[ij + 1], nq, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_density(pressure, T, mmw, &rho);
cp_mix_and_species(T, y, &cp, cpi);
species_enthalpies(T, enthalpies);
cp_sens_T(T, y, &cpsensT, cpisensT);
prod_rates_sens_exact(T, rho, mmw, y, w, wsens);
chem_jac_isobaric(pressure, T, y, mmw, rho, cp, cpi, cpsensT, enthalpies, w, wsens, rhsTemp, primJac);
transform_isobaric_primitive_jacobian(rho, pressure, T, mmw, primJac, jac);
for (int iq = 0; iq < nqq; ++iq)
{
jac[iq] *= prefactor;
}
for (int iq = 0; iq < nq; ++iq)
{
jac[iq * (nq + 1)] += prefactor * (xcp[isx + iq] + ycp[isy + iq]) - 1.;
}
for (int iq = 0; iq < nqq; ++iq)
{
out_values[ijjac + iq] = jac[iq];
}
griffon::lapack::lu_factorize_with_copy(nq, jac, &out_pivots[ij], &out_factors[ijjac]);
}
const int ij_1 = ix * nyq;
const int ijac_1 = ix * nyqq;
const int ijjac_1 = ijac_1;
const int ij_2 = ix * nyq + (ny - 1) * nq;
const int ijac_2 = ix * nyqq;
const int ijjac_2 = ijac_2 + (ny - 1) * nqq;
{
double rho, cp, cpsensT;
double cpi[nq], cpisensT[nq], rhsTemp[nq], enthalpies[nq], w[nq], wsens[(nq + 1) * (nq + 1)], primJac[nq * (nq + 1)];
double jac[nqq];
const double T = state[ij_1];
double y[nq];
extract_y(&state[ij_1 + 1], nq, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_density(pressure, T, mmw, &rho);
cp_mix_and_species(T, y, &cp, cpi);
species_enthalpies(T, enthalpies);
cp_sens_T(T, y, &cpsensT, cpisensT);
prod_rates_sens_exact(T, rho, mmw, y, w, wsens);
chem_jac_isobaric(pressure, T, y, mmw, rho, cp, cpi, cpsensT, enthalpies, w, wsens, rhsTemp, primJac);
transform_isobaric_primitive_jacobian(rho, pressure, T, mmw, primJac, jac);
for (int iq = 0; iq < nqq; ++iq)
{
jac[iq] *= prefactor;
}
for (int iq = 0; iq < nq; ++iq)
{
jac[iq * (nq + 1)] += prefactor * xcp[isx + iq] - 1.;
}
for (int iq = 0; iq < nqq; ++iq)
{
out_values[ijjac_1 + iq] = jac[iq];
}
griffon::lapack::lu_factorize_with_copy(nq, jac, &out_pivots[ij_1], &out_factors[ijjac_1]);
}
{
double rho, cp, cpsensT;
double cpi[nq], cpisensT[nq], rhsTemp[nq], enthalpies[nq], w[nq], wsens[(nq + 1) * (nq + 1)], primJac[nq * (nq + 1)];
double jac[nqq];
const double T = state[ij_2];
double y[nq];
extract_y(&state[ij_2 + 1], nq, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_density(pressure, T, mmw, &rho);
cp_mix_and_species(T, y, &cp, cpi);
species_enthalpies(T, enthalpies);
cp_sens_T(T, y, &cpsensT, cpisensT);
prod_rates_sens_exact(T, rho, mmw, y, w, wsens);
chem_jac_isobaric(pressure, T, y, mmw, rho, cp, cpi, cpsensT, enthalpies, w, wsens, rhsTemp, primJac);
transform_isobaric_primitive_jacobian(rho, pressure, T, mmw, primJac, jac);
for (int iq = 0; iq < nqq; ++iq)
{
jac[iq] *= prefactor;
}
for (int iq = 0; iq < nq; ++iq)
{
jac[iq * (nq + 1)] += prefactor * xcp[isx + iq] - 1.;
}
for (int iq = 0; iq < nqq; ++iq)
{
out_values[ijjac_2 + iq] = jac[iq];
}
griffon::lapack::lu_factorize_with_copy(nq, jac, &out_pivots[ij_2], &out_factors[ijjac_2]);
}
}
for (int iy = 1; iy < ny - 1; ++iy)
{
const int isy = (iy - 1) * nq;
const int ijac_1 = 0;
const int ijjac_1 = ijac_1 + iy * nqq;
const int ij_1 = iy * nq;
const int ijac_2 = (nx - 1) * nyqq;
const int ijjac_2 = ijac_2 + iy * nqq;
const int ij_2 = (nx - 1) * nyq + iy * nq;
{
double rho, cp, cpsensT;
double cpi[nq], cpisensT[nq], rhsTemp[nq], enthalpies[nq], w[nq], wsens[(nq + 1) * (nq + 1)], primJac[nq * (nq + 1)];
double jac[nqq];
const double T = state[ij_1];
double y[nq];
extract_y(&state[ij_1 + 1], nq, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_density(pressure, T, mmw, &rho);
cp_mix_and_species(T, y, &cp, cpi);
species_enthalpies(T, enthalpies);
cp_sens_T(T, y, &cpsensT, cpisensT);
prod_rates_sens_exact(T, rho, mmw, y, w, wsens);
chem_jac_isobaric(pressure, T, y, mmw, rho, cp, cpi, cpsensT, enthalpies, w, wsens, rhsTemp, primJac);
transform_isobaric_primitive_jacobian(rho, pressure, T, mmw, primJac, jac);
for (int iq = 0; iq < nqq; ++iq)
{
jac[iq] *= prefactor;
}
for (int iq = 0; iq < nq; ++iq)
{
jac[iq * (nq + 1)] += prefactor * ycp[isy + iq] - 1.;
}
for (int iq = 0; iq < nqq; ++iq)
{
out_values[ijjac_1 + iq] = jac[iq];
}
griffon::lapack::lu_factorize_with_copy(nq, jac, &out_pivots[ij_1], &out_factors[ijjac_1]);
}
{
double rho, cp, cpsensT;
double cpi[nq], cpisensT[nq], rhsTemp[nq], enthalpies[nq], w[nq], wsens[(nq + 1) * (nq + 1)], primJac[nq * (nq + 1)];
double jac[nqq];
const double T = state[ij_2];
double y[nq];
extract_y(&state[ij_2 + 1], nq, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_density(pressure, T, mmw, &rho);
cp_mix_and_species(T, y, &cp, cpi);
species_enthalpies(T, enthalpies);
cp_sens_T(T, y, &cpsensT, cpisensT);
prod_rates_sens_exact(T, rho, mmw, y, w, wsens);
chem_jac_isobaric(pressure, T, y, mmw, rho, cp, cpi, cpsensT, enthalpies, w, wsens, rhsTemp, primJac);
transform_isobaric_primitive_jacobian(rho, pressure, T, mmw, primJac, jac);
for (int iq = 0; iq < nqq; ++iq)
{
jac[iq] *= prefactor;
}
for (int iq = 0; iq < nq; ++iq)
{
jac[iq * (nq + 1)] += prefactor * ycp[isy + iq] - 1.;
}
for (int iq = 0; iq < nqq; ++iq)
{
out_values[ijjac_2 + iq] = jac[iq];
}
griffon::lapack::lu_factorize_with_copy(nq, jac, &out_pivots[ij_2], &out_factors[ijjac_2]);
}
}
double jac[nqq];
for (int iq = 0; iq < nq; ++iq)
{
jac[iq * (nq + 1)] = prefactor - 1.;
}
griffon::lapack::lu_factorize_with_copy(nq, jac, &out_pivots[0], &out_factors[0]);
for (int iq = 0; iq < nqq; ++iq)
{
out_values[iq] = jac[iq];
out_values[(ny - 1) * nqq + iq] = jac[iq];
out_values[(nx - 1) * nyqq + iq] = jac[iq];
out_values[(nx - 1) * nyqq + (ny - 1) * nqq + iq] = jac[iq];
}
for (int iq = 0; iq < nq; ++iq)
{
out_pivots[(ny - 1) * nq + iq] = out_pivots[iq];
out_pivots[(nx - 1) * nyq + iq] = out_pivots[iq];
out_pivots[(nx - 1) * nyq + (ny - 1) * nq + iq] = out_pivots[iq];
for (int jq = 0; jq < nq; ++jq)
{
out_factors[(ny - 1) * nqq + iq * nq + jq] = out_factors[iq * nq + jq];
out_factors[(nx - 1) * nyqq + iq * nq + jq] = out_factors[iq * nq + jq];
out_factors[(nx - 1) * nyqq + (ny - 1) * nqq + iq * nq + jq] = out_factors[iq * nq + jq];
}
}
}
void CombustionKernels::flamelet2d_offdiag_matvec(const double *vec, const int &nx, const int &ny, const double *xcp,
const double *xcl, const double *xcr, const double *ycp,
const double *ycb, const double *yct, const double &prefactor,
double *out_vec) const
{
const int nq = mechanismData.phaseData.nSpecies;
const int nyq = ny * nq;
for (int ix = 1; ix < nx - 1; ++ix)
{
const int i = ix * nyq;
const int isx = (ix - 1) * nq;
for (int iy = 1; iy < ny - 1; ++iy)
{
const int ij = i + iy * nq;
const int ijm1 = ij - nq;
const int ijp1 = ij + nq;
const int im1j = ij - nyq;
const int ip1j = ij + nyq;
const int isy = (iy - 1) * nq;
for (int iq = 0; iq < nq; ++iq)
{
out_vec[ij + iq] += prefactor * (xcr[isx + iq] * vec[ip1j + iq] + xcl[isx + iq] * vec[im1j + iq] + yct[isy + iq] * vec[ijp1 + iq] + ycb[isy + iq] * vec[ijm1 + iq]);
}
}
const int ij_1 = ix * nyq;
const int im1j_1 = ij_1 - nyq;
const int ip1j_1 = ij_1 + nyq;
const int ij_2 = ix * nyq + (ny - 1) * nq;
const int im1j_2 = ij_2 - nyq;
const int ip1j_2 = ij_2 + nyq;
for (int iq = 0; iq < nq; ++iq)
{
out_vec[ij_1 + iq] += prefactor * (xcr[isx + iq] * vec[ip1j_1 + iq] + xcl[isx + iq] * vec[im1j_1 + iq]);
out_vec[ij_2 + iq] += prefactor * (xcr[isx + iq] * vec[ip1j_2 + iq] + xcl[isx + iq] * vec[im1j_2 + iq]);
}
}
for (int iy = 1; iy < ny - 1; ++iy)
{
const int ij_1 = iy * nq;
const int ijm1_1 = ij_1 - nq;
const int ijp1_1 = ij_1 + nq;
const int ij_2 = (nx - 1) * nyq + iy * nq;
const int ijm1_2 = ij_2 - nq;
const int ijp1_2 = ij_2 + nq;
const int isy = (iy - 1) * nq;
for (int iq = 0; iq < nq; ++iq)
{
out_vec[ij_1 + iq] += prefactor * (yct[isy + iq] * vec[ijp1_1 + iq] + ycb[isy + iq] * vec[ijm1_1 + iq]);
out_vec[ij_2 + iq] += prefactor * (yct[isy + iq] * vec[ijp1_2 + iq] + ycb[isy + iq] * vec[ijm1_2 + iq]);
}
}
for (int iq = 0; iq < nq; ++iq)
{
out_vec[iq] = 0.;
out_vec[(ny - 1) * nq + iq] = 0.;
out_vec[(nx - 1) * nyq + iq] = 0.;
out_vec[(nx - 1) * nyq + (ny - 1) * nq + iq] = 0.;
}
}
void CombustionKernels::flamelet2d_matvec(const double *vec, const int &nx, const int &ny, const double *xcp,
const double *xcl, const double *xcr, const double *ycp, const double *ycb,
const double *yct, const double &prefactor, const double *block_diag_values,
double *out_vec) const
{
const int nq = mechanismData.phaseData.nSpecies;
const int nqq = nq * nq;
const int nyq = ny * nq;
const int nyqq = nyq * nq;
for (int ix = 1; ix < nx - 1; ++ix)
{
const int i = ix * nyq;
const int ijac = ix * nyqq;
const int isx = (ix - 1) * nq;
for (int iy = 1; iy < ny - 1; ++iy)
{
const int ij = i + iy * nq;
const int ijm1 = ij - nq;
const int ijp1 = ij + nq;
const int im1j = ij - nyq;
const int ip1j = ij + nyq;
const int isy = (iy - 1) * nq;
const int ijjac = ijac + iy * nqq;
griffon::blas::matrix_vector_multiply(nq, &out_vec[ij], 1., &block_diag_values[ijjac], &vec[ij], 1.);
for (int iq = 0; iq < nq; ++iq)
{
out_vec[ij + iq] += prefactor * (xcr[isx + iq] * vec[ip1j + iq] + xcl[isx + iq] * vec[im1j + iq] + yct[isy + iq] * vec[ijp1 + iq] + ycb[isy + iq] * vec[ijm1 + iq]);
}
}
const int ij_1 = ix * nyq;
const int im1j_1 = ij_1 - nyq;
const int ip1j_1 = ij_1 + nyq;
const int ijac_1 = ix * nyqq;
const int ijjac_1 = ijac_1;
const int ij_2 = ix * nyq + (ny - 1) * nq;
const int im1j_2 = ij_2 - nyq;
const int ip1j_2 = ij_2 + nyq;
const int ijac_2 = ix * nyqq;
const int ijjac_2 = ijac_2 + (ny - 1) * nqq;
griffon::blas::matrix_vector_multiply(nq, &out_vec[ij_1], 1., &block_diag_values[ijjac_1], &vec[ij_1], 1.);
griffon::blas::matrix_vector_multiply(nq, &out_vec[ij_2], 1., &block_diag_values[ijjac_2], &vec[ij_2], 1.);
for (int iq = 0; iq < nq; ++iq)
{
out_vec[ij_1 + iq] += prefactor * (xcr[isx + iq] * vec[ip1j_1 + iq] + xcl[isx + iq] * vec[im1j_1 + iq]);
out_vec[ij_2 + iq] += prefactor * (xcr[isx + iq] * vec[ip1j_2 + iq] + xcl[isx + iq] * vec[im1j_2 + iq]);
}
}
for (int iy = 1; iy < ny - 1; ++iy)
{
const int isy = (iy - 1) * nq;
const int ijac_1 = 0;
const int ijjac_1 = ijac_1 + iy * nqq;
const int ij_1 = iy * nq;
const int ijp1_1 = ij_1 + nq;
const int ijac_2 = (nx - 1) * nyqq;
const int ijjac_2 = ijac_2 + iy * nqq;
const int ij_2 = (nx - 1) * nyq + iy * nq;
const int ijp1_2 = ij_2 + nq;
griffon::blas::matrix_vector_multiply(nq, &out_vec[ij_1], 1., &block_diag_values[ijjac_1], &vec[ij_1], 1.);
griffon::blas::matrix_vector_multiply(nq, &out_vec[ij_2], 1., &block_diag_values[ijjac_2], &vec[ij_2], 1.);
for (int iq = 0; iq < nq; ++iq)
{
out_vec[ij_1 + iq] += prefactor * (yct[isy + iq] * vec[ijp1_1 + iq] + ycp[isy + iq] * vec[ij_1 + iq]);
out_vec[ij_2 + iq] += prefactor * (yct[isy + iq] * vec[ijp1_2 + iq] + ycp[isy + iq] * vec[ij_2 + iq]);
}
}
for (int iq = 0; iq < nq; ++iq)
{
out_vec[iq] = 0.;
out_vec[(ny - 1) * nq + iq] = 0.;
out_vec[(nx - 1) * nyq + iq] = 0.;
out_vec[(nx - 1) * nyq + (ny - 1) * nq + iq] = 0.;
}
}
void CombustionKernels::flamelet2d_block_diag_solve(const int &nx, const int &ny, const double *factors, const int *pivots,
const double *b, double *out_x) const
{
const int nq = mechanismData.phaseData.nSpecies;
const int nxy = nx * ny;
const int nqq = nq * nq;
for (int id = 0; id < nxy; ++id)
{
griffon::lapack::lu_solve_with_copy(nq, &factors[id * nqq], &pivots[id * nq], &b[id * nq], &out_x[id * nq]);
}
}
} // namespace griffon
<file_sep>Tabulation API Example: Adiabatic Flamelet Models
=================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - Building adiabatic equilibrium, Burke-Schumann, and
strained laminar flamelet (SLFM) models
In the introductory flamelet demonstration we used methods on the
``Flamelet`` class to compute steady and unsteady solutions to the
flamelet equations. We used these solutions to build SLFM and FPV
chemistry libraries. Here we use the following methods to directly build
similar libraries without having to even make a ``Flamelet`` instance.
- adiabatic equilibrium: ``build_adiabatic_eq_library``
- adiabatic Burke-Schumann: ``build_adiabatic_bs_library``
- adiabatic SLFM: ``build_adiabatic_slfm_library``
.. code:: ipython3
from spitfire import (ChemicalMechanismSpec,
FlameletSpec,
build_adiabatic_eq_library,
build_adiabatic_bs_library,
build_adiabatic_slfm_library)
import matplotlib.pyplot as plt
import numpy as np
mech = ChemicalMechanismSpec(cantera_xml='heptane-liu-hewson-chen-pitsch-highT.xml', group_name='gas')
pressure = 101325.
air = mech.stream(stp_air=True)
air.TP = 1200., pressure
fuel = mech.stream('TPY', (300., pressure, 'NXC7H16:1'))
flamelet_specs = FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,
fuel_stream=fuel,
grid_points=34)
With the flamelet specifications all set up, we next use the high-level
tabulation methods to easily build some flamelet models.
First up are the unstrained models - equilibrium (infinitely fast
chemistry) and Burke-Schumann (idealized single-step combustion).
.. code:: ipython3
l_eq = build_adiabatic_eq_library(flamelet_specs, verbose=False)
l_bs = build_adiabatic_bs_library(flamelet_specs, verbose=False)
Next up is the adiabatic strained laminar flamelet library. Note how
much easier this is than running the continuation loop over the
dissipation rate ourselves.
.. code:: ipython3
l_sl = build_adiabatic_slfm_library(flamelet_specs,
diss_rate_values=np.logspace(-2, 3, 6),
diss_rate_ref='stoichiometric',
diss_rate_log_scaled=True,
verbose=False)
And now we visualize the results, showing the equilibrium and
Burke-Schumann profiles alongside the SLFM solutions at several values
of the dissipation rate. Note in particular the difference in OH and
acetylene production in the finite-strain profiles and the nonlinear
effects of the dissipation rate.
.. code:: ipython3
chi_indices_plot = [0, 2, 4, 5]
chi_values = l_sl.dim('dissipation_rate_stoich').values
z = l_sl.dim('mixture_fraction').values
for ix, marker in zip(chi_indices_plot, ['s', 'o', 'd', '^']):
plt.plot(z, l_sl['temperature'][:, ix], 'c-',
marker=marker, markevery=4, markersize=5, markerfacecolor='w',
label='SLFM, $\\chi_{\\mathrm{st}}$=' + '{:.0e} 1/s'.format(chi_values[ix]))
plt.plot(z, l_eq['temperature'], 'P-', markevery=4, markersize=5, markerfacecolor='w', label='EQ')
plt.plot(z, l_bs['temperature'], 'H-', markevery=4, markersize=5, markerfacecolor='w', label='BS')
plt.xlabel('mixture fraction')
plt.ylabel('T (K)')
plt.grid(True)
plt.legend(loc='best')
plt.show()
for ix, marker in zip(chi_indices_plot, ['s', 'o', 'd', '^']):
plt.plot(z, l_sl['mass fraction OH'][:, ix], 'c-',
marker=marker, markevery=4, markersize=5, markerfacecolor='w',
label='SLFM, $\\chi_{\\mathrm{st}}$=' + '{:.0e} 1/s'.format(chi_values[ix]))
plt.plot(z, l_eq['mass fraction OH'], 'P-', markevery=4, markersize=5, markerfacecolor='w', label='EQ')
plt.plot(z, l_bs['mass fraction OH'], 'H-', markevery=4, markersize=5, markerfacecolor='w', label='BS')
plt.xlabel('mixture fraction')
plt.ylabel('mass fraction OH')
plt.xlim([0, 0.3])
plt.grid(True)
plt.legend(loc='best')
plt.show()
for ix, marker in zip(chi_indices_plot, ['s', 'o', 'd', '^']):
plt.plot(z, l_sl['mass fraction C2H2'][:, ix], 'c-',
marker=marker, markevery=4, markersize=5, markerfacecolor='w',
label='SLFM, $\\chi_{\\mathrm{st}}$=' + '{:.0e} 1/s'.format(chi_values[ix]))
plt.plot(z, l_eq['mass fraction C2H2'], 'P-', markevery=4, markersize=5, markerfacecolor='w', label='EQ')
plt.plot(z, l_bs['mass fraction C2H2'], 'H-', markevery=4, markersize=5, markerfacecolor='w', label='BS')
plt.xlabel('mixture fraction')
plt.ylabel('mass fraction C2H2')
plt.grid(True)
plt.legend(loc='best')
plt.show()
.. image:: high_level_tabulation_api_adiabatic_files/high_level_tabulation_api_adiabatic_8_0.png
.. image:: high_level_tabulation_api_adiabatic_files/high_level_tabulation_api_adiabatic_8_1.png
.. image:: high_level_tabulation_api_adiabatic_files/high_level_tabulation_api_adiabatic_8_2.png
<file_sep># Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
import os
from glob import glob
from setuptools import setup
from setuptools.extension import Extension
from Cython.Build import cythonize
from numpy import get_include as numpy_include
import platform
class ConfigSQA:
"""Configuring SQA files, currently just git information. The class handles creating/deleting files during installation."""
def _clean_state(self, create_dir=False):
if os.path.exists(self._sqa_init_path):
os.remove(self._sqa_init_path)
if os.path.exists(self._git_asset_path):
os.remove(self._git_asset_path)
if os.path.isdir(self._sqa_dir):
os.rmdir(self._sqa_dir)
if create_dir:
os.mkdir(self._sqa_dir)
with open(self._sqa_init_path, 'w') as f:
f.write(' ')
def __init__(self, sqa_dir):
self._sqa_dir = sqa_dir
self._sqa_init_path = os.path.join(self._sqa_dir, '__init__.py')
self._git_asset_path = os.path.join(self._sqa_dir, 'gitinfo.py')
self._clean_state(create_dir=True)
def __del__(self, *args):
self._clean_state()
def write_gitinfo(self):
with open(self._git_asset_path, 'w') as f:
from git import Repo
repo = Repo('.')
repo.config_reader()
no_tags = len(repo.tags) == 0
tags = sorted(repo.tags, key=lambda t: t.commit.committed_datetime)
tag_dict = dict({t: repo.commit(t) for t in tags})
latest_tag = None if no_tags else tags[-1]
tag_hexsha = None if no_tags else tag_dict[latest_tag].hexsha
is_dirty = repo.is_dirty()
current_hexsha = repo.head.object.hexsha
if is_dirty:
detailed_version = f'dirty-{latest_tag}-{current_hexsha}'
minimal_version = 'local'
else:
if no_tags:
detailed_version = f'clean-{latest_tag}-{current_hexsha}'
minimal_version = 'committed'
else:
if current_hexsha == tag_hexsha:
detailed_version = f'{latest_tag}'
minimal_version = f'{latest_tag}'
else:
detailed_version = f'clean-{latest_tag}-{current_hexsha}'
minimal_version = 'committed'
f.write(f'detailed_version = "{detailed_version}"\n')
f.write(f'minimal_version = "{minimal_version}"\n')
f.write(f'latest_tag = "{latest_tag}"\n')
f.write(f'latest_tag_sha = "{tag_hexsha}"\n')
f.write(f'is_dirty = "{is_dirty}"\n')
f.write(f'current_hexsha = "{current_hexsha}"\n')
c = ConfigSQA('src/spitfire/sqa')
c.write_gitinfo()
def readfile(filename):
try:
with open(filename) as f:
return f.read()
except:
with open(filename, encoding='utf-8') as f:
return f.read()
base_compile_args = ['-O3', '-g', '-std=c++11', '-Wno-error']
compile_for_mac = ['-stdlib=libc++'] if platform.system() == 'Darwin' else list()
griffon_compile_args = base_compile_args + compile_for_mac
setup(name='Spitfire',
version=readfile('version'),
author='<NAME>',
author_email='<EMAIL>',
license=readfile('license.md'),
description=readfile('description_short'),
long_description=readfile('readme.md'),
url='https://github.com/sandialabs/Spitfire/',
package_dir={'': 'src'},
packages=['spitfire', 'spitfire.chemistry', 'spitfire.time', 'spitfire.griffon', 'spitfire.sqa', 'spitfire.data'],
ext_modules=cythonize(Extension(name='spitfire.griffon.griffon',
sources=[os.path.join('src', 'spitfire', 'griffon', 'griffon.pyx')] + glob(
os.path.join('src', 'spitfire', 'griffon', 'src') + '/*.cpp', recursive=False),
extra_compile_args=griffon_compile_args,
include_dirs=[numpy_include(), os.path.join('src', 'spitfire', 'griffon', 'include')],
library_dirs=[os.path.join('src', 'spitfire', 'griffon')],
libraries=['blas', 'lapack'],
language='c++')),
package_data={'spitfire.griffon': ['*.so'], 'spitfire.data': ['*']},
classifiers=[
'Programming Language :: Python :: 3',
'Programming Language :: C++',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Chemistry',
'Topic :: Scientific/Engineering :: Mathematics',
],
python_requires='>=3.6')
print(f"""
- Done installing Spitfire!
{'-' * 80}
- To test or build docs, an in-place build is also required:
python3 setup.py build_ext --inplace
{'-' * 80}
- Run the tests:
python3 -m unittest discover -s tests
{'-' * 80}
- Build the docs:
cd docs
make html
open build/html/index.html in a browser
{'-' * 80}
- Update docs from Jupyter demos
cd docs/source/demo
find . -name *ipynb | xargs jupyter nbconvert --to rst
{'-' * 80}
""")
<file_sep>Steady State Multiplicity in n-heptane/air Mixtures
===================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - Solving for the steady ignition and extinction
trajectories of a heptane-air mixture, which show the existence of
multiple steady states and path-dependence - Observing the sensitivity
of ignition/extinction behavior to temperature and stoichiometry
Introduction
------------
An interesting feature of combustion chemistry is that the balance of
homogeneous chemistry and transport processes (most often molecular
mixing) can take many forms. In an open homogeneous reactor with a
particular residence time, this means that multiple steady states can
exist for the same residence time - depending on “how you got there.”
In this demo we show this for a mixture of n-heptane and air. We’re
effectively performing continuation in the residence time, starting at a
very low value (very intense flow), letting the mixture equilibrate, and
then slightly giving the reactor more residence time. As we go,
eventually the mixture will be able to sustain chain branching chemistry
and ignite. Approaching an infinite residence time corresponds to
reaching the unperturbed chemical equilibrium state.
We just computed the ignition branch - to compute the extinction branch
we simply go backwards and very slowly take the residence time to zero.
At some point the chemistry will not be able to sustain losses to the
flow and the flame will extinguish. When the residence time gets to
zero, we’ll simply see the reactor outflow be exactly the feed stream -
there is no time for chemistry to occur.
The interesting feature here is that the critical residence time for
ignition is *not* the same as the critical value for extinction. It
takes more dissipation through transport mechansims to extinguish a
flame than what will admit ignition. In a way it makes sense - ignition
fundamentally alters the mixture by providing a pool of radical species,
after which extinction requires those to be removed faster than they are
produced.
.. code:: ipython3
from spitfire import ChemicalMechanismSpec, HomogeneousReactor
import matplotlib.pyplot as plt
import numpy as np
mech = ChemicalMechanismSpec('heptane-liu-hewson-chen-pitsch-highT.xml', 'gas')
So that we could easily run different chemistries, temperatures,
pressures, etc., a function that returns the ignition and extinction
branches is helpful. The steady temperature is provided, but mass
fractions of certain species, explosive eigenvalues, reaction rates, and
more could all be post-processed and observed in addition.
.. code:: ipython3
def get_trajectories(mech, T, P, fuel, phi, tau_values):
tau_list = np.hstack([tau_values, tau_values[::-1]])
T_list = np.zeros_like(tau_list)
mix = mech.mix_for_equivalence_ratio(phi, mech.stream('X', fuel), mech.stream(stp_air=True))
mix.TP = T, P
feed = mech.copy_stream(mix)
for idx, tau in enumerate(tau_list):
r = HomogeneousReactor(mech, mix,
'isobaric',
'adiabatic',
'open',
mixing_tau=tau,
feed_temperature=feed.T,
feed_mass_fractions=feed.Y)
output = r.integrate_to_steady(steady_tolerance=1e-8)
T_list[idx] = output['temperature'][-1]
mix.TPY = r.current_temperature, r.current_pressure, r.current_mass_fractions
return tau_list, T_list
Ignition/Extinction Branches of stoichiometric n-heptane/air at 1000 K, 1 atm
-----------------------------------------------------------------------------
To show the presence of ignition and extinction, and the presence of
multiple steady states for a range of :math:`\tau_{\rm mix}`, we simply
show the steady reactor temperature over the residence time, for both
the ignition and extinction branches.
.. code:: ipython3
ntau = 100
tau_values = np.logspace(-8, 2, ntau)
tau_list, T_list = get_trajectories(mech, 1000., 101325., 'NXC7H16:1', 1.0, tau_values)
.. code:: ipython3
plt.semilogx(tau_list[:ntau] * 1.e3, T_list[:ntau], 'r', label='Ignition branch')
plt.semilogx(tau_list[ntau:] * 1.e3, T_list[ntau:], 'b', label='Extinction branch')
plt.xlabel('$\\tau_{\\rm mix}$ (ms)')
plt.ylabel('Steady temperature (K)')
plt.grid()
plt.legend()
plt.show()
.. image:: ignition_extinction_heptane_files/ignition_extinction_heptane_7_0.png
Dependence on Temperature
-------------------------
Now we simply take the above analysis for stoichiometric mixtures and
repeat it for a range of temperatures.
.. code:: ipython3
for T in [800, 900, 1000, 1100, 1200]:
tau_list, T_list = get_trajectories(mech, T, 101325., 'NXC7H16:1', 1.0, tau_values)
plt.semilogx(tau_list * 1.e3, T_list, label=f'T={T:.1f}')
plt.xlabel('$\\tau_{\\rm mix}$ (ms)')
plt.ylabel('Steady temperature (K)')
plt.grid()
plt.legend()
plt.show()
.. image:: ignition_extinction_heptane_files/ignition_extinction_heptane_9_0.png
An interesting observation here is that while the ignition point is
highly sensitive to temperature, the extinction behavior is much more
consistent.
Dependence on Equivalence Ratio
-------------------------------
Now we’ll see how varying the equivalence ratio affects
ignition/extinction.
.. code:: ipython3
for phi in [0.5, 0.7, 0.9, 1.0, 1.3, 1.6, 2.0]:
tau_list, T_list = get_trajectories(mech, 1000., 101325., 'NXC7H16:1', phi, tau_values)
plt.semilogx(tau_list * 1.e3, T_list, label=f'phi={phi:.2f}')
plt.xlabel('$\\tau_{\\rm mix}$ (ms)')
plt.ylabel('Steady temperature (K)')
plt.grid()
plt.legend()
plt.show()
.. image:: ignition_extinction_heptane_files/ignition_extinction_heptane_11_0.png
Interestingly, sensitivity to stoichiometry is almost nonexistent in the
critical residence times for ignition and extinction. An important
caveat at this point is that this chemical mechanism could be reduced in
size and optimized for a limited range of temperatures, pressures,
equivalence ratios, and combustion pregimes (e.g., nonpremixed vs
premixed/homogeneous).
Conclusions
-----------
In this notebook we’ve generated a number of ignition-extinction
trajectories for mixtures of n-heptane and air, and observed the
sensitivity of the steady state multiplicity to temperature and
stoichiometry.
<file_sep>One-step Ignition Mechanism for n-heptane/air Combustion
========================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - Building a simple mechanism from Python with Cantera -
Comparing n-heptane ignition behavior for two reaction mechanisms
Introduction
------------
This demonstration shows how to build a reaction mechanism, here a
simple one-step global combustion reaction for n-heptane, using Cantera.
We then use Spitfire to simulate homogeneous ignition of an
h-heptane/air mixture, with both the one-step reaction mechanism and a
kinetics model from Liu et al. (*Effects on Strain Rate on High-Pressure
Nonpremixed N-Heptane Autoignition in Counterflow*, Comb. Flame, 137,
320-339, 2004.).
.. code:: ipython3
from spitfire import ChemicalMechanismSpec, HomogeneousReactor
import cantera as ct
import matplotlib.pyplot as plt
Building the Mechanism
----------------------
Specifying the Reaction
~~~~~~~~~~~~~~~~~~~~~~~
Cantera provides several formats for chemical reaction mechanism - see
`here <https://cantera.org/tutorials/input-files.html>`__ for the
details. We use the CTI format below to create the following reaction
and its non-elementary rate expression. A standard Arrhenius rate
constant is employed.
.. math::
2\mathrm{C}_7\mathrm{H}_{16} \, + 22\mathrm{O}_2 \, \rightarrow 14\mathrm{CO}_2 \, + 16\mathrm{H}_2\mathrm{O}
.. math::
\mathrm{rate} = 2\cdot10^{7}\exp\left(-\frac{30 \mathrm{kcal}/\mathrm{mol}}{RT}\right)\langle\mathrm{C}_7\mathrm{H}_{16}\rangle^{0.25}\langle\mathrm{O}_2\rangle^{1.5}
An advantage to building this mechanism in Python is that we could
easily test a range of parameters such as the activation energy or
pre-exponential factor. We could even build a reactor into an
optimization loop to identify an optimal one-step reaction rate in some
sense.
.. code:: ipython3
reaction_cti = '''
reaction(
'2 NXC7H16 + 22 O2 => 14 CO2 + 16 H2O',
[2e7, 0, (30.0, 'kcal/mol')],
order='NXC7H16:0.25 O2:1.5')
'''
Specifying Species Properties
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now we need to specify thermodynamic properties - molecular weights and
heat capacity polynomials over temperature. We obtain these from the Liu
et al. mechanism. Below we build the ``species_list`` to contain the
Cantera ``Species`` objects required for the one-step mechanism.
.. code:: ipython3
species_in_model = ['NXC7H16', 'O2', 'H2O', 'CO2', 'N2']
liu_xml_file = 'heptane-liu-hewson-chen-pitsch-highT.xml'
species_data = ct.Species.listFromFile(liu_xml_file)
species_list = list()
for sp in species_data:
if sp.name in species_in_model:
species_list.append(sp)
Combine for a Cantera ``Solution``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now the final step - build a Cantera ``Solution`` that includes the
listed species and the reaction(s) defined above.
.. code:: ipython3
s = ct.Solution(thermo='IdealGas',
kinetics='GasKinetics',
species=species_list,
reactions=[ct.Reaction.fromCti(reaction_cti)])
Comparing Ignition Behavior
---------------------------
Now we create Spitfire ``ChemicalMechanismSpec`` objects, which can be
done with the ``Solution`` object as follows, or with the XML as we’ve
done before (which we use below to build the Liu mechanism holder).
Given the mechanisms, we can now build ``HomogeneousReactor`` instances
filled with stoichiometric n-heptane/air mixtures, and integrate them
for 100 ms, which will encompass an ignition event from a sparked
mixture at 1000 K and atmospheric pressure. Major species and
temperature are plotted over time in the following figures.
.. code:: ipython3
mech_1step = ChemicalMechanismSpec.from_solution(s)
mech_liu = ChemicalMechanismSpec(cantera_xml=xml_file_for_species, group_name='gas')
solutions = dict()
for mech, name in [(mech_1step, '1 step'),
(mech_liu, 'Liu')]:
fuel = mech.stream('X', 'NXC7H16:1')
air = mech.stream(stp_air=True)
mix = mech.mix_for_equivalence_ratio(phi=1., fuel=fuel, oxy=air)
mix.TP = 1000, 101325
reactor = HomogeneousReactor(mech_spec=mech,
initial_mixture=mix,
configuration='isobaric',
heat_transfer='adiabatic',
mass_transfer='closed')
solutions[name] = reactor.integrate_to_time(0.1)
.. code:: ipython3
for name in solutions:
solution = solutions[name]
t = solution.time_values * 1.e3
fig, axY = plt.subplots()
axY.plot(t, solution['mass fraction NXC7H16'], label='$\\mathrm{C}_7\\mathrm{H}_{16}$')
axY.plot(t, solution['mass fraction O2'], label='$\\mathrm{O}_2$')
axY.plot(t, solution['mass fraction CO2'], label='$\\mathrm{CO}_2$')
axY.plot(t, solution['mass fraction H2O'], label='$\\mathrm{H}_2\\mathrm{O}$')
axY.legend(loc='center left')
axY.set_ylabel('mass fraction')
axY.set_xlim([0, 100])
axY.set_ylim([0, 0.25])
axY.set_xlabel('t (ms)')
axT = axY.twinx()
axT.plot(t, solution['temperature'], 'k--', label='temperature')
axT.set_ylabel('T (K)')
axT.set_ylim([0, 3100])
axT.legend(loc='center right')
plt.title(name)
fig.tight_layout()
plt.show()
.. image:: one_step_heptane_ignition_files/one_step_heptane_ignition_11_0.png
.. image:: one_step_heptane_ignition_files/one_step_heptane_ignition_11_1.png
The plots above suggest several key differences between the one-step and
more detailed reaction mechanisms.
- The one-step mechanism predicts that the ignited mixture is hotter
(~400 K) and contains more CO2. The simplified chemistry represents
idealized combustion, with all hydrogen going to H2O and all carbon
going to CO2.
- The more detailed mechanism predicts breakdown of the n-heptane in
the fuel during the induction phase.
The following plot shows the Liu et al. results, this time including the
ethylene (C2H4) and carbon monoxide (CO) mass fractions to show the
breakdown of n-heptane into smaller hydrocarbons and to make up the
difference in CO2 prediction from the one-step model.
.. code:: ipython3
solution = solutions['Liu']
t = solution.time_values * 1.e3
fig, axY = plt.subplots()
axY.plot(t, solution['mass fraction NXC7H16'], label='$\\mathrm{C}_7\\mathrm{H}_{16}$')
axY.plot(t, solution['mass fraction O2'], label='$\\mathrm{O}_2$')
axY.plot(t, solution['mass fraction CO2'], label='$\\mathrm{CO}_2$')
axY.plot(t, solution['mass fraction H2O'], label='$\\mathrm{H}_2\\mathrm{O}$')
axY.plot(t, solution['mass fraction C2H4'], '-.', label='$\\mathrm{C}_2\\mathrm{H}_4$')
axY.plot(t, solution['mass fraction CO'], '-.', label='$\\mathrm{CO}$')
axY.legend(loc='upper left')
axY.set_ylabel('mass fraction')
axY.set_xlim([0, 100])
axY.set_xlabel('t (ms)')
axT = axY.twinx()
axT.plot(t, solution['temperature'], 'k-', label='temperature')
axT.set_ylabel('T (K)')
axT.legend(loc='center right')
plt.title(name)
fig.tight_layout()
plt.show()
.. image:: one_step_heptane_ignition_files/one_step_heptane_ignition_13_0.png
Conclusions
-----------
This notebook has briefly showcased the use of Cantera to build reaction
mechanisms from Python, and the use of Spitfire to compare ignition
behavior of two n-heptane combustion mechanisms.
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
#include "combustion_kernels.h"
#include "blas_lapack_kernels.h"
#include "btddod_matrix_kernels.h"
#include <cmath>
#include <numeric>
#include <stdexcept>
#define GRIFFON_SUM2(prop) (prop(0) + prop(1))
#define GRIFFON_SUM3(prop) (GRIFFON_SUM2(prop) + prop(2))
#define GRIFFON_SUM4(prop) (GRIFFON_SUM3(prop) + prop(3))
#define GRIFFON_SUM5(prop) (GRIFFON_SUM4(prop) + prop(4))
#define GRIFFON_SUM6(prop) (GRIFFON_SUM5(prop) + prop(5))
#define GRIFFON_SUM7(prop) (GRIFFON_SUM6(prop) + prop(6))
#define GRIFFON_SUM8(prop) (GRIFFON_SUM7(prop) + prop(7))
#define THD_BDY(i) (tb_efficiencies[(0)] * y[tb_indices[(0) * nzi + i]])
#define GIBBS(i) (net_stoich[(i)] * gi[net_indices[(i)] * nzi + i])
namespace griffon
{
void CombustionKernels::flamelet_stencils(const double *dz, const int &nzi, const double *dissipationRate,
const double *invLewisNumbers, double *out_cmajor, double *out_csub,
double *out_csup, double *out_mcoeff, double *out_ncoeff) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
for (int i = 0; i < nzi; ++i)
{
const double dzt = dz[i] + dz[i + 1];
for (int l = 0; l < nSpec; ++l)
{
out_cmajor[i * nSpec + l] = -dissipationRate[1 + i] / (dz[i] * dz[i + 1]) * invLewisNumbers[l];
out_csub[i * nSpec + l] = dissipationRate[1 + i] / (dzt * dz[i]) * invLewisNumbers[l];
out_csup[i * nSpec + l] = dissipationRate[1 + i] / (dzt * dz[i + 1]) * invLewisNumbers[l];
}
out_ncoeff[i] = 1 / (dz[i] + dz[i + 1]);
out_mcoeff[i] = -out_ncoeff[i];
}
}
void CombustionKernels::flamelet_jac_indices(const int &nzi, int *out_row_indices, int *out_col_indices) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
int idx = 0;
// diagonal blocks
for (int iz = 0; iz < nzi; ++iz)
{
const int blockBase = iz * nSpec;
for (int iq = 0; iq < nSpec; ++iq)
{
for (int jq = 0; jq < nSpec; ++jq)
{
out_row_indices[idx] = blockBase + jq;
out_col_indices[idx] = blockBase + iq;
++idx;
}
}
}
// subdiagonal
for (int iz = 1; iz < nzi; ++iz)
{
const int blockBase = iz * nSpec;
for (int iq = 0; iq < nSpec; ++iq)
{
out_row_indices[idx] = blockBase + iq;
out_col_indices[idx] = blockBase + iq - nSpec;
++idx;
}
}
// superdiagonal
for (int iz = 0; iz < nzi - 1; ++iz)
{
const int blockBase = iz * nSpec;
for (int iq = 0; iq < nSpec; ++iq)
{
out_row_indices[idx] = blockBase + iq;
out_col_indices[idx] = blockBase + iq + nSpec;
++idx;
}
}
}
// ------------------------------------------------------------------------------------------------
void CombustionKernels::flamelet_rhs_test1(const double *state, const double &pressure, const double *oxyState, const double *fuelState,
const bool adiabatic, const double *T_convection, const double *h_convection,
const double *T_radiation, const double *h_radiation, const int &nzi, const double *cmajor,
const double *csub, const double *csup, const double *mcoeff, const double *ncoeff,
const double *chi, const bool include_enthalpy_flux, const bool include_variable_cp,
const bool use_scaled_heat_loss, double *out_rhs) const
{
const int ns = mechanismData.phaseData.nSpecies;
const auto minv = mechanismData.phaseData.inverseMolecularWeights.data();
const auto nr = mechanismData.reactionData.nReactions;
const auto ps = mechanismData.phaseData.referencePressure;
const auto invR = 1. / mechanismData.phaseData.Ru;
const double poverRu = pressure * invR;
const double psoverRu = ps * invR;
const auto &cpTypes = mechanismData.heatCapacityData.types;
const auto &cpCoeffs = mechanismData.heatCapacityData.coefficients;
const auto &cpMaxTs = mechanismData.heatCapacityData.maxTemperatures;
const auto &cpMinTs = mechanismData.heatCapacityData.minTemperatures;
double T[nzi];
double y[nzi * ns];
double maxT = -1;
for (int i = 0; i < nzi; ++i)
{
const int offsetTY = i * ns + 1;
const int offsetY = i;
T[i] = state[offsetTY];
maxT = std::max(maxT, T[i]);
y[offsetY + (ns - 1) * nzi] = 1.;
for (int k = 0; k < ns - 1; ++k)
{
y[offsetY + k * nzi] = state[offsetTY + k];
y[offsetY + (ns - 1) * nzi] -= y[offsetY + k * nzi];
}
}
double maxT4 = maxT * maxT * maxT * maxT;
double logT[nzi];
double invT[nzi];
double M[nzi];
double rho[nzi];
double conc[nzi];
double cp[nzi];
double cpi[nzi * ns];
double hi[nzi * ns];
double gi[nzi * ns];
double wi[nzi * ns];
double Tz[nzi];
double yz[nzi * ns];
double cpz[nzi];
double yzcpi[nzi];
double kf[nzi];
double kr[nzi];
double mtb[nzi];
double pr[nzi];
double logPrC[nzi];
double logFCent[nzi];
for (int k = 0; k < ns; ++k)
{
const double minvk = minv[k];
const int offset = k * nzi;
for (int i = 0; i < nzi; ++i)
{
M[i] += minvk * y[offset + i];
}
}
for (int i = 0; i < nzi; ++i)
{
logT[i] = std::log(T[i]);
invT[i] = 1. / T[i];
M[i] = 1. / M[i];
rho[i] = poverRu * M[i] * invT[i];
conc[i] = poverRu * invT[i];
}
for (int k = 0; k < ns; ++k)
{
const auto polyType = cpTypes[k];
const auto &c = cpCoeffs[k];
const double maxT = cpMaxTs[k];
const double minT = cpMinTs[k];
const int offset = k * nzi;
const double minvk = minv[k];
switch (polyType)
{
case CpType::CONST:
for (int i = 0; i < nzi; ++i)
{
const double t = T[i];
const double logt = logT[i];
cpi[offset + i] = minvk * c[3];
cp[i] += y[offset + i] * cpi[offset + i];
hi[offset + i] = minvk * (c[1] + c[3] * (t - c[0]));
gi[offset + i] = c[1] + c[3] * (t - c[0]) - t * (c[2] + c[3] * (logt - log(c[0])));
}
break;
case CpType::NASA7:
for (int i = 0; i < nzi; ++i)
{
const double t = T[i];
const double logt = logT[i];
if (t <= c[0] && t >= minT)
{
cpi[offset + i] = minvk * (c[8] + t * (2. * c[9] + t * (6. * c[10] + t * (12. * c[11] + 20. * t * c[12]))));
cp[i] += y[offset + i] * cpi[offset + i];
hi[offset + i] = minvk * (c[13] + t * (c[8] + t * (c[9] + t * (2. * c[10] + t * (3. * c[11] + t * 4. * c[12])))));
gi[offset + i] = c[13] + t * (c[8] - c[14] - c[8] * logt - t * (c[9] + t * (c[10] + t * (c[11] + t * c[12]))));
break;
}
else if (t > c[0] && t <= maxT)
{
cpi[offset + i] = minvk * (c[1] + t * (2. * c[2] + t * (6. * c[3] + t * (12. * c[4] + 20. * t * c[5]))));
cp[i] += y[offset + i] * cpi[offset + i];
hi[offset + i] = minvk * (c[6] + t * (c[1] + t * (c[2] + t * (2. * c[3] + t * (3. * c[4] + t * 4. * c[5])))));
gi[offset + i] = c[6] + t * (c[1] - c[7] - c[1] * logt - t * (c[2] + t * (c[3] + t * (c[4] + t * c[5]))));
break;
}
else if (t < minT)
{
cpi[offset + i] = minvk * (c[8] + minT * (2. * c[9] + minT * (6. * c[10] + minT * (12. * c[11] + 20. * minT * c[12]))));
cp[i] += y[offset + i] * cpi[offset + i];
hi[offset + i] = minvk * (c[13] + c[8] * t + minT * (2. * c[9] * t + minT * (3. * 2. * c[10] * t - c[9] + minT * (4. * 3. * c[11] * t - 2. * 2. * c[10] + minT * (5. * 4. * c[12] * t - 3. * 3. * c[11] + minT * -4. * 4. * c[12])))));
gi[offset + i] = c[13] + t * (c[8] - c[14] - c[8] * logt - t * (c[9] + t * (c[10] + t * (c[11] + t * c[12]))));
break;
}
else
{
cpi[offset + i] = minvk * (c[1] + maxT * (2. * c[2] + maxT * (6. * c[3] + maxT * (12. * c[4] + 20. * maxT * c[5]))));
cp[i] += y[offset + i] * cpi[offset + i];
hi[offset + i] = minvk * (c[6] + c[1] * t + maxT * (2. * c[2] * t + maxT * (3. * 2. * c[3] * t - c[2] + maxT * (4. * 3. * c[4] * t - 2. * 2. * c[3] + maxT * (5. * 4. * c[5] * t - 3. * 3. * c[4] + maxT * -4. * 4. * c[5])))));
gi[offset + i] = c[6] + t * (c[1] - c[7] - c[1] * logt - t * (c[2] + t * (c[3] + t * (c[4] + t * c[5]))));
break;
}
}
default:
break;
}
}
{
for (int j = 0; j < ns * nzi; ++j)
{
wi[j] = 0.;
}
for (int r = 0; r < nr; ++r)
{
const auto &rxnData = mechanismData.reactionData.reactions[r];
const auto &tb_indices = rxnData.tb_indices;
const auto &tb_efficiencies = rxnData.tb_efficiencies;
const auto n_tb = rxnData.n_tb;
const auto &rc_indices = rxnData.reactant_indices;
const auto &rc_stoich = rxnData.reactant_stoich;
const auto &rc_invmw = rxnData.reactant_invmw;
const auto n_rc = rxnData.n_reactants;
const auto &pd_indices = rxnData.product_indices;
const auto &pd_stoich = rxnData.product_stoich;
const auto &pd_invmw = rxnData.product_invmw;
const auto n_pd = rxnData.n_products;
const auto &sp_indices = rxnData.special_indices;
const auto &sp_order = rxnData.special_orders;
const auto &sp_invmw = rxnData.special_invmw;
const auto &sp_nonzero = rxnData.special_nonzero;
const auto n_sp = rxnData.n_special;
const auto &net_indices = rxnData.net_indices;
const auto &net_stoich = rxnData.net_stoich;
const auto &net_mw = rxnData.net_mw;
const auto n_net = rxnData.n_net;
const auto &kCoefs = rxnData.kFwdCoefs;
const auto &kPCoefs = rxnData.kPressureCoefs;
const auto baseEff = rxnData.thdBdyDefault;
const auto &troe = rxnData.troeParams;
switch (rxnData.kForm)
{
case RateConstantTForm::CONSTANT:
for (int i = 0; i < nzi; ++i)
{
kf[i] = kCoefs[0];
}
break;
case RateConstantTForm::LINEAR:
for (int i = 0; i < nzi; ++i)
{
kf[i] = kCoefs[0] * T[i];
}
break;
case RateConstantTForm::QUADRATIC:
for (int i = 0; i < nzi; ++i)
{
kf[i] = kCoefs[0] * T[i] * T[i];
}
break;
case RateConstantTForm::RECIPROCAL:
for (int i = 0; i < nzi; ++i)
{
kf[i] = kCoefs[0] / T[i];
}
break;
case RateConstantTForm::ARRHENIUS:
for (int i = 0; i < nzi; ++i)
{
kf[i] = kCoefs[0] * std::exp(kCoefs[1] * logT[i] - kCoefs[2] * invT[i]);
}
break;
}
switch (rxnData.type)
{
case RateType::SIMPLE:
break;
case RateType::THIRD_BODY:
switch (n_tb)
{
case 0:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= baseEff * conc[i];
}
break;
case 1:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= baseEff * conc[i] + rho[i] * (THD_BDY(0));
}
break;
case 2:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= baseEff * conc[i] + rho[i] * (GRIFFON_SUM2(THD_BDY));
}
break;
case 3:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= baseEff * conc[i] + rho[i] * (GRIFFON_SUM3(THD_BDY));
}
break;
case 4:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= baseEff * conc[i] + rho[i] * (GRIFFON_SUM4(THD_BDY));
}
break;
case 5:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= baseEff * conc[i] + rho[i] * (GRIFFON_SUM5(THD_BDY));
}
break;
case 6:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= baseEff * conc[i] + rho[i] * (GRIFFON_SUM6(THD_BDY));
}
break;
case 7:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= baseEff * conc[i] + rho[i] * (GRIFFON_SUM7(THD_BDY));
}
break;
case 8:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= baseEff * conc[i] + rho[i] * (GRIFFON_SUM8(THD_BDY));
}
break;
default:
for (int i = 0; i < nzi; ++i)
{
mtb[i] = baseEff * conc[i] + rho[i] * (GRIFFON_SUM8(THD_BDY));
}
for (int i = 8; i != n_tb; ++i)
{
for (int i = 0; i < nzi; ++i)
{
mtb[i] = rho[i] * THD_BDY(i);
}
}
for (int i = 0; i < nzi; ++i)
{
kf[i] *= mtb[i];
}
break;
}
break;
case RateType::LINDEMANN:
switch (n_tb)
{
case 0:
for (int i = 0; i < nzi; ++i)
{
kf[i] /= (1. + kf[i] / ((kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) * (baseEff * conc[i])));
}
break;
case 1:
for (int i = 0; i < nzi; ++i)
{
kf[i] /= (1. + kf[i] / ((kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) * (baseEff * conc[i] + rho[i] * (THD_BDY(0)))));
}
break;
case 2:
for (int i = 0; i < nzi; ++i)
{
kf[i] /= (1. + kf[i] / ((kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM2(THD_BDY)))));
}
break;
case 3:
for (int i = 0; i < nzi; ++i)
{
kf[i] /= (1. + kf[i] / ((kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM3(THD_BDY)))));
}
break;
case 4:
for (int i = 0; i < nzi; ++i)
{
kf[i] /= (1. + kf[i] / ((kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM4(THD_BDY)))));
}
break;
case 5:
for (int i = 0; i < nzi; ++i)
{
kf[i] /= (1. + kf[i] / ((kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM5(THD_BDY)))));
}
break;
case 6:
for (int i = 0; i < nzi; ++i)
{
kf[i] /= (1. + kf[i] / ((kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM6(THD_BDY)))));
}
break;
case 7:
for (int i = 0; i < nzi; ++i)
{
kf[i] /= (1. + kf[i] / ((kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM7(THD_BDY)))));
}
break;
case 8:
for (int i = 0; i < nzi; ++i)
{
kf[i] /= (1. + kf[i] / ((kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM8(THD_BDY)))));
}
break;
default:
for (int i = 0; i < nzi; ++i)
{
mtb[i] = baseEff * conc[i] + rho[i] * (GRIFFON_SUM8(THD_BDY));
}
for (int i = 8; i != n_tb; ++i)
{
for (int i = 0; i < nzi; ++i)
{
mtb[i] = rho[i] * THD_BDY(i);
}
}
for (int i = 0; i < nzi; ++i)
{
kf[i] /= (1 + kf[i] / ((kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) * mtb[i]));
}
break;
}
break;
case RateType::TROE:
switch (n_tb)
{
case 0:
for (int i = 0; i < nzi; ++i)
{
pr[i] = (kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) / kf[i] * (baseEff * conc[i]);
}
break;
case 1:
for (int i = 0; i < nzi; ++i)
{
pr[i] = (kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) / kf[i] * (baseEff * conc[i] + rho[i] * (THD_BDY(0)));
}
break;
case 2:
for (int i = 0; i < nzi; ++i)
{
pr[i] = (kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) / kf[i] * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM2(THD_BDY)));
}
break;
case 3:
for (int i = 0; i < nzi; ++i)
{
pr[i] = (kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) / kf[i] * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM3(THD_BDY)));
}
break;
case 4:
for (int i = 0; i < nzi; ++i)
{
pr[i] = (kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) / kf[i] * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM4(THD_BDY)));
}
break;
case 5:
for (int i = 0; i < nzi; ++i)
{
pr[i] = (kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) / kf[i] * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM5(THD_BDY)));
}
break;
case 6:
for (int i = 0; i < nzi; ++i)
{
pr[i] = (kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) / kf[i] * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM6(THD_BDY)));
}
break;
case 7:
for (int i = 0; i < nzi; ++i)
{
pr[i] = (kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) / kf[i] * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM7(THD_BDY)));
}
break;
case 8:
for (int i = 0; i < nzi; ++i)
{
pr[i] = (kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) / kf[i] * (baseEff * conc[i] + rho[i] * (GRIFFON_SUM8(THD_BDY)));
}
break;
default:
for (int i = 0; i < nzi; ++i)
{
mtb[i] = baseEff * conc[i] + rho[i] * (GRIFFON_SUM8(THD_BDY));
}
for (int i = 8; i != n_tb; ++i)
{
for (int i = 0; i < nzi; ++i)
{
mtb[i] = rho[i] * THD_BDY(i);
}
}
for (int i = 0; i < nzi; ++i)
{
pr[i] = (kPCoefs[0] * std::exp(kPCoefs[1] * logT[i] - kPCoefs[2] * invT[i])) / kf[i] * mtb[i];
}
break;
}
switch (rxnData.troeForm)
{
case TroeTermsPresent::T123:
for (int i = 0; i < nzi; ++i)
{
logFCent[i] = std::log10(
(1 - troe[0]) * std::exp(-T[i] / troe[1]) + troe[0] * std::exp(-T[i] / troe[2]) + std::exp(-invT[i] * troe[3]));
}
break;
case TroeTermsPresent::T12:
for (int i = 0; i < nzi; ++i)
{
logFCent[i] = std::log10((1 - troe[0]) * std::exp(-T[i] / troe[1]) + troe[0] * std::exp(-T[i] / troe[2]) + 0.0);
}
break;
case TroeTermsPresent::T1:
for (int i = 0; i < nzi; ++i)
{
logFCent[i] = std::log10((1 - troe[0]) * std::exp(-T[i] / troe[1]) + 0.0 + 0.0);
}
break;
case TroeTermsPresent::T23:
for (int i = 0; i < nzi; ++i)
{
logFCent[i] = std::log10(0.0 + troe[0] * std::exp(-T[i] / troe[2]) + std::exp(-invT[i] * troe[3]));
}
break;
case TroeTermsPresent::T2:
for (int i = 0; i < nzi; ++i)
{
logFCent[i] = std::log10(0.0 + troe[0] * std::exp(-T[i] / troe[2]) + 0.0);
}
break;
case TroeTermsPresent::T13:
for (int i = 0; i < nzi; ++i)
{
logFCent[i] = std::log10((1 - troe[0]) * std::exp(-T[i] / troe[1]) + 0.0 + std::exp(-invT[i] * troe[3]));
}
break;
case TroeTermsPresent::T3:
for (int i = 0; i < nzi; ++i)
{
logFCent[i] = std::log10(0.0 + 0.0 + std::exp(-invT[i] * troe[3]));
}
break;
case TroeTermsPresent::NO_TROE_TERMS:
default:
{
throw std::runtime_error("no troe Terms flagged for evaluation");
}
}
#define CTROE (-0.4 - 0.67 * logFCent[i])
#define NTROE (0.75 - 1.27 * logFCent[i])
#define F1 (logPrC[i] / (NTROE - 0.14 * logPrC[i]))
for (int i = 0; i < nzi; ++i)
{
logPrC[i] = std::log10(std::max(pr[i], 1.e-300)) + CTROE;
kf[i] *= std::pow(10, logFCent[i] / (1. + F1 * F1)) * pr[i] / (1 + pr[i]);
}
break;
default:
{
throw std::runtime_error("unidentified reaction");
}
}
#undef CTROE
#undef NTROE
#undef F1
if (rxnData.hasOrders)
{
for (int k = 0; k < n_sp; ++k)
{
if (sp_nonzero[k])
{
const double sporderk = sp_order[k];
const double spminvk = sp_invmw[k];
const int offset = sp_indices[k] * nzi;
for (int i = 0; i < nzi; ++i)
{
kf[i] *= std::pow(std::max(y[offset + i] * rho[i] * spminvk, 0.), sporderk);
kr[i] = 0.;
}
}
}
}
else
{
if (rxnData.reversible)
{
switch (n_net)
{
case 3:
for (int i = 0; i < nzi; ++i)
{
kr[i] = kf[i] * std::exp(rxnData.sumStoich * std::log(psoverRu * invT[i]) - invT[i] * invR * (GRIFFON_SUM3(GIBBS)));
}
break;
case 2:
for (int i = 0; i < nzi; ++i)
{
kr[i] = kf[i] * std::exp(rxnData.sumStoich * std::log(psoverRu * invT[i]) - invT[i] * invR * (GRIFFON_SUM2(GIBBS)));
}
break;
case 4:
for (int i = 0; i < nzi; ++i)
{
kr[i] = kf[i] * std::exp(rxnData.sumStoich * std::log(psoverRu * invT[i]) - invT[i] * invR * (GRIFFON_SUM4(GIBBS)));
}
break;
case 5:
for (int i = 0; i < nzi; ++i)
{
kr[i] = kf[i] * std::exp(rxnData.sumStoich * std::log(psoverRu * invT[i]) - invT[i] * invR * (GRIFFON_SUM5(GIBBS)));
}
break;
case 6:
for (int i = 0; i < nzi; ++i)
{
kr[i] = kf[i] * std::exp(rxnData.sumStoich * std::log(psoverRu * invT[i]) - invT[i] * invR * (GRIFFON_SUM6(GIBBS)));
}
break;
case 7:
for (int i = 0; i < nzi; ++i)
{
kr[i] = kf[i] * std::exp(rxnData.sumStoich * std::log(psoverRu * invT[i]) - invT[i] * invR * (GRIFFON_SUM7(GIBBS)));
}
break;
case 8:
for (int i = 0; i < nzi; ++i)
{
kr[i] = kf[i] * std::exp(rxnData.sumStoich * std::log(psoverRu * invT[i]) - invT[i] * invR * (GRIFFON_SUM8(GIBBS)));
}
break;
}
}
#define C_R(j) (y[rc_indices[j] * nzi + i] * rho[i] * rc_invmw[j])
#define C_P(j) (y[pd_indices[j] * nzi + i] * rho[i] * pd_invmw[j])
switch (rxnData.forwardOrder)
{
case ReactionOrder::ONE:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= C_R(0);
}
break;
case ReactionOrder::TWO:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= C_R(0) * C_R(0);
}
break;
case ReactionOrder::ONE_ONE:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= C_R(0) * C_R(1);
}
break;
case ReactionOrder::ONE_ONE_ONE:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= C_R(0) * C_R(1) * C_R(2);
}
break;
case ReactionOrder::TWO_ONE:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= C_R(0) * C_R(0) * C_R(1);
}
break;
case ReactionOrder::ONE_TWO:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= C_R(0) * C_R(1) * C_R(1);
}
break;
default:
for (int j = 0; j < n_rc; ++j)
{
switch (rc_stoich[j])
{
case 1:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= C_R(j);
}
break;
case 2:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= C_R(j) * C_R(j);
}
break;
case 3:
for (int i = 0; i < nzi; ++i)
{
kf[i] *= C_R(j) * C_R(j) * C_R(j);
}
break;
}
}
break;
}
if (rxnData.reversible)
{
switch (rxnData.reverseOrder)
{
case ReactionOrder::ONE:
for (int i = 0; i < nzi; ++i)
{
kr[i] *= C_P(0);
}
break;
case ReactionOrder::TWO:
for (int i = 0; i < nzi; ++i)
{
kr[i] *= C_P(0) * C_P(0);
}
break;
case ReactionOrder::ONE_ONE:
for (int i = 0; i < nzi; ++i)
{
kr[i] *= C_P(0) * C_P(1);
}
break;
case ReactionOrder::ONE_ONE_ONE:
for (int i = 0; i < nzi; ++i)
{
kr[i] *= C_P(0) * C_P(1) * C_P(2);
}
break;
case ReactionOrder::TWO_ONE:
for (int i = 0; i < nzi; ++i)
{
kr[i] *= C_P(0) * C_P(0) * C_P(1);
}
break;
case ReactionOrder::ONE_TWO:
for (int i = 0; i < nzi; ++i)
{
kr[i] *= C_P(0) * C_P(1) * C_P(1);
}
break;
default:
for (int j = 0; j < n_pd; ++j)
{
switch (pd_stoich[j])
{
case -1:
for (int i = 0; i < nzi; ++i)
{
kr[i] *= C_P(j);
}
break;
case -2:
for (int i = 0; i < nzi; ++i)
{
kr[i] *= C_P(j) * C_P(j);
}
break;
case -3:
for (int i = 0; i < nzi; ++i)
{
kr[i] *= C_P(j) * C_P(j) * C_P(j);
}
break;
}
}
break;
}
}
#undef C_R
#undef C_P
}
for (int k = 0; k < n_net; ++k)
{
const auto offset = net_indices[k] * nzi;
const auto numw = net_stoich[k] * net_mw[k];
for (int i = 0; i < nzi; ++i)
{
wi[offset + i] -= numw * (kf[i] - kr[i]);
}
}
}
}
for (int k = 0; k < ns - 1; ++k)
{
const int offset = k * nzi;
for (int i = 0; i < nzi; ++i)
{
out_rhs[i * ns] -= wi[offset + i] * hi[offset + i] / (rho[i] * cp[i]);
out_rhs[i * ns + k] = wi[offset + i] / rho[i];
}
}
{
const int offset = (ns - 1) * nzi;
for (int i = 0; i < nzi; ++i)
{
out_rhs[i * ns] = (out_rhs[i * ns] - wi[offset + i] * hi[offset + i] / (rho[i] * cp[i])) / (rho[i] * cp[i]);
}
}
if (!adiabatic)
{
if (use_scaled_heat_loss)
{
for (int i = 0; i < nzi; ++i)
{
const double &hc = h_convection[i];
const double &hr = h_radiation[i];
const double &Tc = T_convection[i];
const double &Tr = T_radiation[i];
const double Tr4 = Tr * Tr * Tr * Tr;
out_rhs[i * ns] += (hc * (Tc - T[i]) / (maxT - Tc) + hr * 5.67e-8 * (Tr4 - T[i] * T[i] * T[i] * T[i]) / (maxT4 - Tr4)) / (rho[i] * cp[i]);
}
}
else
{
for (int i = 0; i < nzi; ++i)
{
const double &hc = h_convection[i];
const double &hr = h_radiation[i];
const double &Tc = T_convection[i];
const double &Tr = T_radiation[i];
out_rhs[i * ns] += (hc * (Tc - T[i]) + hr * 5.67e-8 * (Tr * Tr * Tr * Tr - T[i] * T[i] * T[i] * T[i])) / (rho[i] * cp[i]);
}
}
}
if (include_enthalpy_flux or include_variable_cp)
{
for (int i = 1; i < nzi - 1; ++i)
{
Tz[i] = mcoeff[i] * T[i - 1] + ncoeff[i] * T[i + 1];
cpz[i] = mcoeff[i] * cp[i - 1] + ncoeff[i] * cp[i + 1];
}
for (int k = 0; k < ns; ++k)
{
const int offset = k * nzi;
for (int i = 1; i < nzi - 1; ++i)
{
yz[offset + i] = mcoeff[i] * y[offset + i - 1] + ncoeff[i] * y[offset + i + 1];
}
}
double yoxy[ns];
double yfuel[ns];
double Moxy = 0.;
double Mfuel = 0.;
double cpoxy = 0.;
double cpfuel = 0.;
yoxy[ns - 1] = 1.;
yfuel[ns - 1] = 1.;
for (int k = 0; k < ns; ++k)
{
yoxy[k] = oxyState[1 + k];
yfuel[k] = fuelState[1 + k];
yoxy[ns - 1] -= yoxy[k];
yfuel[ns - 1] -= yfuel[k];
Moxy += yoxy[k] * minv[k];
Mfuel += yfuel[k] * minv[k];
}
for (int k = 0; k < ns; ++k)
{
const auto polyType = cpTypes[k];
const auto &c = cpCoeffs[k];
const double maxT = cpMaxTs[k];
const double minT = cpMinTs[k];
const double minvk = minv[k];
double t;
switch (polyType)
{
case CpType::CONST:
cpoxy += yoxy[k] * minvk * c[3];
cpfuel += yfuel[k] * minvk * c[3];
break;
case CpType::NASA7:
t = oxyState[0];
if (t <= c[0] && t >= minT)
{
cpoxy += yoxy[k] * minvk * (c[8] + t * (2. * c[9] + t * (6. * c[10] + t * (12. * c[11] + 20. * t * c[12]))));
break;
}
else if (t > c[0] && t <= maxT)
{
cpoxy += yoxy[k] * minvk * (c[1] + t * (2. * c[2] + t * (6. * c[3] + t * (12. * c[4] + 20. * t * c[5]))));
break;
}
else if (t < minT)
{
cpoxy += yoxy[k] * minvk * (c[8] + minT * (2. * c[9] + minT * (6. * c[10] + minT * (12. * c[11] + 20. * minT * c[12]))));
break;
}
else
{
cpoxy += yoxy[k] * minvk * (c[1] + maxT * (2. * c[2] + maxT * (6. * c[3] + maxT * (12. * c[4] + 20. * maxT * c[5]))));
break;
}
t = fuelState[0];
if (t <= c[0] && t >= minT)
{
cpfuel += yfuel[k] * minvk * (c[8] + t * (2. * c[9] + t * (6. * c[10] + t * (12. * c[11] + 20. * t * c[12]))));
break;
}
else if (t > c[0] && t <= maxT)
{
cpfuel += yfuel[k] * minvk * (c[1] + t * (2. * c[2] + t * (6. * c[3] + t * (12. * c[4] + 20. * t * c[5]))));
break;
}
else if (t < minT)
{
cpfuel += yfuel[k] * minvk * (c[8] + minT * (2. * c[9] + minT * (6. * c[10] + minT * (12. * c[11] + 20. * minT * c[12]))));
break;
}
else
{
cpfuel += yfuel[k] * minvk * (c[1] + maxT * (2. * c[2] + maxT * (6. * c[3] + maxT * (12. * c[4] + 20. * maxT * c[5]))));
break;
}
default:
break;
}
}
{
const int i = 0;
Tz[i] = mcoeff[0] * oxyState[0] + ncoeff[0] * T[1];
cpz[i] = mcoeff[0] * cpoxy + ncoeff[0] * cp[1];
for (int k = 0; k < ns; ++k)
{
yz[k * ns] = mcoeff[0] * yoxy[k] + ncoeff[0] * y[k * ns + 1];
}
}
{
const int i = nzi - 1;
Tz[i] = mcoeff[nzi - 1] * T[nzi - 2] + ncoeff[nzi - 1] * fuelState[0];
cpz[i] = mcoeff[nzi - 1] * cp[nzi - 2] + ncoeff[nzi - 1] * cpfuel;
for (int k = 0; k < ns; ++k)
{
yz[k * ns + nzi - 1] = mcoeff[nzi - 1] * y[k * ns + nzi - 2] + ncoeff[0] * yfuel[k];
}
}
if (include_variable_cp)
{
for (int i = 0; i < nzi; ++i)
{
out_rhs[i * ns] += 0.5 * chi[i] * cpz[i] / cp[i] * Tz[i];
}
}
if (include_enthalpy_flux)
{
for (int k = 0; k < ns; ++k)
{
const int offset = k * nzi;
for (int i = 0; i < nzi; ++i)
{
yzcpi[i] += yz[offset + i] * cpi[offset + i];
}
}
for (int i = 0; i < nzi; ++i)
{
out_rhs[i * ns] += 0.5 * chi[i] / cp[i] * Tz[i] * yzcpi[i];
}
}
}
const int endIdx = (nzi - 1) * ns;
for (int i = ns; i < endIdx; ++i)
{
out_rhs[i] += cmajor[i] * state[i] + csub[i] * state[i - ns] + csup[i] * state[i + ns];
}
for (int j = 0; j < ns; ++j)
{
out_rhs[j] += cmajor[j] * state[j] + csub[j] * oxyState[j] + csup[j] * state[j + ns];
out_rhs[endIdx + j] += cmajor[endIdx + j] * state[endIdx + j] + csub[endIdx + j] * state[endIdx + j - ns] + csup[endIdx + j] * fuelState[j];
}
}
// ------------------------------------------------------------------------------------------------
void CombustionKernels::flamelet_rhs(const double *state, const double &pressure, const double *oxyState,
const double *fuelState, const bool adiabatic, const double *T_convection,
const double *h_convection, const double *T_radiation, const double *h_radiation,
const int &nzi, const double *cmajor, const double *csub, const double *csup,
const double *mcoeff, const double *ncoeff, const double *chi,
const bool include_enthalpy_flux, const bool include_variable_cp,
const bool use_scaled_heat_loss, double *out_rhs) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
double maxT = -1;
double maxT4 = -1;
if (use_scaled_heat_loss)
{
for (int i = 0; i < nzi; ++i)
{
maxT = std::max(maxT, state[i * nSpec]);
}
maxT4 = maxT * maxT * maxT * maxT;
}
double cpz_grid[nzi];
if (include_variable_cp)
{
double cp_grid[nzi];
for (int i = 0; i < nzi; ++i)
{
double y[nSpec];
extract_y(&state[i * nSpec + 1], nSpec, y);
cp_grid[i] = cp_mix(state[i * nSpec], y);
}
for (int i = 0; i < nzi; ++i)
{
if (i == 0)
{
double y[nSpec];
const double *b_state = oxyState;
extract_y(&b_state[1], nSpec, y);
cpz_grid[i] = mcoeff[i] * cp_mix(b_state[0], y) + ncoeff[i] * cp_grid[1];
}
else if (i == nzi - 1)
{
double y[nSpec];
const double *b_state = fuelState;
extract_y(&b_state[1], nSpec, y);
cpz_grid[i] = mcoeff[i] * cp_grid[nzi - 2] + ncoeff[i] * cp_mix(b_state[0], y);
}
else
{
cpz_grid[i] = mcoeff[i] * cp_grid[i - 1] + ncoeff[i] * cp_grid[i + 1];
}
}
}
for (int i = 0; i < nzi; ++i)
{
double rho;
double enthalpies[nSpec];
double w[nSpec];
double cp;
double cpi[nSpec];
const double T = state[i * nSpec];
double y[nSpec];
extract_y(&state[i * nSpec + 1], nSpec, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_density(pressure, T, mmw, &rho);
if (include_enthalpy_flux)
{
cp_mix_and_species(T, y, &cp, cpi);
}
else
{
cp = cp_mix(T, y);
}
species_enthalpies(T, enthalpies);
production_rates(T, rho, mmw, y, w);
chem_rhs_isobaric(rho, cp, enthalpies, w, &out_rhs[i * nSpec]);
if (!adiabatic)
{
const double hc = h_convection[i];
const double hr = h_radiation[i];
const double Tc = T_convection[i];
const double Tr = T_radiation[i];
if (use_scaled_heat_loss)
{
const double Tr4 = Tr * Tr * Tr * Tr;
const double q = hc * (Tc - T) / (maxT - Tc) + hr * 5.67e-8 * (Tr4 - T * T * T * T) / (maxT4 - Tr4);
out_rhs[i * nSpec] += q / (rho * cp);
}
else
{
const double q = hc * (Tc - T) + hr * 5.67e-8 * (Tr * Tr * Tr * Tr - T * T * T * T);
out_rhs[i * nSpec] += q / (rho * cp);
}
}
if (include_enthalpy_flux)
{
const double cpn = cpi[nSpec - 1];
double dTdZ;
double dYdZ_cpi = 0.;
if (i == 0)
{
const double *state_nm1 = oxyState;
const double *state_np1 = &state[nSpec];
dTdZ = mcoeff[i] * state_nm1[0] + ncoeff[i] * state_np1[0];
for (int j = 0; j < nSpec - 1; ++j)
{
dYdZ_cpi += (cpi[j] - cpn) * (mcoeff[i] * state_nm1[1 + j] + ncoeff[i] * state_np1[1 + j]);
}
}
else if (i == nzi - 1)
{
const double *state_nm1 = &state[(nzi - 2) * nSpec];
const double *state_np1 = fuelState;
dTdZ = mcoeff[i] * state_nm1[0] + ncoeff[i] * state_np1[0];
for (int j = 0; j < nSpec - 1; ++j)
{
dYdZ_cpi += (cpi[j] - cpn) * (mcoeff[i] * state_nm1[1 + j] + ncoeff[i] * state_np1[1 + j]);
}
}
else
{
const double *state_nm1 = &state[(i - 1) * nSpec];
const double *state_np1 = &state[(i + 1) * nSpec];
dTdZ = mcoeff[i] * state_nm1[0] + ncoeff[i] * state_np1[0];
for (int j = 0; j < nSpec - 1; ++j)
{
dYdZ_cpi += (cpi[j] - cpn) * (mcoeff[i] * state_nm1[1 + j] + ncoeff[i] * state_np1[1 + j]);
}
}
out_rhs[i * nSpec] += 0.5 * chi[i] / cp * dTdZ * dYdZ_cpi;
if (include_variable_cp)
{
out_rhs[i * nSpec] += 0.5 * chi[i] * cpz_grid[i] / cp * dTdZ;
}
}
if (include_variable_cp and not include_enthalpy_flux)
{
double dTdZ;
if (i == 0)
{
const double *state_nm1 = oxyState;
const double *state_np1 = &state[nSpec];
dTdZ = mcoeff[i] * state_nm1[0] + ncoeff[i] * state_np1[0];
}
else if (i == nzi - 1)
{
const double *state_nm1 = &state[(nzi - 2) * nSpec];
const double *state_np1 = fuelState;
dTdZ = mcoeff[i] * state_nm1[0] + ncoeff[i] * state_np1[0];
}
else
{
const double *state_nm1 = &state[(i - 1) * nSpec];
const double *state_np1 = &state[(i + 1) * nSpec];
dTdZ = mcoeff[i] * state_nm1[0] + ncoeff[i] * state_np1[0];
}
out_rhs[i * nSpec] += 0.5 * chi[i] * cpz_grid[i] / cp * dTdZ;
}
}
const int endIdx = (nzi - 1) * nSpec;
for (int i = nSpec; i < endIdx; ++i)
{
out_rhs[i] += cmajor[i] * state[i] + csub[i] * state[i - nSpec] + csup[i] * state[i + nSpec];
}
for (int j = 0; j < nSpec; ++j)
{
out_rhs[j] += cmajor[j] * state[j] + csub[j] * oxyState[j] + csup[j] * state[j + nSpec];
out_rhs[endIdx + j] += cmajor[endIdx + j] * state[endIdx + j] + csub[endIdx + j] * state[endIdx + j - nSpec] + csup[endIdx + j] * fuelState[j];
}
}
void CombustionKernels::flamelet_jacobian(const double *state, const double &pressure, const double *oxyState,
const double *fuelState, const bool adiabatic, const double *T_convection,
const double *h_convection, const double *T_radiation, const double *h_radiation,
const int &nzi, const double *cmajor, const double *csub, const double *csup,
const double *mcoeff, const double *ncoeff, const double *chi,
const bool compute_eigenvalues, const double diffterm,
const bool scale_and_offset, const double prefactor,
const int &rates_sensitivity_option, const int &sensitivity_transform_option,
const bool include_enthalpy_flux, const bool include_variable_cp,
const bool use_scaled_heat_loss, double *out_expeig, double *out_jac) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
const int nelements = nSpec * (nzi * nSpec + 2 * (nzi - 1));
const int blocksize = nSpec * nSpec;
double rhsTemp[nSpec];
double realParts[nSpec];
double imagParts[nSpec];
double cp[nzi];
double cpsensT[nzi];
double maxT = -1;
double maxT4 = -1;
if (use_scaled_heat_loss)
{
for (int i = 0; i < nzi; ++i)
{
maxT = std::max(maxT, state[i * nSpec]);
}
maxT4 = maxT * maxT * maxT * maxT;
}
int idx = 0;
for (int iz = 0; iz < nzi; ++iz)
{
double rho;
double cpi[nSpec];
double cpisensT[nSpec];
double enthalpies[nSpec];
double w[nSpec];
double wsens[(nSpec + 1) * (nSpec + 1)];
double primJac[nSpec * (nSpec + 1)];
const double T = state[iz * nSpec];
double y[nSpec];
extract_y(&state[iz * nSpec + 1], nSpec, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_density(pressure, T, mmw, &rho);
cp_mix_and_species(T, y, &cp[iz], cpi);
species_enthalpies(T, enthalpies);
cp_sens_T(T, y, &cpsensT[iz], cpisensT);
switch (rates_sensitivity_option)
{
case 1:
prod_rates_sens_no_tbaf(T, rho, mmw, y, w, wsens);
break;
case 0:
prod_rates_sens_exact(T, rho, mmw, y, w, wsens);
break;
case 2:
prod_rates_sens_sparse(T, rho, mmw, y, w, wsens);
break;
}
chem_jac_isobaric(pressure, T, y, mmw, rho, cp[iz], cpi, cpsensT[iz], enthalpies, w, wsens, rhsTemp, primJac);
if (!adiabatic)
{
const double Tc = T_convection[iz];
const double Tr = T_radiation[iz];
const double hc = h_convection[iz];
const double hr = h_radiation[iz];
const double invRhoCp = 1. / (rho * cp[iz]);
const double invCp = 1. / cp[iz];
double q;
if (use_scaled_heat_loss)
{
const double Tr4 = Tr * Tr * Tr * Tr;
q = (hc * (Tc - T) / (maxT - Tc) + hr * 5.67e-8 * (Tr4 - T * T * T * T) / (maxT4 - Tr4)) * invRhoCp;
primJac[nSpec] -= invCp * cpsensT[iz] * q + invRhoCp * (hc / (maxT - Tc) + 4. * hr / (maxT4 - Tr4) * 5.67e-8 * T * T * T);
}
else
{
q = (hc * (Tc - T) + hr * 5.67e-8 * (Tr * Tr * Tr * Tr - T * T * T * T)) * invRhoCp;
primJac[nSpec] -= invCp * cpsensT[iz] * q + invRhoCp * (hc + 4. * hr * 5.67e-8 * T * T * T);
}
primJac[0] -= q / rho;
const double cpn = cpi[nSpec - 1];
for (int k = 0; k < nSpec + 1; ++k)
{
primJac[(2 + k) * nSpec] += invCp * q * (cpn - cpi[k]);
}
}
switch (sensitivity_transform_option)
{
case 0:
transform_isobaric_primitive_jacobian(rho, pressure, T, mmw, primJac, &out_jac[idx]);
break;
}
if (compute_eigenvalues)
{
griffon::lapack::eigenvalues(nSpec, &out_jac[idx], realParts, imagParts);
double exp_eig = 0.;
for (int iq = 0; iq < nSpec; ++iq)
{
exp_eig = std::max(exp_eig, std::max(realParts[iq] - diffterm, 0.));
}
for (int iq = 0; iq < nSpec; ++iq)
{
out_expeig[iz * nSpec + iq] = exp_eig;
}
}
for (int iq = 0; iq < nSpec; ++iq)
{
out_jac[idx + iq * (nSpec + 1)] += cmajor[iz * nSpec + iq];
}
idx += blocksize;
}
if (include_enthalpy_flux)
{ // note that this is very inexact. this should be improved but convergence seems fine
for (int i = 1; i < nzi - 1; ++i)
{
const double dTdZ = mcoeff[i] * state[(i - 1) * nSpec] + ncoeff[i] * state[(i + 1) * nSpec];
const double dcpdZ = mcoeff[i] * cp[i - 1] + ncoeff[i] * cp[i + 1];
const double f1 = 0.5 * chi[i] / cp[i] * dTdZ * dcpdZ;
out_jac[i * blocksize] -= f1 / cp[i] * cpsensT[i];
}
{
double y[nSpec];
extract_y(&oxyState[1], nSpec, y);
const double cp_oxy = cp_mix(oxyState[0], y);
const int i = 0;
const double dTdZ = mcoeff[i] * oxyState[0] + ncoeff[i] * state[(i + 1) * nSpec];
const double dcpdZ = mcoeff[i] * cp_oxy + ncoeff[i] * cp[i + 1];
const double f1 = 0.5 * chi[i] / cp[i] * dTdZ * dcpdZ;
out_jac[i * blocksize] -= f1 / cp[i] * cpsensT[i];
}
{
double y[nSpec];
extract_y(&fuelState[1], nSpec, y);
const double cp_fuel = cp_mix(fuelState[0], y);
const int i = nzi - 1;
const double dTdZ = mcoeff[i] * state[(i - 1) * nSpec] + ncoeff[i] * fuelState[0];
const double dcpdZ = mcoeff[i] * cp[i - 1] + ncoeff[i] * cp_fuel;
const double f1 = 0.5 * chi[i] / cp[i] * dTdZ * dcpdZ;
out_jac[i * blocksize] -= f1 / cp[i] * cpsensT[i];
}
}
// we should consider adding the variable cp sensitivities here, at least something close
const int off_diag_offset = (nzi - 1) * nSpec;
for (int iz = 1; iz < nzi; ++iz)
{
for (int iq = 0; iq < nSpec; ++iq)
{
out_jac[idx] += csub[iz * nSpec + iq];
out_jac[off_diag_offset + idx] += csup[(iz - 1) * nSpec + iq];
++idx;
}
}
if (scale_and_offset)
{
for (int i = 0; i < nelements; ++i)
{
out_jac[i] *= prefactor;
}
for (int iz = 0; iz < nzi; ++iz)
{
for (int iq = 0; iq < nSpec; ++iq)
{
out_jac[iz * blocksize + iq * (nSpec + 1)] -= 1.;
}
}
}
}
} // namespace griffon
<file_sep>import unittest
from numpy import max, abs, ones, zeros, hstack, sqrt, finfo
from cantera import gas_constant
from spitfire import ChemicalMechanismSpec as Mechanism
import pickle
import cantera as ct
ct.suppress_thermo_warnings() # because we are faking heat capacity polynomials
species_decl = list([ct.Species('A', 'H:2'),
ct.Species('B', 'H:1'),
ct.Species('C', 'O:1'),
ct.Species('D', 'O:2'),
ct.Species('E', 'H:1, O:2'),
ct.Species('N', 'H:1, O:1')])
species_dict = dict({'const': list(), 'nasa7': list(), 'nasa9-1': list(), 'nasa9-2': list(), 'nasa9-3': list()})
for i, s in enumerate(species_decl):
species_dict['const'].append(ct.Species(s.name, s.composition))
species_dict['const'][-1].thermo = ct.ConstantCp(300., 3000., 101325., (300., 0., 0., float(i + 1) * 1.e4))
species_dict['nasa7'].append(ct.Species(s.name, s.composition))
coeffs1 = [float(i + 1) * v for v in [1.e0, 1.e-2, 1.e-4, 1.e-6, 1.e-8, 1.e-10, 1.e-12]]
coeffs2= [float(i + 2) * v for v in [1.e0, 1.e-2, 1.e-4, 1.e-6, 1.e-8, 1.e-10, 1.e-12]]
species_dict['nasa7'][-1].thermo = ct.NasaPoly2(300., 3000., 101325., hstack([1200.] + coeffs1 + coeffs2))
species_dict['nasa9-1'].append(ct.Species(s.name, s.composition))
coeffs = [float(i + 1) * v for v in [1e0, 1e0, 1.e0, 1.e-2, 1.e-4, 1.e-6, 1.e-10, 1.e2, 1.e1]]
species_dict['nasa9-1'][-1].thermo = ct.Nasa9PolyMultiTempRegion(300., 3000., 101325., hstack([1] + [300, 3000.] + coeffs))
species_dict['nasa9-2'].append(ct.Species(s.name, s.composition))
coeffs1 = [float(i + 1) * v for v in [1e0, 1e0, 1.e0, 1.e-2, 1.e-4, 1.e-6, 1.e-10, 1.e2, 1.e1]]
coeffs2 = [float(i + 2) * v for v in [1e0, 1e0, 1.e0, 1.e-2, 1.e-4, 1.e-6, 1.e-10, 1.e2, 1.e1]]
species_dict['nasa9-2'][-1].thermo = ct.Nasa9PolyMultiTempRegion(300., 3000., 101325., hstack([2] + [300, 1200.] + coeffs1 + [1200., 3000.] + coeffs2))
species_dict['nasa9-3'].append(ct.Species(s.name, s.composition))
coeffs1 = [float(i + 1) * v for v in [1e0, 1e0, 1.e0, 1.e-2, 1.e-4, 1.e-6, 1.e-10, 1.e2, 1.e1]]
coeffs2 = [float(i + 2) * v for v in [1e0, 1e0, 1.e0, 1.e-2, 1.e-4, 1.e-6, 1.e-10, 1.e2, 1.e1]]
coeffs3 = [float(i + 3) * v for v in [1e0, 1e0, 1.e0, 1.e-2, 1.e-4, 1.e-6, 1.e-10, 1.e2, 1.e1]]
species_dict['nasa9-3'][-1].thermo = ct.Nasa9PolyMultiTempRegion(300., 3000., 101325., hstack([3] + [300, 1200.] + coeffs1 + [1200., 2000.] + coeffs2 + [2000., 3000.] + coeffs3))
mechs = [(s, Mechanism.from_solution(ct.Solution(transport_model=None, thermo='IdealGas', kinetics='GasKinetics', species=species_dict[s], reactions=[]))) for s in species_dict]
tolerance = 1.e-14
def do_mmw(griffon, gas, T, p, y):
gas.TPY = T, p, y
ct = gas.mean_molecular_weight
gr = griffon.mixture_molecular_weight(y)
return abs(gr - ct) / abs(gr) < tolerance
def do_density(griffon, gas, T, p, y):
gas.TPY = T, p, y
ct = gas.density_mass
gr = griffon.ideal_gas_density(p, T, y)
return abs(gr - ct) / abs(gr) < tolerance
def do_pressure(griffon, gas, T, p, y):
gas.TPY = T, p, y
rho = gas.density_mass
gr = griffon.ideal_gas_pressure(rho, T, y)
return abs(gr - p) / abs(gr) < tolerance
def do_cpmix(griffon, gas, T, p, y):
gas.TPY = T, p, y
ct = gas.cp_mass
gr = griffon.cp_mix(T, y)
return abs(gr - ct) / abs(gr) < tolerance
def do_cvmix(griffon, gas, T, p, y):
gas.TPY = T, p, y
ct = gas.cv_mass
gr = griffon.cv_mix(T, y)
return abs(gr - ct) / abs(gr) < tolerance
def do_cpspec(griffon, gas, T, p, y):
gas.TPY = T, p, y
ct = gas.standard_cp_R * gas_constant / gas.molecular_weights
gr = zeros(gas.n_species)
griffon.species_cp(T, gr)
return max(abs(gr - ct) / abs(gr)) < tolerance
def do_dcpdT(griffon, gas, T, p, y):
dcpspecdT_gr = zeros(gas.n_species)
griffon.dcpdT_species(T, y, dcpspecdT_gr)
gas.TPY = T, p, y
cpspec1_ct = gas.standard_cp_R * gas_constant / gas.molecular_weights
dT = 1.e-2
gas.TPY = T + dT, p, y
cpspec2_ct = gas.standard_cp_R * gas_constant / gas.molecular_weights
dcpspecdT_ct = (cpspec2_ct - cpspec1_ct) / dT
this_fd_tol = 1.e-4
return max(abs(dcpspecdT_ct - dcpspecdT_gr) / cpspec1_ct.dot(y)) < this_fd_tol
def do_cvspec(griffon, gas, T, p, y):
gas.TPY = T, p, y
ct = gas.standard_cp_R * gas_constant / gas.molecular_weights - gas_constant / gas.molecular_weights
gr = zeros(gas.n_species)
griffon.species_cv(T, gr)
return max(abs(gr - ct) / abs(gr)) < tolerance
def do_hmix(griffon, gas, T, p, y):
gas.TPY = T, p, y
ct = gas.enthalpy_mass
gr = griffon.enthalpy_mix(T, y)
return abs(abs(gr - ct) / (abs(gr) + 1.e0)) < tolerance
def do_emix(griffon, gas, T, p, y):
gas.TPY = T, p, y
ct = gas.int_energy_mass
gr = griffon.energy_mix(T, y)
return abs(abs(gr - ct) / (abs(gr) + 1.e0)) < tolerance
def do_hspec(griffon, gas, T, p, y):
gas.TPY = T, p, y
ct = gas.standard_enthalpies_RT * gas.T * gas_constant / gas.molecular_weights
gr = zeros(gas.n_species)
griffon.species_enthalpies(T, gr)
return max(abs(gr - ct) / (abs(gr) + 1.e0)) < tolerance
def do_espec(griffon, gas, T, p, y):
gas.TPY = T, p, y
ct = gas.standard_int_energies_RT * gas.T * gas_constant / gas.molecular_weights
gr = zeros(gas.n_species)
griffon.species_energies(T, gr)
return max(abs(gr - ct) / (abs(gr) + 1.e0)) < tolerance
quantity_test_dict = {'mixture molecular weight': do_mmw,
'density': do_density,
'pressure': do_pressure,
'cp mix': do_cpmix,
'cv mix': do_cvmix,
'cp species': do_cpspec,
'cv species': do_cvspec,
'enthalpy mix': do_hmix,
'energy mix': do_emix,
'enthalpy species': do_hspec,
'energy species': do_espec,
'dcpdT': do_dcpdT}
temperature_dict = {'low': 300., 'high': 1400.}
def validate_on_mechanism(mech, temperature, quantity, serialize_mech):
if serialize_mech:
serialized = pickle.dumps(mech)
mech = pickle.loads(serialized)
r = mech.griffon
gas = mech.gas
p = 101325.
gas.TPY = temperature, p, ones(gas.n_species)
y = gas.Y
return quantity_test_dict[quantity](r, gas, temperature, p, y)
def create_test(m, T, quantity, serialize_mech):
def test(self):
self.assertTrue(validate_on_mechanism(m, T, quantity, serialize_mech))
return test
class Accuracy(unittest.TestCase):
pass
for mech in mechs:
for quantity in quantity_test_dict.keys():
for temperature in temperature_dict:
for serialize_mech in [False, True]:
testname = 'test_' + quantity.replace(' ', '-') + '_' + mech[0] + '_' + temperature + 'T' + \
f'{"_serialized_mech" if serialize_mech else ""}'
setattr(Accuracy, testname, create_test(mech[1],
temperature_dict[temperature],
quantity,
serialize_mech))
if __name__ == '__main__':
unittest.main()
<file_sep>spitfire.data package
=====================
Submodules
----------
spitfire.data.get module
------------------------
.. automodule:: spitfire.data.get
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: spitfire.data
:members:
:undoc-members:
:show-inheritance:
<file_sep>spitfire.time package
=====================
Submodules
----------
spitfire.time.integrator module
-------------------------------
.. automodule:: spitfire.time.integrator
:members:
:undoc-members:
:show-inheritance:
spitfire.time.methods module
----------------------------
.. automodule:: spitfire.time.methods
:members:
:undoc-members:
:show-inheritance:
spitfire.time.nonlinear module
------------------------------
.. automodule:: spitfire.time.nonlinear
:members:
:undoc-members:
:show-inheritance:
spitfire.time.stepcontrol module
--------------------------------
.. automodule:: spitfire.time.stepcontrol
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: spitfire.time
:members:
:undoc-members:
:show-inheritance:
<file_sep>import unittest
from spitfire import Library, Dimension
import numpy as np
class TestDimensionExceptions(unittest.TestCase):
def test_check_for_invalid_python_names_hyphen(self):
try:
x = Dimension('x-1', np.linspace(0, 1, 16))
self.assertTrue(False)
except ValueError:
self.assertTrue(True)
def test_check_for_invalid_python_space(self):
try:
x = Dimension('x 1', np.linspace(0, 1, 16))
self.assertTrue(False)
except ValueError:
self.assertTrue(True)
def test_check_for_nonflat_data(self):
try:
x = Dimension('x', np.zeros((4, 2)))
self.assertTrue(False)
except ValueError:
self.assertTrue(True)
def test_check_for_duplicate_data(self):
try:
x = Dimension('x', np.array([0, 1, 1, 2]))
self.assertTrue(False)
except ValueError:
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
#include "combustion_kernels.h"
#include "blas_lapack_kernels.h"
#include <numeric>
namespace griffon
{
void CombustionKernels::chem_rhs_isochoric(const double &rho, const double &cv, const double *e, const double *w,
double *out_rhs) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
out_rhs[0] = 0.;
out_rhs[1] = -griffon::blas::inner_product(nSpec, w, e) / (rho * cv);
const double invRho = 1. / rho;
for (int i = 0; i < nSpec - 1; ++i)
{
out_rhs[2 + i] = w[i] * invRho;
}
}
void CombustionKernels::heat_rhs_isochoric(const double &temperature, const double &rho, const double &cv,
const double &fluidTemperature, const double &surfTemperature,
const double &hConv, const double &epsRad, const double &surfaceAreaOverVolume,
double *out_heatTransferRate) const
{
*out_heatTransferRate = surfaceAreaOverVolume / (rho * cv) * (hConv * (fluidTemperature - temperature) + epsRad * 5.67e-8 * (surfTemperature * surfTemperature * surfTemperature * surfTemperature - temperature * temperature * temperature * temperature));
}
void CombustionKernels::mass_rhs_isochoric(const double *y, const double *energies, const double *inflowEnergies,
const double &rho, const double &inflowRho, const double &pressure,
const double &inflowPressure, const double &cv, const double *inflowY,
const double &tau, double *out_rhs) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
out_rhs[1] = (inflowEnergies[nSpec - 1] - energies[nSpec - 1]) * inflowY[nSpec - 1];
for (int i = 0; i < nSpec - 1; ++i)
{
out_rhs[1] += (inflowEnergies[i] - energies[i]) * inflowY[i];
out_rhs[2 + i] = inflowY[i] - y[i];
}
const double invRho = 1. / rho;
const double invTau = 1. / tau;
out_rhs[0] = (inflowRho - rho) * invTau;
out_rhs[1] /= cv;
for (int i = 1; i < nSpec + 1; ++i)
{
out_rhs[i] *= invTau * inflowRho * invRho;
}
}
void CombustionKernels::chem_jac_isochoric(const double &temperature, const double *y, const double &rho, const double &cv,
const double *cvi, const double &cvsensT, const double *e, const double *w,
const double *wsens, double *out_rhs, double *out_jac) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
// out_primJac is an (n+1) x (n+1) column-major array
// row i col j is i + j * (n+1)
chem_rhs_isochoric(rho, cv, e, w, out_rhs);
const double invRho = 1. / rho;
const double invCv = 1. / cv;
const double invRhoCv = 1. / (rho * cv);
// rho column
out_jac[0] = 0.;
out_jac[1] = -invRhoCv * griffon::blas::inner_product(nSpec, wsens, e) - invRho * out_rhs[1];
for (int i = 0; i < nSpec - 1; ++i)
{
out_jac[2 + i] = invRho * (wsens[i] - invRho * w[i]);
}
// T column
const int firstRow = nSpec + 1;
out_jac[firstRow] = 0.;
out_jac[firstRow + 1] = -invCv * (invRho * (griffon::blas::inner_product(nSpec, &wsens[nSpec + 1], e) + griffon::blas::inner_product(nSpec, w, cvi)) + out_rhs[1] * cvsensT);
for (int i = 0; i < nSpec - 1; ++i)
{
out_jac[firstRow + 2 + i] = invRho * wsens[nSpec + 1 + i];
}
// Yk column
const double cvn = cvi[nSpec - 1];
for (int k = 0; k < nSpec - 1; ++k)
{
const int firstRowSpec = (2 + k) * (nSpec + 1);
out_jac[firstRowSpec] = 0.;
out_jac[firstRowSpec + 1] = -invRhoCv * griffon::blas::inner_product(nSpec, &wsens[(2 + k) * (nSpec + 1)], e) - out_rhs[1] * (cvi[k] - cvn) * invCv;
for (int i = 0; i < nSpec - 1; ++i)
{
out_jac[firstRowSpec + 2 + i] = invRho * wsens[(2 + k) * (nSpec + 1) + i];
}
}
}
void CombustionKernels::mass_jac_isochoric(const double &pressure, const double &inflowPressure, const double &temperature,
const double *y, const double &rho, const double &inflowRho, const double &cv,
const double &cvsensT, const double *cvi, const double *energies,
const double *inflowEnergies, const double &inflowTemperature,
const double *inflowY, const double &tau, double *out_rhs,
double *out_jac) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
// out_primJac is an (n+1) x (n+1) column-major array
// row i col j is i + j * (n+1)
mass_rhs_isochoric(y, energies, inflowEnergies, rho, inflowRho, pressure, inflowPressure, cv, inflowY, tau,
out_rhs);
const double invRho = 1. / rho;
const double invCv = 1. / cv;
const double invTau = 1. / tau;
// rho column
out_jac[0] = -invTau;
for (int i = 0; i < nSpec; ++i)
{
out_jac[1 + i] = -invRho * out_rhs[1 + i];
}
// T column
const int firstRow = nSpec + 1;
out_jac[firstRow] = 0.;
out_jac[firstRow + 1] = -invCv * (invTau * invRho * (inflowRho * griffon::blas::inner_product(nSpec, inflowY, cvi)) + cvsensT * out_rhs[1]);
double *Tcolp1 = &out_jac[firstRow + 2];
for (int i = 0; i < nSpec - 1; ++i)
{
Tcolp1[i] = 0.;
}
// Yk column
const double cvn = cvi[nSpec - 1];
for (int k = 0; k < nSpec - 1; ++k)
{
const int firstRowSpec = (2 + k) * (nSpec + 1);
out_jac[firstRowSpec] = 0.;
out_jac[firstRowSpec + 1] = -invCv * out_rhs[1] * (cvi[k] - cvn);
for (int i = 0; i < nSpec - 1; ++i)
{
out_jac[firstRowSpec + 2 + i] = 0.;
}
out_jac[firstRowSpec + 2 + k] = -invTau * inflowRho / rho;
}
}
void CombustionKernels::heat_jac_isochoric(const double &temperature, const double &rho, const double &cv,
const double &cvsensT, const double *cvi, const double &convectionTemperature,
const double &radiationTemperature, const double &convectionCoefficient,
const double &radiativeEmissivity, const double &surfaceAreaOverVolume,
double *out_heatTransferRate, double *out_heatTransferRateJac) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
heat_rhs_isochoric(temperature, rho, cv, convectionTemperature, radiationTemperature, convectionCoefficient,
radiativeEmissivity, surfaceAreaOverVolume, out_heatTransferRate);
const double invRhoCv = 1. / (rho * cv);
const double invCv = 1. / cv;
// rho column
out_heatTransferRateJac[0] = -*out_heatTransferRate / rho;
// T column
out_heatTransferRateJac[1] = -invCv * cvsensT * *out_heatTransferRate - surfaceAreaOverVolume * invRhoCv * (convectionCoefficient + 4. * radiativeEmissivity * 5.67e-8 * temperature * temperature * temperature);
// Yk column
double *Yksens = &out_heatTransferRateJac[2];
const double cvn = cvi[nSpec - 1];
for (int k = 0; k < nSpec - 1; ++k)
{
Yksens[k] = invCv * *out_heatTransferRate * (cvn - cvi[k]);
}
}
void CombustionKernels::reactor_rhs_isochoric(const double *state, const double &inflowDensity,
const double &inflowTemperature, const double *inflowY, const double &tau,
const double &fluidTemperature, const double &surfTemperature,
const double &hConv, const double &epsRad,
const double &surfaceAreaOverVolume, const int heatTransferOption,
const bool open, double *out_rhs) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
double p;
double cv;
double cvi[nSpec];
double energies[nSpec];
double w[nSpec];
double out_heatTransferRate;
double massRhs[nSpec];
double inflowP;
double inflowEnergies[nSpec];
const double inflowMmw = mixture_molecular_weight(inflowY);
const double density = state[0];
const double temperature = state[1];
double y[nSpec];
extract_y(&state[2], nSpec, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_pressure(density, temperature, mmw, &p);
cv_mix_and_species(temperature, y, mmw, &cv, cvi);
species_energies(temperature, energies);
production_rates(temperature, density, mmw, y, w);
chem_rhs_isochoric(density, cv, energies, w, out_rhs);
if (open)
{
species_energies(inflowTemperature, inflowEnergies);
ideal_gas_pressure(inflowDensity, inflowTemperature, inflowMmw, &inflowP);
mass_rhs_isochoric(y, energies, inflowEnergies, density, inflowDensity, p, inflowP, cv, inflowY, tau, massRhs);
for (int i = 0; i < nSpec + 1; ++i)
{
out_rhs[i] += massRhs[i];
}
}
switch (heatTransferOption)
{
case 0: // adiabatic
break;
case 1: // isothermal
out_rhs[1] = 0.;
break;
case 2: // diathermal
heat_rhs_isochoric(temperature, density, cv, fluidTemperature, surfTemperature, hConv, epsRad,
surfaceAreaOverVolume, &out_heatTransferRate);
out_rhs[1] += out_heatTransferRate;
break;
}
}
void CombustionKernels::reactor_jac_isochoric(const double *state, const double &inflowDensity,
const double &inflowTemperature, const double *inflowY, const double &tau,
const double &fluidTemperature, const double &surfTemperature,
const double &hConv, const double &epsRad,
const double &surfaceAreaOverVolume, const int heatTransferOption,
const bool open, const int rates_sensitivity_option, double *out_rhs,
double *out_jac) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
double p;
double cv;
double cvsensT;
double cvi[nSpec];
double cvisensT[nSpec];
double energies[nSpec];
double w[nSpec];
double wsens[(nSpec + 1) * (nSpec + 1)];
double heatTransferRate;
double heatTransferRateJac[nSpec];
double inflowP;
double inflowEnergies[nSpec];
double massRhs[nSpec];
double massJac[(nSpec + 1) * (nSpec + 1)];
const double inflowMmw = mixture_molecular_weight(inflowY);
const double density = state[0];
const double temperature = state[1];
double y[nSpec];
extract_y(&state[2], nSpec, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_pressure(density, temperature, mmw, &p);
cv_mix_and_species(temperature, y, mmw, &cv, cvi);
cv_sens_T(temperature, y, &cvsensT, cvisensT);
species_energies(temperature, energies);
switch (rates_sensitivity_option)
{
case 1:
prod_rates_sens_no_tbaf(temperature, density, mmw, y, w, wsens);
break;
case 0:
prod_rates_sens_exact(temperature, density, mmw, y, w, wsens);
break;
case 2:
prod_rates_sens_sparse(temperature, density, mmw, y, w, wsens);
break;
}
chem_jac_isochoric(temperature, y, density, cv, cvi, cvsensT, energies, w, wsens, out_rhs, out_jac);
if (open)
{
ideal_gas_pressure(inflowDensity, inflowTemperature, inflowMmw, &inflowP);
species_energies(inflowTemperature, inflowEnergies);
mass_jac_isochoric(p, inflowP, temperature, y, density, inflowDensity, cv, cvsensT, cvi, energies, inflowEnergies,
inflowTemperature, inflowY, tau, massRhs, massJac);
for (int i = 0; i < nSpec + 1; ++i)
{
out_rhs[i] += massRhs[i];
}
for (int i = 0; i < (nSpec + 1) * (nSpec + 1); ++i)
{
out_jac[i] += massJac[i];
}
}
switch (heatTransferOption)
{
case 0: // adiabatic
break;
case 1: // isothermal
for (int k = 0; k < nSpec + 1; ++k)
{
out_jac[k * (nSpec + 1) + 1] = 0.;
}
out_rhs[1] = 0.;
break;
case 2: // diathermal
heat_jac_isochoric(temperature, density, cv, cvsensT, cvi, fluidTemperature, surfTemperature, hConv, epsRad,
surfaceAreaOverVolume, &heatTransferRate, heatTransferRateJac);
out_rhs[1] += heatTransferRate;
for (int k = 0; k < nSpec + 1; ++k)
{
out_jac[k * (nSpec + 1) + 1] += heatTransferRateJac[k];
}
break;
}
}
} // namespace griffon
<file_sep>"""
This module contains thermochemical analysis tools such as property evaluators and chemical explosive mode analysis,
which operate generally on spitfire Library instances from time integration, flamelet tabulation, etc.
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
import numpy as np
import cantera as ct
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.chemistry.library import Library
from scipy.linalg import eig, eigvals
from spitfire.chemistry.ctversion import check as cantera_version_check
def get_ct_solution_array(mechanism=None, library=None):
"""Obtain a Cantera SolutionArray object representative of an arbitrary library
Parameters
----------
mechanism: spitfire.chemistry.mechanism ChemicalMechanismSpec instance
the mechanism
library: a spitfire.chemistry.library Library instance
a library with T, Y, and either density or pressure (pressure is used if both are present)
Returns
-------
solution_array : cantera.SolutionArray instance
a SolutionArray filled with the library data
library_shape : tuple
shape of the original library
"""
if not isinstance(library, Library):
raise TypeError('Input argument "library" to get_ct_solution_array() must be a Library')
if mechanism is None:
if 'mech_spec' in library.extra_attributes:
mechanism = library.extra_attributes['mech_spec']
else:
raise ValueError('Input argument "mechanism" to get_ct_solution_array() is required as a mechanism could not be found at library.extra_attributes["mech_spec"]')
if not isinstance(mechanism, ChemicalMechanismSpec):
raise TypeError('Invalid "mechanism" for get_ct_solution_array(): must be a ChemicalMechanismSpec')
required_strings = ['temperature'] + ['mass fraction ' + s for s in mechanism.species_names]
for required_string in required_strings:
if required_string not in library:
raise ValueError('Library argument to get_ct_solution_array() must contain '
'temperature, all mass fractions, and pressure or density')
if 'density' not in library and 'pressure' not in library:
raise ValueError('Library argument to get_ct_solution_array() must contain '
'temperature, all mass fractions, and pressure or density')
library_shape = library['temperature'].shape
nstates = library['temperature'].size
Y = np.ndarray((nstates, mechanism.n_species))
for i, name in enumerate(mechanism.species_names):
Y[:, i] = library['mass fraction ' + name].ravel()
states = ct.SolutionArray(mechanism.gas, (nstates,))
if 'pressure' in library:
states.TPY = library['temperature'].ravel(), library['pressure'].ravel(), Y
elif 'density' in library:
states.TDY = library['temperature'].ravel(), library['density'].ravel(), Y
return states, library_shape
def compute_specific_enthalpy(mechanism, output_library):
"""Add the total specific enthalpy to a library (Cantera "enthalpy_mass"), named 'enthalpy'
Parameters
----------
mechanism: spitfire.chemistry.mechanism ChemicalMechanismSpec instance
the mechanism
output_library: a spitfire.chemistry.library Library instance
a library with T, Y, and either density or pressure (pressure is used if both are present)
Returns
-------
output_library : cantera.SolutionArray instance
the library with the 'enthalpy' field added
"""
if not isinstance(mechanism, ChemicalMechanismSpec):
raise TypeError('Input argument "mechanism" to explosive_mode_analysis() must be a ChemicalMechanismSpec')
if not isinstance(output_library, Library):
raise TypeError('Input argument "output_library" to explosive_mode_analysis() must be a Library')
ctsol, lib_shape = get_ct_solution_array(mechanism, output_library)
output_library['enthalpy'] = ctsol.enthalpy_mass.reshape(lib_shape)
return output_library
def compute_density(mechanism, output_library):
"""Add the total mass density to a library (Cantera "density"), named 'density'
Parameters
----------
mechanism: spitfire.chemistry.mechanism ChemicalMechanismSpec instance
the mechanism
output_library: a spitfire.chemistry.library Library instance
a library with T, Y, and either density or pressure (pressure is used if both are present)
Returns
-------
output_library : cantera.SolutionArray instance
the library with the 'density' field added
"""
if not isinstance(mechanism, ChemicalMechanismSpec):
raise TypeError('Input argument "mechanism" to explosive_mode_analysis() must be a ChemicalMechanismSpec')
if not isinstance(output_library, Library):
raise TypeError('Input argument "output_library" to explosive_mode_analysis() must be a Library')
ctsol, lib_shape = get_ct_solution_array(mechanism, output_library)
output_library['density'] = ctsol.density.reshape(lib_shape)
return output_library
def compute_pressure(mechanism, output_library):
"""Add the pressure to a library (Cantera "P"), named 'pressure'
Parameters
----------
mechanism: spitfire.chemistry.mechanism ChemicalMechanismSpec instance
the mechanism
output_library: a spitfire.chemistry.library Library instance
a library with T, Y, and either density or pressure (pressure is used if both are present)
Returns
-------
output_library : cantera.SolutionArray instance
the library with the 'pressure' field added
"""
if not isinstance(mechanism, ChemicalMechanismSpec):
raise TypeError('Input argument "mechanism" to explosive_mode_analysis() must be a ChemicalMechanismSpec')
if not isinstance(output_library, Library):
raise TypeError('Input argument "output_library" to explosive_mode_analysis() must be a Library')
ctsol, lib_shape = get_ct_solution_array(mechanism, output_library)
output_library['pressure'] = ctsol.P.reshape(lib_shape)
return output_library
def compute_viscosity(mechanism, output_library):
"""Add the dynamic viscosity to a library (Cantera "viscosity"), named 'viscosity'
Parameters
----------
mechanism: spitfire.chemistry.mechanism ChemicalMechanismSpec instance
the mechanism
output_library: a spitfire.chemistry.library Library instance
a library with T, Y, and either density or pressure (pressure is used if both are present)
Returns
-------
output_library : cantera.SolutionArray instance
the library with the 'viscosity' field added
"""
if not isinstance(mechanism, ChemicalMechanismSpec):
raise TypeError('Input argument "mechanism" to explosive_mode_analysis() must be a ChemicalMechanismSpec')
if not isinstance(output_library, Library):
raise TypeError('Input argument "output_library" to explosive_mode_analysis() must be a Library')
ctsol, lib_shape = get_ct_solution_array(mechanism, output_library)
output_library['viscosity'] = ctsol.viscosity.reshape(lib_shape)
return output_library
def compute_isobaric_specific_heat(mechanism, output_library):
"""Add the constant-pressure specific heat capacity to a library (Cantera "cp_mass"), named 'heat capacity cp'
Parameters
----------
mechanism: spitfire.chemistry.mechanism ChemicalMechanismSpec instance
the mechanism
output_library: a spitfire.chemistry.library Library instance
a library with T, Y, and either density or pressure (pressure is used if both are present)
Returns
-------
output_library : cantera.SolutionArray instance
the library with the 'heat capacity cp' field added
"""
if not isinstance(mechanism, ChemicalMechanismSpec):
raise TypeError('Input argument "mechanism" to explosive_mode_analysis() must be a ChemicalMechanismSpec')
if not isinstance(output_library, Library):
raise TypeError('Input argument "output_library" to explosive_mode_analysis() must be a Library')
ctsol, lib_shape = get_ct_solution_array(mechanism, output_library)
output_library['heat capacity cp'] = ctsol.cp_mass.reshape(lib_shape)
return output_library
def compute_isochoric_specific_heat(mechanism, output_library):
"""Add the constant-volume specific heat capacity to a library (Cantera "cv_mass"), named 'heat capacity cv'
Parameters
----------
mechanism: spitfire.chemistry.mechanism ChemicalMechanismSpec instance
the mechanism
output_library: a spitfire.chemistry.library Library instance
a library with T, Y, and either density or pressure (pressure is used if both are present)
Returns
-------
output_library : cantera.SolutionArray instance
the library with the 'heat capacity cv' field added
"""
if not isinstance(mechanism, ChemicalMechanismSpec):
raise TypeError('Input argument "mechanism" to explosive_mode_analysis() must be a ChemicalMechanismSpec')
if not isinstance(output_library, Library):
raise TypeError('Input argument "output_library" to explosive_mode_analysis() must be a Library')
ctsol, lib_shape = get_ct_solution_array(mechanism, output_library)
output_library['heat capacity cv'] = ctsol.cv_mass.reshape(lib_shape)
return output_library
def explosive_mode_analysis(mechanism,
output_library,
configuration='isobaric',
heat_transfer='adiabatic',
compute_explosion_indices=False,
compute_participation_indices=False,
include_secondary_mode=False):
"""Perform chemical explosive mode analysis across a range of states in a library.
Parameters
----------
mechanism: spitfire.chemistry.mechanism ChemicalMechanismSpec instance
the mechanism
output_library: a spitfire.chemistry.library Library instance
a library with T, Y, and either density or pressure (pressure is used if both are present)
configuration: str
whether to analyze the system as "isobaric" (default) or "isochoric"
heat_transfer: str
whether to analyze the system as "adiabatic" (default) or "isothermal"
compute_explosion_indices: bool
whether or not (default: False) to include explosion index analysis
compute_participation_indices: bool
whether or not (default: False) to include participation index analysis
include_secondary_mode: bool
whether or not (default: False) to include secondary explosive mode analysis
Returns
-------
output_library : cantera.SolutionArray instance
The library with the following fields added (if requested)
- 'cema-lexp1': the primary explosive eigenvalue (always computed)
- 'cema-lexp2': the secondary explosive eigenvalue (default: off)
- 'cema-ei1 [name]': the primary explosion indices for species (name) or temperature (T) (default: off)
- 'cema-ei2 [name]': the secondary explosion indices for species (name) or temperature (T) (default: off)
- 'cema-pi1 [#]': the primary participation indices of each reaction (numbered) (default: off)
- 'cema-pi2 [#]': the secondary participation indices of each reaction (numbered) (default: off)
"""
if not isinstance(mechanism, ChemicalMechanismSpec):
raise TypeError('Input argument "mechanism" to explosive_mode_analysis() must be a ChemicalMechanismSpec')
if not isinstance(output_library, Library):
raise TypeError('Input argument "output_library" to explosive_mode_analysis() must be a Library')
gas = mechanism.gas
griffon = mechanism.griffon
if cantera_version_check('pre', 2, 6, None):
V_stoich = gas.product_stoich_coeffs() - gas.reactant_stoich_coeffs()
else:
V_stoich = gas.product_stoich_coeffs3 - gas.reactant_stoich_coeffs3
ns = gas.n_species
ne = ns if configuration == 'isobaric' else ns + 1
nr = mechanism.n_reactions
Tidx = 0 if configuration == 'isobaric' else 1
cema_Vmod = np.zeros((ne, nr))
cema_Vmod[Tidx + 1:, :] = np.copy(V_stoich[:-1, :])
cema_Vmod[Tidx, :] = (gas.standard_enthalpies_RT * ct.gas_constant * 298.).T.dot(V_stoich)
library_shape = output_library['temperature'].shape
nstates = output_library['temperature'].size
lexp1 = np.zeros(nstates)
if compute_explosion_indices:
ei1_list = np.zeros((ns, nstates))
if compute_participation_indices:
pi1_list = np.zeros((nr, nstates))
if include_secondary_mode:
lexp2 = np.zeros(nstates)
if compute_explosion_indices:
ei2_list = np.zeros((ns, nstates))
if compute_participation_indices:
pi2_list = np.zeros((nr, nstates))
Tflat = output_library['temperature'].ravel()
Yflat = []
for name in mechanism.species_names:
Yflat.append(output_library['mass fraction ' + name].ravel())
if configuration == 'isochoric':
rhoflat = output_library['density'].ravel()
if configuration == 'isobaric':
pflat = output_library['pressure'].ravel()
for i in range(nstates):
# get the state
state = np.zeros(ne)
if configuration == 'isobaric':
p = pflat[i]
state[0] = Tflat[i]
for ispec in range(ns - 1):
state[1 + ispec] = Yflat[ispec][i]
elif configuration == 'isochoric':
state[0] = rhoflat[i]
state[1] = Tflat[i]
for ispec in range(ns - 1):
state[2 + ispec] = Yflat[ispec][i]
# get an appropriate Jacobian
jac = np.zeros(ne * ne)
null = np.zeros(ne)
if configuration == 'isobaric':
if heat_transfer == 'adiabatic' or heat_transfer == 'diathermal':
griffon.reactor_jac_isobaric(state, p, 0, np.ndarray(1), 0, 0, 0, 0,
0, 0, 0, False, 0, 0, null, jac)
jac = jac.reshape((ne, ne), order='F')
elif heat_transfer == 'isothermal':
griffon.reactor_jac_isobaric(state, p, 0, np.ndarray(1), 0, 0, 0, 0,
0, 0, 1, False, 0, 0, null, jac)
jac = jac.reshape((ne, ne), order='F')
elif configuration == 'isochoric':
if heat_transfer == 'adiabatic' or heat_transfer == 'diathermal':
griffon.reactor_jac_isochoric(state, 0, 0, np.ndarray(1),
0, 0, 0, 0, 0, 0, 0, False, 0, null, jac)
jac = jac.reshape((ne, ne), order='F')
elif heat_transfer == 'isothermal':
griffon.reactor_jac_isochoric(state, 0, 0, np.ndarray(1),
0, 0, 0, 0, 0, 0, 1, False, 0, null, jac)
jac = jac.reshape((ne, ne), order='F')
# do cema with the Jacobian
if compute_explosion_indices or compute_participation_indices:
w, vl, vr = eig(jac, left=True, right=True)
else:
w = eigvals(jac)
realparts = np.real(w)
threshold = 1.e-4
realparts[(realparts > -threshold) & (realparts < threshold)] = -np.inf
exp_idx1 = np.argmax(realparts)
real_parts_without_1 = np.delete(realparts, exp_idx1)
exp_idx2 = np.argmax(real_parts_without_1)
lexp1[i] = realparts[exp_idx1]
if include_secondary_mode:
lexp2[i] = realparts[exp_idx2]
if compute_explosion_indices or compute_participation_indices:
exp_rvec1 = vr[:, exp_idx1]
exp_lvec1 = vl[:, exp_idx1]
exp_rvec2 = vr[:, exp_idx2]
exp_lvec2 = vl[:, exp_idx2]
ep_list1 = np.abs(np.real(exp_lvec1) * np.real(exp_rvec1))
ei1_list[:, i] = ep_list1[Tidx:] / np.sum(np.abs(ep_list1))
if include_secondary_mode:
ep_list2 = np.abs(np.real(exp_lvec2) * np.real(exp_rvec2))
ei2_list[:, i] = ep_list2[Tidx:] / (
1. if np.sum(np.abs(ep_list2)) < 1.e-16 else np.sum(np.abs(ep_list2)))
if compute_participation_indices:
if configuration == 'isobaric':
ynm1 = state[1:]
gas.TPY = state[0], pflat[i], np.hstack((ynm1, 1. - sum(ynm1)))
elif configuration == 'isochoric':
ynm1 = state[2:]
gas.TDY = state[1], state[0], np.hstack((ynm1, 1. - sum(ynm1)))
qnet = gas.net_rates_of_progress
pi1 = np.abs(exp_lvec1.dot(cema_Vmod) * qnet)
pi1_list[:, i] = pi1 / np.sum(np.abs(pi1))
if include_secondary_mode:
pi2 = np.abs(exp_lvec2.dot(cema_Vmod) * qnet)
pi2_list[:, i] = pi2 / np.sum(np.abs(pi2))
# insert quantities into the library
output_library['cema-lexp1'] = lexp1.reshape(library_shape)
if compute_explosion_indices:
output_library['cema-ei1 T'] = ei1_list[0].reshape(library_shape)
for ispec in range(ns - 1):
output_library['cema-ei1 ' + mechanism.species_names[ispec]] = ei1_list[1 + ispec].reshape(library_shape)
if compute_participation_indices:
for ireac in range(nr):
output_library['cema-pi1 ' + str(ireac)] = pi1_list[ireac].reshape(library_shape)
if include_secondary_mode:
output_library['cema-lexp2'] = lexp2.reshape(library_shape)
if compute_explosion_indices:
output_library['cema-ei2 T'] = ei2_list[0].reshape(library_shape)
for ispec in range(ns - 1):
output_library['cema-ei2 ' + mechanism.species_names[ispec]] = ei2_list[1 + ispec].reshape(library_shape)
if compute_participation_indices:
for ireac in range(nr):
output_library['cema-pi2 ' + str(ireac)] = pi2_list[ireac].reshape(library_shape)
return output_library
<file_sep>"""
This module contains nonlinear solvers used in time stepping.
At the moment this is simply Newton's method.
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
import numpy as np
from numpy import copy as numpy_copy
from numpy import any, logical_or, isinf, isnan, abs, Inf
from scipy.linalg import norm
def finite_difference_jacobian(residual_func, residual_value, state, offset_rel=1.e-5, offset_abs=1.e-8):
"""
Compute a simple one-sided finite difference approximation to the Jacobian of a residual function.
Parameters
----------
residual_func : callable f(q)->r
residual function of the state vector, r(q)
residual_value : np.array
value of the residual function at the specified state vector
state : np.array
the state vector
offset_rel : float
the relative contribution to the finite difference delta (optional, default: 1e-5)
offset_abs : float
the absolute contribution to the finite difference delta (optional, default: 1e-8)
Returns
-------
j : np.ndarray
the approximate Jacobian matrix
"""
neq = state.size
j = np.ndarray((neq, neq))
for i in range(neq):
state_offset = numpy_copy(state)
offset = offset_rel * np.abs(state[i]) + offset_abs
state_offset[i] += offset
j[:, i] = (residual_func(state_offset) - residual_value) / offset
return j
class SolverOutput(object):
"""Read-only class that holds information about the result of a nonlinear solver.
**Constructor**: build a SolverOutput object, specifying all data here (the object will be read-only)
Parameters
----------
solution : np.ndarray
the solution to the nonlinear system
iter : int
how many nonlinear iterations were needed for convergence
liter : int
how many total linear iterations were needed for convergence
converged : bool
whether or not the solver converged to a solution
slow_convergence : bool
whether or not the solver detected slow convergence
projector_setups : int
the number of times the linear projector was set up (e.g. Jacobian evaluation-factorization)
rhs_at_converged : np.ndarray
the right-hand side of the ODE system at the converged solution
"""
__slots__ = ['solution',
'rhs_at_converged',
'iter',
'liter',
'converged',
'slow_convergence',
'projector_setups']
def __init__(self, **kwargs):
for slot in self.__slots__:
self.__setattr__(slot, kwargs[slot] if slot in kwargs else None)
class NonlinearSolver(object):
"""Base class for nonlinear solvers.
**Constructor**: build a NonlinearSolver object
Parameters
----------
max_nonlinear_iter : int
maximum number of nonlinear iterations to try (default: 20)
slowness_detection_iter : int
how many iterations the solver runs can run without declaring convergence "slow" (default: Inf)
must_converge : bool
whether or not the solver must converge to a solution within max_nonlinear_iter (default: False)
norm_weighting : np.ndarray or float
how the temporal error estimate is weighted in its norm calculation (default: 1)
norm_order : int or np.Inf
the order of the norm used in the temporal error estimate (default: Inf)
raise_naninf : bool
whether or not to check for NaN/Inf values in the solution and residual and raise an exception if found (default: False)
custom_solution_check : callable
a function of the solution that executes custom checks for solution validity (default: None)
setup_projector_in_governor : bool
whether or not the linear projector is set up outside of the solver (default: True)
"""
defaults = {'max_nonlinear_iter': 20,
'slowness_detection_iter': Inf,
'must_converge': False,
'tolerance': 1.e-12,
'norm_weighting': 1.,
'norm_order': Inf,
'raise_naninf': False,
'custom_solution_check': None,
'setup_projector_in_governor': True}
def __init__(self, *args, **kwargs):
for attr in self.defaults:
self.__setattr__(attr, kwargs[attr] if attr in kwargs else self.defaults[attr])
@staticmethod
def _there_are_any_naninf(state):
return any(logical_or(isinf(state), isnan(state)))
def _check_for_naninf(self, variable, message):
if self.raise_naninf:
if self._there_are_any_naninf(variable):
raise ValueError(message)
def _run_custom_solution_check(self, solution, debug_message):
if self.custom_solution_check is not None:
self.custom_solution_check(solution, debug_message)
class SimpleNewtonSolver(NonlinearSolver):
"""Simple Newton solver
**Constructor**: build a SimpleNewtonSolver object
Parameters
----------
evaluate_jacobian_every_iter : bool
whether or not to set up the linear projector on every iteration of Newton's method (default: False)
max_nonlinear_iter : int
maximum number of nonlinear iterations to try (default: 20)
slowness_detection_iter : int
how many iterations the solver runs can run without declaring convergence "slow" (default: Inf)
must_converge : bool
whether or not the solver must converge to a solution within max_nonlinear_iter (default: False)
norm_weighting : np.ndarray or float
how the temporal error estimate is weighted in its norm calculation (default: 1)
norm_order : int or np.Inf
the order of the norm used in the temporal error estimate (default: Inf)
raise_naninf : bool
whether or not to check for NaN/Inf values in the solution and residual and raise an exception if found (default: False)
custom_solution_check : callable
a function of the solution that executes custom checks for solution validity (default: None)
setup_projector_in_governor : bool
whether or not the linear projector is set up outside of the solver (default: True)
"""
def __init__(self, evaluate_jacobian_every_iter=False, *args, **kwargs):
super().__init__(*args, **kwargs)
self._evaluate_jacobian_every_iter = evaluate_jacobian_every_iter
self.setup_projector_in_governor = not self._evaluate_jacobian_every_iter
@property
def evaluate_jacobian_every_iter(self):
return self._evaluate_jacobian_every_iter
@evaluate_jacobian_every_iter.setter
def evaluate_jacobian_every_iter(self, newvalue):
self._evaluate_jacobian_every_iter = newvalue
self.setup_projector_in_governor = not self._evaluate_jacobian_every_iter
def __call__(self,
residual_method,
setup_method,
solve_method,
initial_guess,
initial_rhs):
"""
Solve a nonlinear problem and return the result.
Parameters
----------
residual_method : callable f(x)->(res,rhs)
residual function of the solution that returns both the residual and right-hand side of an ODE,
to use this on a non-ODE problem simply have your residual method return as residual, None
setup_method : callable f(x)
setup function of the solution for the linear projector (e.g. Jacobian eval and factorize)
solve_method : callabe f(x)->b
linear projector solver function of a residual alone,
which returns the state update, linear solver iterations, and whether or not the linear solver converged
initial_guess : np.array
initial guess for the solution
initial_rhs : np.array
ODE right-hand side for the problem at the initial guess (to avoid re-evaluation)
Returns
-------
sol : np.array
solution to the nonlinear problem
"""
solution = numpy_copy(initial_guess)
self._check_for_naninf(solution, 'NaN or Inf detected in Simple Newton Solve: in the initial solution!')
self._run_custom_solution_check(solution, 'In the initial solution')
this_is_a_scalar_problem = True if solution.size == 1 else False
norm_method = abs if this_is_a_scalar_problem else lambda x: norm(x, ord=self.norm_order)
residual, rhs = residual_method(solution, existing_rhs=initial_rhs, evaluate_new_rhs=False)
self._check_for_naninf(residual, 'NaN or Inf detected in Simple Newton Solve: in the initial residual!')
projector_setups = 0
total_linear_iter = 0
for iteration_count in range(1, self.max_nonlinear_iter + 1):
if self.evaluate_jacobian_every_iter:
setup_method(solution)
projector_setups += 1
dstate, this_linear_solver_iter, linear_converged = solve_method(residual)
debug_string = 'On iteration ' + str(iteration_count) + ', linear solve convergence: ' + str(
linear_converged) + ' in ' + str(this_linear_solver_iter) + ' iterations'
self._check_for_naninf(dstate,
'NaN or Inf detected in Simple Newton Solve: solution update check! ' + debug_string)
total_linear_iter += this_linear_solver_iter
solution -= dstate
self._check_for_naninf(solution,
'NaN or Inf detected in Simple Newton Solve: solution check! ' + debug_string)
self._run_custom_solution_check(solution, debug_string)
residual, rhs = residual_method(solution, evaluate_new_rhs=True)
self._check_for_naninf(residual,
'NaN or Inf detected in Simple Newton Solve: solution check! ' + debug_string)
if norm_method(residual * self.norm_weighting) < self.tolerance:
return SolverOutput(slow_convergence=iteration_count > self.slowness_detection_iter,
solution=solution,
rhs_at_converged=rhs,
iter=iteration_count,
liter=total_linear_iter,
converged=True,
projector_setups=projector_setups)
if self.must_converge:
raise ValueError('Simple Newton method did not converge and must_converge=True!')
else:
return SolverOutput(
solution=solution,
rhs_at_converged=rhs,
iter=self.max_nonlinear_iter,
liter=total_linear_iter,
converged=False,
slow_convergence=True,
projector_setups=projector_setups)
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
#include "combustion_kernels.h"
#include "blas_lapack_kernels.h"
#include <cmath>
namespace griffon
{
void CombustionKernels::mole_fractions(const double *y, double *x) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
const auto invMolecularWeights = mechanismData.phaseData.inverseMolecularWeights.data();
const double mmw = mixture_molecular_weight(y);
for (int i = 0; i < nSpec; ++i)
{
x[i] = y[i] * mmw * invMolecularWeights[i];
}
}
double
CombustionKernels::ideal_gas_density(const double &pressure, const double &temperature, const double *y) const
{
double rho;
ideal_gas_density(pressure, temperature, mixture_molecular_weight(y), &rho);
return rho;
}
double
CombustionKernels::ideal_gas_pressure(const double &density, const double &temperature, const double *y) const
{
double p;
ideal_gas_pressure(density, temperature, mixture_molecular_weight(y), &p);
return p;
}
void CombustionKernels::cp_mix_and_species(const double &temperature, const double *y, double *out_cpmix,
double *out_cpspecies) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
const auto invMolecularWeights = mechanismData.phaseData.inverseMolecularWeights.data();
const double t = temperature;
*out_cpmix = 0.;
for (int i = 0; i < nSpec; ++i)
{
const auto polyType = mechanismData.heatCapacityData.types[i];
const auto &c = mechanismData.heatCapacityData.coefficients[i];
const auto &c9 = mechanismData.heatCapacityData.nasa9Coefficients[i];
const double maxT = mechanismData.heatCapacityData.maxTemperatures[i];
const double minT = mechanismData.heatCapacityData.minTemperatures[i];
switch (polyType)
{
case CpType::CONST:
out_cpspecies[i] = invMolecularWeights[i] * c[3];
*out_cpmix += y[i] * out_cpspecies[i];
break;
case CpType::NASA7:
if (t <= c[0] && t >= minT)
{
out_cpspecies[i] = invMolecularWeights[i] * (c[8] + t * (2. * c[9] + t * (6. * c[10] + t * (12. * c[11] + 20. * t * c[12]))));
*out_cpmix += y[i] * out_cpspecies[i];
break;
}
else if (t > c[0] && t <= maxT)
{
out_cpspecies[i] = invMolecularWeights[i] * (c[1] + t * (2. * c[2] + t * (6. * c[3] + t * (12. * c[4] + 20. * t * c[5]))));
*out_cpmix += y[i] * out_cpspecies[i];
break;
}
else if (t < minT)
{
out_cpspecies[i] = invMolecularWeights[i] * (c[8] + minT * (2. * c[9] + minT * (6. * c[10] + minT * (12. * c[11] + 20. * minT * c[12]))));
*out_cpmix += y[i] * out_cpspecies[i];
break;
}
else
{
out_cpspecies[i] = invMolecularWeights[i] * (c[1] + maxT * (2. * c[2] + maxT * (6. * c[3] + maxT * (12. * c[4] + 20. * maxT * c[5]))));
*out_cpmix += y[i] * out_cpspecies[i];
break;
}
case CpType::NASA9:
{
const auto nregions = static_cast<int>(c9[0]);
if(t < minT)
{
const double invminT = 1. / minT;
const auto *a = &(c9[3]);
out_cpspecies[i] = invMolecularWeights[i] * (invminT * (a[1] + invminT * a[0]) + a[2] + minT * (a[3] + minT * (a[4] + minT * (a[5] + minT * a[6]))));
*out_cpmix += y[i] * out_cpspecies[i];
}
else if(t > maxT)
{
const double invmaxT = 1. / maxT;
const auto *a = &(c9[1 + (nregions - 1) * 11 + 2]);
out_cpspecies[i] = invMolecularWeights[i] * (invmaxT * (a[1] + invmaxT * a[0]) + a[2] + maxT * (a[3] + maxT * (a[4] + maxT * (a[5] + maxT * a[6]))));
*out_cpmix += y[i] * out_cpspecies[i];
}
else
{
const double invT = 1. / t;
for(int k=0; k<nregions; ++k)
{
const int region_start_idx = 1 + k * 11;
if(t >= c9[region_start_idx] && t < c9[region_start_idx + 1])
{
const auto *a = &(c9[region_start_idx + 2]);
out_cpspecies[i] = invMolecularWeights[i] * (invT * (a[1] + invT * a[0]) + a[2] + t * (a[3] + t * (a[4] + t * (a[5] + t * a[6]))));
*out_cpmix += y[i] * out_cpspecies[i];
break;
}
}
}
break;
}
default:
{
break;
}
}
}
}
double
CombustionKernels::cp_mix(const double &temperature, const double *y) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
double cpmix = 0.;
double cpspecies[nSpec];
cp_mix_and_species(temperature, y, &cpmix, cpspecies);
return cpmix;
}
void CombustionKernels::species_cp(const double &temperature, double *out_cpspecies) const
{
double garbage;
cp_mix_and_species(temperature, out_cpspecies, &garbage, out_cpspecies);
}
double
CombustionKernels::cv_mix(const double &temperature, const double *y) const
{
const double gasConstant = mechanismData.phaseData.Ru;
return cp_mix(temperature, y) - gasConstant / mixture_molecular_weight(y);
}
void CombustionKernels::species_cv(const double &temperature, double *out_cvspecies) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
const auto invMolecularWeights = mechanismData.phaseData.inverseMolecularWeights.data();
const double gasConstant = mechanismData.phaseData.Ru;
double null;
cp_mix_and_species(temperature, out_cvspecies, &null, out_cvspecies);
for (int i = 0; i < nSpec; ++i)
{
out_cvspecies[i] -= gasConstant * invMolecularWeights[i];
}
}
void CombustionKernels::cv_mix_and_species(const double &temperature, const double *y, const double &mmw,
double *out_cvmix, double *out_cvspecies) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
const auto invMolecularWeights = mechanismData.phaseData.inverseMolecularWeights.data();
const double gasConstant = mechanismData.phaseData.Ru;
cp_mix_and_species(temperature, y, out_cvmix, out_cvspecies);
*out_cvmix -= gasConstant / mmw;
for (int i = 0; i < nSpec; ++i)
{
out_cvspecies[i] -= gasConstant * invMolecularWeights[i];
}
}
void CombustionKernels::cp_sens_T(const double &temperature, const double *y, double *out_cpmixsens,
double *out_cpspeciessens) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
const auto invMolecularWeights = mechanismData.phaseData.inverseMolecularWeights.data();
const double t = temperature;
*out_cpmixsens = 0.;
for (int i = 0; i < nSpec; ++i)
{
const auto polyType = mechanismData.heatCapacityData.types[i];
const auto &c = mechanismData.heatCapacityData.coefficients[i];
const auto &c9 = mechanismData.heatCapacityData.nasa9Coefficients[i];
const double minT = mechanismData.heatCapacityData.minTemperatures[i];
const double maxT = mechanismData.heatCapacityData.maxTemperatures[i];
switch (polyType)
{
case CpType::CONST:
out_cpspeciessens[i] = 0.;
*out_cpmixsens = 0.;
break;
case CpType::NASA7:
if (t <= c[0] && t >= minT)
{
out_cpspeciessens[i] = invMolecularWeights[i] * ((2. * c[9] + t * (12. * c[10] + t * (36. * c[11] + 80. * t * c[12]))));
*out_cpmixsens += y[i] * out_cpspeciessens[i];
break;
}
else if (t > c[0] && t <= maxT)
{
out_cpspeciessens[i] = invMolecularWeights[i] * ((2. * c[2] + t * (12. * c[3] + t * (36. * c[4] + 80. * t * c[5]))));
*out_cpmixsens += y[i] * out_cpspeciessens[i];
break;
}
else if (t < minT)
{
out_cpspeciessens[i] = 0.;
*out_cpmixsens += 0.;
break;
}
else
{
out_cpspeciessens[i] = 0.;
*out_cpmixsens += 0.;
break;
}
case CpType::NASA9:
{
const auto nregions = static_cast<int>(c9[0]);
if(t < minT || t > maxT)
{
out_cpspeciessens[i] = 0.;
*out_cpmixsens += 0.;
}
else
{
const double invT = 1. / t;
for(int k=0; k<nregions; ++k)
{
const int region_start_idx = 1 + k * 11;
if(t >= c9[region_start_idx] && t < c9[region_start_idx + 1])
{
const auto *a = &(c9[region_start_idx + 2]);
out_cpspeciessens[i] = invMolecularWeights[i] * (-invT * invT * (a[1] + invT * 2.0 * a[0]) + a[3] + t * (2.0 * a[4] + t * (3.0 * a[5] + t * 4.0 * a[6])));
*out_cpmixsens += y[i] * out_cpspeciessens[i];
break;
}
}
}
break;
}
default:
{
break;
}
}
}
}
void CombustionKernels::species_enthalpies(const double &temperature, double *out_enthalpies) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
const auto invMolecularWeights = mechanismData.phaseData.inverseMolecularWeights.data();
const double temp = temperature;
for (int i = 0; i < nSpec; ++i)
{
const auto polyType = mechanismData.heatCapacityData.types[i];
const auto &c = mechanismData.heatCapacityData.coefficients[i];
const auto &c9 = mechanismData.heatCapacityData.nasa9Coefficients[i];
const double minT = mechanismData.heatCapacityData.minTemperatures[i];
const double maxT = mechanismData.heatCapacityData.maxTemperatures[i];
switch (polyType)
{
case CpType::CONST:
out_enthalpies[i] = invMolecularWeights[i] * (c[1] + c[3] * (temp - c[0]));
break;
case CpType::NASA7:
if (temp <= c[0] && temp >= minT)
{
out_enthalpies[i] =
invMolecularWeights[i] * (c[13] + temp * (c[8] + temp * (c[9] + temp * (2. * c[10] + temp * (3. * c[11] + temp * 4. * c[12])))));
break;
}
else if (temp > c[0] && temp <= maxT)
{
out_enthalpies[i] = invMolecularWeights[i] * (c[6] + temp * (c[1] + temp * (c[2] + temp * (2. * c[3] + temp * (3. * c[4] + temp * 4. * c[5])))));
break;
}
else if (temp < minT)
{
out_enthalpies[i] =
invMolecularWeights[i] * (c[13] + c[8] * temp + minT * (2. * c[9] * temp + minT * (3. * 2. * c[10] * temp - c[9] + minT * (4. * 3. * c[11] * temp - 2. * 2. * c[10] + minT * (5. * 4. * c[12] * temp - 3. * 3. * c[11] + minT * -4. * 4. * c[12])))));
break;
}
else
{
out_enthalpies[i] =
invMolecularWeights[i] * (c[6] + c[1] * temp + maxT * (2. * c[2] * temp + maxT * (3. * 2. * c[3] * temp - c[2] + maxT * (4. * 3. * c[4] * temp - 2. * 2. * c[3] + maxT * (5. * 4. * c[5] * temp - 3. * 3. * c[4] + maxT * -4. * 4. * c[5])))));
break;
}
case CpType::NASA9:
{
const auto nregions = static_cast<int>(c9[0]);
if(temp < minT)
{
const double invT = 1. / minT;
const double logT = std::log(minT);
const int region_start_idx = 1;
const auto *a = &(c9[region_start_idx + 2]);
const double hmin = invMolecularWeights[i] * minT * (invT * (a[7] + logT * a[1] - a[0] * invT) + a[2] + minT * (0.5 * a[3] + minT * (0.3333333333333333 * a[4] + minT * (0.25 * a[5] + minT * 0.2 * a[6]))));
const double cpmin = invMolecularWeights[i] * (invT * (a[1] + invT * a[0]) + a[2] + minT * (a[3] + minT * (a[4] + minT * (a[5] + minT * a[6]))));
out_enthalpies[i] = hmin + cpmin * (temp - minT);
}
else if(temp > maxT)
{
const double invT = 1. / maxT;
const double logT = std::log(maxT);
const int region_start_idx = 1 + (nregions - 1) * 11;
const auto *a = &(c9[region_start_idx + 2]);
const double hmax = invMolecularWeights[i] * maxT * (invT * (a[7] + logT * a[1] - a[0] * invT) + a[2] + maxT * (0.5 * a[3] + maxT * (0.3333333333333333 * a[4] + maxT * (0.25 * a[5] + maxT * 0.2 * a[6]))));
const double cpmax = invMolecularWeights[i] * (invT * (a[1] + invT * a[0]) + a[2] + maxT * (a[3] + maxT * (a[4] + maxT * (a[5] + maxT * a[6]))));
out_enthalpies[i] = hmax + cpmax * (temp - maxT);
}
else
{
const double invT = 1. / temp;
const double logT = std::log(temp);
for(int k=0; k<nregions; ++k)
{
const int region_start_idx = 1 + k * 11;
if(temp >= c9[region_start_idx] && temp < c9[region_start_idx + 1])
{
const auto *a = &(c9[region_start_idx + 2]);
out_enthalpies[i] = invMolecularWeights[i] * temp * (invT * (a[7] + logT * a[1] - a[0] * invT) + a[2] + temp * (0.5 * a[3] + temp * (0.3333333333333333 * a[4] + temp * (0.25 * a[5] + temp * 0.2 * a[6]))));
break;
}
}
}
break;
}
default:
{
break;
}
}
}
}
void CombustionKernels::species_energies(const double &temperature, double *out_energies) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
const auto invMolecularWeights = mechanismData.phaseData.inverseMolecularWeights.data();
const double gasConstant = mechanismData.phaseData.Ru;
species_enthalpies(temperature, out_energies);
const double RT = gasConstant * temperature;
for (int i = 0; i < nSpec; ++i)
{
out_energies[i] -= RT * invMolecularWeights[i];
}
}
double
CombustionKernels::enthalpy_mix(const double &temperature, const double *y) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
double hi[nSpec];
species_enthalpies(temperature, hi);
return blas::inner_product(nSpec, hi, y);
}
double
CombustionKernels::energy_mix(const double &temperature, const double *y) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
double ei[nSpec];
species_energies(temperature, ei);
return blas::inner_product(nSpec, ei, y);
}
} // namespace griffon
<file_sep>Tabulation API Example: Presumed PDF SLFM Tables
================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - Building presumed PDF adiabatic and nonadiabatic SFLM
libraries for turbulent flows - Using Spitfire’s wrapper around the
Python interface of
```TabProps`` <https://multiscale.utah.edu/software/>`__ to easily
extend tables with clipped Gaussian and Beta PDFs
Tabulated chemistry models can often be split into two pieces: a
*reaction* model and a *mixing* model. The reaction model describes
small scale laminar flame structure, for instance equilibrium (fast
chemistry) or diffusion-reaction (SLFM), possibly perturbed by radiative
heat losses. A mixing model is unnecessary in a CFD simulation when the
flow is laminar or when all scales of turbulence are resolved as in
direct numerical simulation (DNS). In Reynolds-averaged Navier-Stokes
(RANS) or large eddy simulation (LES), however, small scales are modeled
instead of being resolved by the mesh. Here a mixing model is necessary
to account for turbulence-chemistry interaction on subgrid scales.
In RANS and LES, typically two statistical moments of conserved scalars
are transported on the mesh and the mixing model accounts for
unresolved, or subgrid, heterogeneity. A mixing model accomplishes this
by describing the statistical distribution of the subgrid scalar field.
Spitfire and the `Python interface of the ``TabProps``
code <https://multiscale.utah.edu/software/>`__ can be combined to build
reaction models and then incorporate presumed PDF mixing models.
The Reaction Models
-------------------
First we’ll build the reaction models for an n-heptane/air system
following prior demonstrations.
.. code:: ipython3
from spitfire import (ChemicalMechanismSpec,
Library,
FlameletSpec,
build_adiabatic_slfm_library,
build_nonadiabatic_defect_transient_slfm_library)
import matplotlib.pyplot as plt
import numpy as np
mech = ChemicalMechanismSpec(cantera_xml='heptane-liu-hewson-chen-pitsch-highT.xml',
group_name='gas')
pressure = 101325.
air = mech.stream(stp_air=True)
fuel = mech.stream('TPY', (372., pressure, 'NXC7H16:1'))
flamelet_specs = FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,
fuel_stream=fuel,
grid_points=34)
l_ad = build_adiabatic_slfm_library(flamelet_specs,
diss_rate_values=np.logspace(-1, 2, 8),
diss_rate_ref='stoichiometric',
verbose=False)
l_na = build_nonadiabatic_defect_transient_slfm_library(flamelet_specs,
diss_rate_values=np.logspace(-1, 2, 8),
diss_rate_ref='stoichiometric',
n_defect_st=16,
integration_args={'transient_tolerance': 1.e-12})
# note here: the transient_tolerance is specified to avoid seeing "failure" messages,
# but in absence of this flag, Spitfire will automatically iterate after failures to obtain a solution
.. parsed-literal::
----------------------------------------------------------------------------------
building nonadiabatic (defect) SLFM library
----------------------------------------------------------------------------------
- mechanism: heptane-liu-hewson-chen-pitsch-highT.xml
- 38 species, 105 reactions
- stoichiometric mixture fraction: 0.062
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
building adiabatic SLFM library
----------------------------------------------------------------------------------
- mechanism: heptane-liu-hewson-chen-pitsch-highT.xml
- 38 species, 105 reactions
- stoichiometric mixture fraction: 0.062
----------------------------------------------------------------------------------
1/ 8 (chi_stoich = 1.0e-01 1/s) converged in 0.66 s, T_max = 2122.1
2/ 8 (chi_stoich = 2.7e-01 1/s) converged in 0.01 s, T_max = 2089.8
3/ 8 (chi_stoich = 7.2e-01 1/s) converged in 0.01 s, T_max = 2055.4
4/ 8 (chi_stoich = 1.9e+00 1/s) converged in 0.06 s, T_max = 2027.5
5/ 8 (chi_stoich = 5.2e+00 1/s) converged in 0.07 s, T_max = 1984.7
6/ 8 (chi_stoich = 1.4e+01 1/s) converged in 0.08 s, T_max = 1924.2
7/ 8 (chi_stoich = 3.7e+01 1/s) converged in 0.07 s, T_max = 1840.6
8/ 8 (chi_stoich = 1.0e+02 1/s) converged in 0.10 s, T_max = 1695.0
----------------------------------------------------------------------------------
library built in 1.19 s
----------------------------------------------------------------------------------
expanding (transient) enthalpy defect dimension ...
chi_st = 1.0e-01 1/s converged in 7.03 s
chi_st = 2.7e-01 1/s converged in 6.60 s
chi_st = 7.2e-01 1/s converged in 6.45 s
chi_st = 1.9e+00 1/s converged in 6.05 s
chi_st = 5.2e+00 1/s converged in 5.96 s
chi_st = 1.4e+01 1/s converged in 6.52 s
chi_st = 3.7e+01 1/s converged in 7.72 s
chi_st = 1.0e+02 1/s converged in 6.91 s
----------------------------------------------------------------------------------
enthalpy defect dimension expanded in 53.25 s
----------------------------------------------------------------------------------
Structuring enthalpy defect dimension ...
Initializing ... Done.
Interpolating onto structured grid ...
Progress: 0%--10%--20%--30%--40%--50%--60%--70%--80%--100%
Structured enthalpy defect dimension built in 3.28 s
----------------------------------------------------------------------------------
library built in 57.74 s
----------------------------------------------------------------------------------
Tabulated Properties
--------------------
Running a CFD calculation requires fluid properties such as the
viscosity, heat capacity, and enthalpy. These are computed on the
laminar reaction model and are then integrated with the presumed PDF. So
before applying the presumed PDF mixing model we make new libraries with
just a few properties likely necessary for the simulation. We typically
don’t need to tabulate the entire set of mass fractions, so we’ll remove
them to save time.
.. code:: ipython3
from spitfire import get_ct_solution_array
import copy
def tabulate_properties(TY_lib):
ct_sol, lib_shape = get_ct_solution_array(mech, TY_lib)
prop_lib = copy.copy(TY_lib)
prop_lib.remove(*prop_lib.props)
prop_lib['temperature'] = ct_sol.T.reshape(lib_shape)
prop_lib['viscosity'] = ct_sol.viscosity.reshape(lib_shape)
prop_lib['enthalpy'] = ct_sol.enthalpy_mass.reshape(lib_shape)
prop_lib['heat_capacity_cp'] = ct_sol.cp_mass.reshape(lib_shape)
return prop_lib
prop_ad = tabulate_properties(l_ad)
prop_na = tabulate_properties(l_na)
Presumed PDFs
-------------
First, we’ll use TabProps to evaluate the clipped Gaussian and
:math:`\beta` PDFs for some represenative means and variances. Note the
major differences between the PDF types at higher variances and near the
boundaries. The poor behavior of the :math:`\beta` PDF in these regimes
makes it substantially harder to integrate than the clipped Gaussian.
.. code:: ipython3
from pytabprops import ClippedGaussMixMdl, BetaMixMdl
ztest = np.linspace(0, 1, 1000)
cg = ClippedGaussMixMdl(201, 201, False)
bp = BetaMixMdl()
zmean = 0.38
for i, zsvar in enumerate([0.05, 0.1, 0.2, 0.25, 0.28]):
bp.set_mean(zmean)
bp.set_scaled_variance(zsvar)
plt.plot(ztest, bp.get_pdf(ztest), 'b--', label='$\\beta-PDF$' if i == 0 else None)
cg.set_mean(zmean)
cg.set_scaled_variance(zsvar)
plt.plot(ztest, cg.get_pdf(ztest), 'g-', label='ClipGauss' if i == 0 else None)
plt.title(f'mean {zmean:.2f} w/multiple variances')
plt.xlabel('input')
plt.ylabel('PDF')
plt.grid()
plt.legend()
plt.show()
zsvar = 0.12
for i, zmean in enumerate([0.15, 0.3, 0.5]):
bp.set_mean(zmean)
bp.set_scaled_variance(zsvar)
plt.plot(ztest, bp.get_pdf(ztest), 'b--', label='$\\beta-PDF$' if i == 0 else None)
cg.set_mean(zmean)
cg.set_scaled_variance(zsvar)
plt.plot(ztest, cg.get_pdf(ztest), 'g-', label='ClipGauss' if i == 0 else None)
plt.title(f'scaled variance {zsvar:.2f} w/multiple means')
plt.xlabel('input')
plt.ylabel('PDF')
plt.grid()
plt.legend()
plt.show()
.. image:: tabulation_api_presumed_pdf_files/tabulation_api_presumed_pdf_5_0.png
.. image:: tabulation_api_presumed_pdf_files/tabulation_api_presumed_pdf_5_1.png
Incorporating the Mixing Model: Clipped Gaussian and :math:`\beta` PDFs
-----------------------------------------------------------------------
Spitfire provides the ``apply_mixing_model`` which takes an existing
``Library``, for instance those computed above, and incorporates subgrid
variation for all dimensions and adds the (default) suffix ``_mean``.
Spitfire provides two optimized PDF integrators from TabProps, the
clipped Gaussian (``'ClipGauss'``) and the beta PDF (``'Beta'``). These
PDFs and their integrals are challenging to implement and TabProps’
implementation is excellent. In addition these, Spitfire allows you to
“roll your own” PDF integrator, a feature to be shown in following
demonstrations.
.. code:: ipython3
from spitfire import apply_mixing_model, PDFSpec
scaled_variance_values = np.array([0, 0.001, 0.01, 0.1, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0])
mixing_spec = {'mixture_fraction': PDFSpec(pdf='ClipGauss', scaled_variance_values=scaled_variance_values)}
t_cg_prop_ad = apply_mixing_model(prop_ad, mixing_spec, verbose=True)
t_cg_prop_na = apply_mixing_model(prop_na, mixing_spec, verbose=True)
.. parsed-literal::
scaled_scalar_variance_mean: computing 10880 integrals... completed in 1.7 seconds, average = 6231 integrals/s.
scaled_scalar_variance_mean: computing 174080 integrals... completed in 26.3 seconds, average = 6609 integrals/s.
Now take a quick look at the tables. Input dimensions have been suffixed
with ``_mean`` and the scalar variance (its scaled form that varies
between 0 and 1) is incorporated as the final dimension. Futher, the
``extra_attributes`` dictionary that holds library metadata saves the
``mixing_spec`` dictionary for later reference.
.. code:: ipython3
print(t_cg_prop_ad)
print(t_cg_prop_na)
.. parsed-literal::
Spitfire Library with 3 dimensions and 4 properties
------------------------------------------
1. Dimension "mixture_fraction_mean" spanning [0.0, 1.0] with 34 points
2. Dimension "dissipation_rate_stoich_mean" spanning [0.1, 100.0] with 8 points
3. Dimension "scaled_scalar_variance_mean" spanning [0.0, 1.0] with 10 points
------------------------------------------
temperature , min = 300.0 max = 2122.0969552261395
viscosity , min = 1.2370131775920866e-05 max = 6.906467776682997e-05
enthalpy , min = -1739935.6849118916 max = 1901.8191601112546
heat_capacity_cp , min = 1011.3329912202539 max = 2422.2079033534937
Extra attributes: {'mech_spec': <spitfire.chemistry.mechanism.ChemicalMechanismSpec object at 0x7fb4465fe050>, 'mixing_spec': {'mixture_fraction': <spitfire.chemistry.tabulation.PDFSpec object at 0x7fb459b7a350>, 'dissipation_rate_stoich': <spitfire.chemistry.tabulation.PDFSpec object at 0x7fb459b7a2d0>}}
------------------------------------------
Spitfire Library with 4 dimensions and 4 properties
------------------------------------------
1. Dimension "mixture_fraction_mean" spanning [0.0, 1.0] with 34 points
2. Dimension "dissipation_rate_stoich_mean" spanning [0.1, 100.0] with 8 points
3. Dimension "enthalpy_defect_stoich_mean" spanning [-2140792.9007149865, 0.0] with 16 points
4. Dimension "scaled_scalar_variance_mean" spanning [0.0, 1.0] with 10 points
------------------------------------------
temperature , min = 299.99999999999994 max = 2122.0969552261395
viscosity , min = 1.2370131775920852e-05 max = 6.906467776682997e-05
enthalpy , min = -2521386.931029486 max = 1901.8191601113012
heat_capacity_cp , min = 1011.3329912202539 max = 2422.2079033534937
Extra attributes: {'mech_spec': <spitfire.chemistry.mechanism.ChemicalMechanismSpec object at 0x7fb45ebb4110>, 'mixing_spec': {'mixture_fraction': <spitfire.chemistry.tabulation.PDFSpec object at 0x7fb459b7a350>, 'dissipation_rate_stoich': <spitfire.chemistry.tabulation.PDFSpec object at 0x7fb459e46d90>, 'enthalpy_defect_stoich': <spitfire.chemistry.tabulation.PDFSpec object at 0x7fb459e46d50>}}
------------------------------------------
.. code:: ipython3
from mpl_toolkits.mplot3d import axes3d
from matplotlib.colors import Normalize
To finish things off we can show some simple visualiations of the data.
.. code:: ipython3
fig = plt.figure()
ax = fig.gca(projection='3d')
z = np.squeeze(t_cg_prop_ad.mixture_fraction_mean_grid[:, :, 0])
x = np.squeeze(np.log10(t_cg_prop_ad.dissipation_rate_stoich_mean_grid[:, :, 0]))
v_list = t_cg_prop_ad.scaled_scalar_variance_mean_values
for idx in [7, 6, 5, 4, 0]:
p = ax.contourf(z, x, np.squeeze(t_cg_prop_ad['temperature'][:, :, idx]),
offset=v_list[idx],
cmap='inferno',
norm=Normalize(300, 2200))
plt.colorbar(p)
ax.view_init(elev=14, azim=-120)
ax.set_zlim([0, 1])
ax.set_xlabel('mixture fraction')
ax.set_ylabel('log dissipation rate')
ax.set_zlabel('scaled scalar variance')
ax.set_title('mean T (K)')
plt.show()
.. image:: tabulation_api_presumed_pdf_files/tabulation_api_presumed_pdf_13_0.png
.. code:: ipython3
j = 0
chi = t_cg_prop_ad.dissipation_rate_stoich_mean_values[j]
for i in range(0, t_cg_prop_ad.scaled_scalar_variance_mean_npts, 3):
svar = t_cg_prop_ad.scaled_scalar_variance_mean_values[i]
plt.plot(t_cg_prop_ad.mixture_fraction_mean_values, np.squeeze(t_cg_prop_ad['temperature'][:, j, i]),
'-',
label='$\\overline{\sigma_{z,s}}=$'+f'{svar}'+', $\\overline{\\chi_{\\rm st}}=$'+f'{chi:.1f} Hz')
j = 3
chi = t_cg_prop_ad.dissipation_rate_stoich_mean_values[j]
for i in range(0, t_cg_prop_ad.scaled_scalar_variance_mean_npts, 3):
svar = t_cg_prop_ad.scaled_scalar_variance_mean_values[i]
plt.plot(t_cg_prop_ad.mixture_fraction_mean_values, np.squeeze(t_cg_prop_ad['temperature'][:, j, i]),
'--',
label='$\\overline{\sigma_{z,s}}=$'+f'{svar}'+', $\\overline{\\chi_{\\rm st}}=$'+f'{chi:.1f} Hz')
j = 7
chi = t_cg_prop_ad.dissipation_rate_stoich_mean_values[j]
for i in range(0, t_cg_prop_ad.scaled_scalar_variance_mean_npts, 3):
svar = t_cg_prop_ad.scaled_scalar_variance_mean_values[i]
plt.plot(t_cg_prop_ad.mixture_fraction_mean_values, np.squeeze(t_cg_prop_ad['temperature'][:, j, i]),
'-.',
label='$\\overline{\sigma_{z,s}}=$'+f'{svar}'+', $\\overline{\\chi_{\\rm st}}=$'+f'{chi:.1f} Hz')
plt.xlabel('mean mixture fraction')
plt.ylabel('mean T (K)')
plt.title('filtered temperature')
plt.grid()
plt.legend(bbox_to_anchor=(1, 1), loc='upper left', ncol=3)
plt.show()
.. image:: tabulation_api_presumed_pdf_files/tabulation_api_presumed_pdf_14_0.png
<file_sep>"""
This module facilitates loading chemical reaction mechanisms in Cantera format and mixing streams in useful ways.
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
import cantera as ct
from numpy import sum, array, abs
from spitfire.griffon.griffon import PyCombustionKernels
from spitfire.chemistry.ctversion import check as cantera_version_check
class CanteraLoadError(Exception):
def __init__(self, mech_file_path, group_name, error):
super().__init__(f'Cantera failed to build a Solution object for the given XML and group name. '
f'YAML/CTI/XML path provided: {mech_file_path}, '
f'group name provided: {group_name}, '
f'Error: {error}')
class _CanteraWrapper(object):
def __init__(self, mech_file_path, group_name, solution=None):
self._mech_file_path = mech_file_path if mech_file_path is not None else 'cantera-input-not-given'
self._group_name = group_name if group_name is not None else 'cantera-group-not-given'
if solution is None:
try:
self._solution = ct.Solution(self._mech_file_path, self._group_name)
except Exception as error:
raise CanteraLoadError(mech_file_path, group_name, error)
else:
self._solution = solution
@property
def mech_file_path(self):
return self._mech_file_path
@property
def group_name(self):
return self._group_name
@property
def solution(self):
return self._solution
class ChemicalMechanismSpec(object):
"""A class that loads chemical mechanisms and mixes streams.
This class facilitates some simple way of specifying the fuel and oxidizer streams for flamelets
and of blending these streams to make mixtures for zero-dimensional simulations.
**Constructor**: specify a chemical mechanism file in cantera XML format
Parameters
----------
cantera_input : str
a cantera YAML/XML/CTI file describing the thermochemistry and (optionally) transport properties
group_name : str
the phase to use (e.g. a phase with transport properties vs without, if such a split exists in the XML file)
cantera_solution: ct.Solution
a ct.Solution object to use directly (optional, if specified the xml and group name are ignored if given)
"""
def __init__(self, cantera_input=None, group_name=None, cantera_solution=None, cantera_xml=None):
cantera_input = cantera_input
if cantera_xml is not None:
cantera_input = cantera_input if cantera_input is not None else cantera_xml
print('Deprecation warning: the "cantera_xml" input argument to ChemicalMechanismSpec is deprecated and will be removed.\nUse the "cantera_input" argument instead.')
if cantera_solution is None:
self._cantera_wrapper = _CanteraWrapper(cantera_input, group_name)
else:
self._cantera_wrapper = _CanteraWrapper(None, None, cantera_solution)
self._mech_data = dict()
self._mech_data['ref_pressure'] = None
self._mech_data['ref_temperature'] = None
self._mech_data['elements'] = list()
self._mech_data['species'] = dict()
self._mech_data['reactions'] = list()
self._mech_data['transport-model'] = None
self._griffon = PyCombustionKernels()
self._populate_griffon_mechanism_data(*self._extract_cantera_mechanism_data(self._cantera_wrapper.solution))
@property
def mech_data(self):
return self._mech_data
def __getstate__(self):
return dict({'mech_data': self._mech_data})
def __setstate__(self, state):
mech_data = state['mech_data']
self.__init__(cantera_solution=ChemicalMechanismSpec._build_cantera_solution(mech_data))
@classmethod
def from_solution(cls, solution: ct.Solution):
"""Construct a ChemicalMechanismSpec directly from a cantera solution"""
return ChemicalMechanismSpec(cantera_solution=solution)
def _populate_griffon_mechanism_data(self,
ct_element_mw_map,
elem_list,
ref_temperature,
ref_pressure,
spec_name_list,
spec_dict,
reac_list,
transport_model):
self._griffon.mechanism_set_ref_pressure(ref_pressure)
self._mech_data['ref_pressure'] = ref_pressure
self._griffon.mechanism_set_ref_temperature(ref_temperature)
self._mech_data['ref_temperature'] = ref_temperature
gas_constant = ct.gas_constant
self._griffon.mechanism_set_gas_constant(gas_constant)
self._mech_data['gas_constant'] = gas_constant
self._griffon.mechanism_set_element_mw_map(ct_element_mw_map)
self._mech_data['element_mw_map'] = ct_element_mw_map
for e in elem_list:
self._griffon.mechanism_add_element(e)
self._mech_data['elements'].append(e)
for s in spec_name_list:
self._griffon.mechanism_add_species(s, spec_dict[s]['atoms'])
self._mech_data['species'][s] = dict()
self._mech_data['species'][s]['atom_map'] = spec_dict[s]['atoms']
self._griffon.mechanism_resize_heat_capacity_data()
for s in spec_dict:
cp = spec_dict[s]['heat-capacity']
if cp['type'] == 'constant':
self._griffon.mechanism_add_const_cp(s, cp['Tmin'], cp['Tmax'], cp['T0'], cp['h0'], cp['s0'], cp['cp'])
self._mech_data['species'][s]['cp'] = (
'constant', cp['Tmin'], cp['Tmax'], cp['T0'], cp['h0'], cp['s0'], cp['cp'])
elif cp['type'] == 'NASA7':
self._griffon.mechanism_add_nasa7_cp(s, cp['Tmin'], cp['Tmid'], cp['Tmax'], cp['low-coeffs'].tolist(),
cp['high-coeffs'].tolist())
self._mech_data['species'][s]['cp'] = (
'NASA7', cp['Tmin'], cp['Tmid'], cp['Tmax'], cp['low-coeffs'].tolist(), cp['high-coeffs'].tolist())
elif cp['type'] == 'NASA9':
self._griffon.mechanism_add_nasa9_cp(s, cp['Tmin'], cp['Tmax'], cp['coeffs'].tolist())
self._mech_data['species'][s]['cp'] = ('NASA9', cp['Tmin'], cp['Tmax'], cp['coeffs'].tolist())
if transport_model is not None and 'transport-data' in spec_dict[s]:
self._mech_data['species'][s]['transport-data'] = dict(spec_dict[s]['transport-data'])
self._mech_data['transport-model'] = transport_model
add_smpl = self._griffon.mechanism_add_reaction_simple
add_3bdy = self._griffon.mechanism_add_reaction_three_body
add_Lind = self._griffon.mechanism_add_reaction_Lindemann
add_Troe = self._griffon.mechanism_add_reaction_Troe
add_smpl_ord = self._griffon.mechanism_add_reaction_simple_with_special_orders
add_3bdy_ord = self._griffon.mechanism_add_reaction_three_body_with_special_orders
add_Lind_ord = self._griffon.mechanism_add_reaction_Lindemann_with_special_orders
add_Troe_ord = self._griffon.mechanism_add_reaction_Troe_with_special_orders
for i, rx in enumerate(reac_list):
if rx['type'] == 'simple':
if 'orders' in rx:
add_smpl_ord(rx['reactants'], rx['products'], rx['reversible'],
rx['A'], rx['b'], rx['Ea'] / ct.gas_constant, rx['orders'])
self._mech_data['reactions'].append(('simple-special', rx['reactants'], rx['products'],
rx['reversible'], rx['A'], rx['b'], rx['Ea'],
rx['orders']))
else:
add_smpl(rx['reactants'], rx['products'], rx['reversible'],
rx['A'], rx['b'], rx['Ea'] / ct.gas_constant)
self._mech_data['reactions'].append(('simple', rx['reactants'], rx['products'], rx['reversible'],
rx['A'], rx['b'], rx['Ea']))
elif rx['type'] == 'three-body':
if 'orders' in rx:
add_3bdy_ord(rx['reactants'], rx['products'], rx['reversible'],
rx['A'], rx['b'], rx['Ea'] / ct.gas_constant,
rx['efficiencies'], rx['default-eff'], rx['orders'])
self._mech_data['reactions'].append(('three-body-special', rx['reactants'], rx['products'],
rx['reversible'],
rx['A'], rx['b'], rx['Ea'],
rx['efficiencies'], rx['default-eff'], rx['orders']))
else:
add_3bdy(rx['reactants'], rx['products'], rx['reversible'],
rx['A'], rx['b'], rx['Ea'] / ct.gas_constant,
rx['efficiencies'], rx['default-eff'])
self._mech_data['reactions'].append(
('three-body', rx['reactants'], rx['products'], rx['reversible'],
rx['A'], rx['b'], rx['Ea'],
rx['efficiencies'], rx['default-eff']))
elif rx['type'] == 'Lindemann':
if 'orders' in rx:
add_Lind_ord(rx['reactants'], rx['products'], rx['reversible'],
rx['fwd-A'], rx['fwd-b'], rx['fwd-Ea'] / ct.gas_constant,
rx['efficiencies'], rx['default-eff'],
rx['flf-A'], rx['flf-b'], rx['flf-Ea'] / ct.gas_constant,
rx['orders'])
self._mech_data['reactions'].append(('Lindemann-special', rx['reactants'], rx['products'],
rx['reversible'],
rx['fwd-A'], rx['fwd-b'], rx['fwd-Ea'],
rx['efficiencies'], rx['default-eff'],
rx['flf-A'], rx['flf-b'], rx['flf-Ea'],
rx['orders']))
else:
add_Lind(rx['reactants'], rx['products'], rx['reversible'],
rx['fwd-A'], rx['fwd-b'], rx['fwd-Ea'] / ct.gas_constant,
rx['efficiencies'], rx['default-eff'],
rx['flf-A'], rx['flf-b'], rx['flf-Ea'] / ct.gas_constant)
self._mech_data['reactions'].append(('Lindemann', rx['reactants'], rx['products'], rx['reversible'],
rx['fwd-A'], rx['fwd-b'], rx['fwd-Ea'],
rx['efficiencies'], rx['default-eff'],
rx['flf-A'], rx['flf-b'], rx['flf-Ea']))
elif rx['type'] == 'Troe':
if 'orders' in rx:
add_Troe_ord(rx['reactants'], rx['products'], rx['reversible'],
rx['fwd-A'], rx['fwd-b'], rx['fwd-Ea'] / ct.gas_constant,
rx['efficiencies'], rx['default-eff'],
rx['flf-A'], rx['flf-b'], rx['flf-Ea'] / ct.gas_constant,
rx['Troe-params'].tolist(),
rx['orders'])
self._mech_data['reactions'].append(('Troe-special', rx['reactants'], rx['products'],
rx['reversible'],
rx['fwd-A'], rx['fwd-b'], rx['fwd-Ea'],
rx['efficiencies'], rx['default-eff'],
rx['flf-A'], rx['flf-b'], rx['flf-Ea'],
rx['Troe-params'].tolist(),
rx['orders']))
else:
add_Troe(rx['reactants'], rx['products'], rx['reversible'],
rx['fwd-A'], rx['fwd-b'], rx['fwd-Ea'] / ct.gas_constant,
rx['efficiencies'], rx['default-eff'],
rx['flf-A'], rx['flf-b'], rx['flf-Ea'] / ct.gas_constant,
rx['Troe-params'].tolist())
self._mech_data['reactions'].append(('Troe', rx['reactants'], rx['products'], rx['reversible'],
rx['fwd-A'], rx['fwd-b'], rx['fwd-Ea'],
rx['efficiencies'], rx['default-eff'],
rx['flf-A'], rx['flf-b'], rx['flf-Ea'],
rx['Troe-params'].tolist()))
@classmethod
def _build_cantera_solution(cls, gdata):
p_ref = gdata['ref_pressure']
species_list = list()
for s in gdata['species']:
spec = gdata['species'][s]
ctspec = ct.Species(s, ','.join([f'{k}:{spec["atom_map"][k]}' for k in spec['atom_map']]))
if spec['cp'][0] == 'constant':
Tmin, Tmax, T0, h0, s0, cp = spec['cp'][1:]
ctspec.thermo = ct.ConstantCp(Tmin, Tmax, p_ref, list([T0, h0, s0, cp]))
elif spec['cp'][0] == 'NASA7':
Tmin, Tmid, Tmax, low_coeffs, high_coeffs = spec['cp'][1:]
coeffs = [Tmid] + high_coeffs + low_coeffs
ctspec.thermo = ct.NasaPoly2(Tmin, Tmax, p_ref, coeffs)
elif spec['cp'][0] == 'NASA9':
Tmin, Tmax, coeffs = spec['cp'][1:]
ctspec.thermo = ct.Nasa9PolyMultiTempRegion(Tmin, Tmax, p_ref, coeffs)
if 'transport-data' in spec and 'transport-model' in gdata and gdata['transport-model'] is not None:
ctspec.transport = ct.GasTransportData(**spec['transport-data'])
species_list.append(ctspec)
reaction_list = list()
for rxn in gdata['reactions']:
type, reactants_stoich, products_stoich, reversible = rxn[:4]
if type == 'simple' or type == 'simple-special':
if cantera_version_check('pre', 2, 6, None):
ctrxn = ct.ElementaryReaction(reactants_stoich, products_stoich)
ctrxn.rate = ct.Arrhenius(*rxn[4:7])
else:
ctrxn = ct.Reaction(reactants_stoich, products_stoich, ct.ArrheniusRate(*rxn[4:7]))
elif type == 'three-body' or type == 'three-body-special':
ctrxn = ct.ThreeBodyReaction(reactants_stoich, products_stoich)
ctrxn.rate = ct.Arrhenius(*rxn[4:7]) if cantera_version_check('pre', 2, 6, None) else ct.ArrheniusRate(*rxn[4:7])
ctrxn.efficiencies = rxn[7]
ctrxn.default_efficiency = rxn[8]
elif type == 'Lindemann' or type == 'Lindemann-special':
if cantera_version_check('pre', 2, 6, None):
ctrxn = ct.FalloffReaction(reactants_stoich, products_stoich)
ctrxn.efficiencies = rxn[7]
ctrxn.default_efficiency = rxn[8]
ctrxn.high_rate = ct.Arrhenius(*rxn[4:7])
ctrxn.low_rate = ct.Arrhenius(*rxn[9:12])
ctrxn.falloff = ct.Falloff()
else:
ctrxn = ct.FalloffReaction(
reactants_stoich,
products_stoich,
rate=ct.LindemannRate(low=ct.Arrhenius(*rxn[9:12]), high=ct.Arrhenius(*rxn[4:7])),
efficiencies=rxn[7])
ctrxn.default_efficiency = rxn[8]
elif type == 'Troe' or type == 'Troe-special':
if cantera_version_check('pre', 2, 6, None):
ctrxn = ct.FalloffReaction(reactants_stoich, products_stoich)
ctrxn.efficiencies = rxn[7]
ctrxn.default_efficiency = rxn[8]
troe_params = rxn[12]
ctrxn.high_rate = ct.Arrhenius(*rxn[4:7])
ctrxn.low_rate = ct.Arrhenius(*rxn[9:12])
if len(troe_params) == 4 and abs(troe_params[3]) < 1e-300:
ctrxn.falloff = ct.TroeFalloff(troe_params[:3])
else:
ctrxn.falloff = ct.TroeFalloff(troe_params)
else:
troe_params = rxn[12]
if len(troe_params) == 4 and abs(troe_params[3]) < 1e-300:
falloff_coeffs = troe_params[:3]
else:
falloff_coeffs = troe_params
ctrxn = ct.FalloffReaction(
reactants_stoich,
products_stoich,
rate=ct.TroeRate(low=ct.Arrhenius(*rxn[9:12]), high=ct.Arrhenius(*rxn[4:7]), falloff_coeffs=falloff_coeffs),
efficiencies=rxn[7])
ctrxn.default_efficiency = rxn[8]
if 'special' in type:
ctrxn.orders = rxn[-1]
ctrxn.reversible = reversible
reaction_list.append(ctrxn)
return ct.Solution(transport_model=None if 'transport-model' not in gdata else gdata['transport-model'], thermo='IdealGas', kinetics='GasKinetics', species=species_list, reactions=reaction_list)
@classmethod
def _get_cantera_element_mw_map(cls, ctsol: ct.Solution):
species_list = [ct.Species(element_name, f'{element_name}: 1') for element_name in ctsol.element_names]
for i in range(len(species_list)):
species_list[i].thermo = ct.ConstantCp(300., 3000., 101325., (300., 0., 0., 1.e4))
element_only_ctsol = ct.Solution(thermo='IdealGas', kinetics='GasKinetics', species=species_list, reactions=[])
return {name: mw for name, mw in zip(element_only_ctsol.species_names, element_only_ctsol.molecular_weights)}
@classmethod
def _extract_cantera_mechanism_data(cls, ctsol: ct.Solution):
ct_element_mw_map = cls._get_cantera_element_mw_map(ctsol)
elem_list = ctsol.element_names
ref_temperature = 298.15
ref_pressure = ctsol.reference_pressure
spec_name_list = list()
spec_dict = dict()
reac_temporary_list = list()
# todo: add error checking
for i in range(ctsol.n_species):
sp = ctsol.species(i)
spec_name_list.append(sp.name)
if isinstance(sp.thermo, ct.ConstantCp):
spec_dict[sp.name] = dict({'atoms': sp.composition,
'heat-capacity': dict({
'type': 'constant',
'Tmin': sp.thermo.min_temp,
'Tmax': sp.thermo.max_temp,
'T0': sp.thermo.coeffs[0],
'h0': sp.thermo.coeffs[1],
's0': sp.thermo.coeffs[2],
'cp': sp.thermo.coeffs[3]})})
elif isinstance(sp.thermo, ct.NasaPoly2):
spec_dict[sp.name] = dict({'atoms': sp.composition,
'heat-capacity': dict({
'type': 'NASA7',
'Tmin': sp.thermo.min_temp,
'Tmid': sp.thermo.coeffs[0],
'Tmax': sp.thermo.max_temp,
'low-coeffs': sp.thermo.coeffs[8:],
'high-coeffs': sp.thermo.coeffs[1:8]})})
elif isinstance(sp.thermo, ct.Nasa9PolyMultiTempRegion):
spec_dict[sp.name] = dict({'atoms': sp.composition,
'heat-capacity': dict({
'type': 'NASA9',
'Tmin': sp.thermo.min_temp,
'Tmax': sp.thermo.max_temp,
'coeffs': sp.thermo.coeffs})})
if sp.transport is not None:
spec_dict[sp.name]['transport-data'] = dict(acentric_factor=sp.transport.acentric_factor,
diameter=sp.transport.diameter,
dipole=sp.transport.dipole,
dispersion_coefficient=sp.transport.dispersion_coefficient,
geometry=sp.transport.geometry,
polarizability=sp.transport.polarizability,
quadrupole_polarizability=sp.transport.quadrupole_polarizability,
rotational_relaxation=sp.transport.rotational_relaxation,
well_depth=sp.transport.well_depth)
transport_model = None if (ctsol.transport_model == 'Transport' or ctsol.transport_model is None) else ctsol.transport_model
for i in range(ctsol.n_reactions):
rx = ctsol.reaction(i)
if isinstance(rx, ct.FalloffReaction):
if cantera_version_check('pre', 2, 6, None):
f = rx.falloff
if isinstance(f, ct.TroeFalloff):
reac_temporary_list.append((3, dict({'type': 'Troe',
'reversible': rx.reversible,
'reactants': rx.reactants,
'products': rx.products,
'default-eff': rx.default_efficiency,
'efficiencies': rx.efficiencies,
'fwd-A': rx.high_rate.pre_exponential_factor,
'fwd-b': rx.high_rate.temperature_exponent,
'fwd-Ea': rx.high_rate.activation_energy,
'flf-A': rx.low_rate.pre_exponential_factor,
'flf-b': rx.low_rate.temperature_exponent,
'flf-Ea': rx.low_rate.activation_energy,
'Troe-params': rx.falloff.parameters})))
if rx.orders:
reac_temporary_list[-1][1]['orders'] = rx.orders
else:
reac_temporary_list.append((2, dict({'type': 'Lindemann',
'reversible': rx.reversible,
'reactants': rx.reactants,
'products': rx.products,
'default-eff': rx.default_efficiency,
'efficiencies': rx.efficiencies,
'fwd-A': rx.high_rate.pre_exponential_factor,
'fwd-b': rx.high_rate.temperature_exponent,
'fwd-Ea': rx.high_rate.activation_energy,
'flf-A': rx.low_rate.pre_exponential_factor,
'flf-b': rx.low_rate.temperature_exponent,
'flf-Ea': rx.low_rate.activation_energy})))
if rx.orders:
reac_temporary_list[-1][1]['orders'] = rx.orders
else:
if isinstance(rx.rate, ct.TroeRate):
reac_temporary_list.append((3, dict({'type': 'Troe',
'reversible': rx.reversible,
'reactants': rx.reactants,
'products': rx.products,
'default-eff': rx.default_efficiency,
'efficiencies': rx.efficiencies,
'fwd-A': rx.rate.high_rate.pre_exponential_factor,
'fwd-b': rx.rate.high_rate.temperature_exponent,
'fwd-Ea': rx.rate.high_rate.activation_energy,
'flf-A': rx.rate.low_rate.pre_exponential_factor,
'flf-b': rx.rate.low_rate.temperature_exponent,
'flf-Ea': rx.rate.low_rate.activation_energy,
'Troe-params': rx.rate.falloff_coeffs})))
if rx.orders:
reac_temporary_list[-1][1]['orders'] = rx.orders
else:
reac_temporary_list.append((2, dict({'type': 'Lindemann',
'reversible': rx.reversible,
'reactants': rx.reactants,
'products': rx.products,
'default-eff': rx.default_efficiency,
'efficiencies': rx.efficiencies,
'fwd-A': rx.rate.high_rate.pre_exponential_factor,
'fwd-b': rx.rate.high_rate.temperature_exponent,
'fwd-Ea': rx.rate.high_rate.activation_energy,
'flf-A': rx.rate.low_rate.pre_exponential_factor,
'flf-b': rx.rate.low_rate.temperature_exponent,
'flf-Ea': rx.rate.low_rate.activation_energy})))
if rx.orders:
reac_temporary_list[-1][1]['orders'] = rx.orders
elif isinstance(rx, ct.ThreeBodyReaction):
reac_temporary_list.append((1, dict({'type': 'three-body',
'reversible': rx.reversible,
'reactants': rx.reactants,
'products': rx.products,
'default-eff': rx.default_efficiency,
'efficiencies': rx.efficiencies,
'A': rx.rate.pre_exponential_factor,
'b': rx.rate.temperature_exponent,
'Ea': rx.rate.activation_energy})))
if rx.orders:
reac_temporary_list[-1][1]['orders'] = rx.orders
else:
reac_temporary_list.append((0, dict({'type': 'simple',
'reversible': rx.reversible,
'reactants': rx.reactants,
'products': rx.products,
'A': rx.rate.pre_exponential_factor,
'b': rx.rate.temperature_exponent,
'Ea': rx.rate.activation_energy})))
if rx.orders:
reac_temporary_list[-1][1]['orders'] = rx.orders
reac_list = [y[1] for y in sorted(reac_temporary_list, key=lambda x: x[0])]
return ct_element_mw_map, elem_list, ref_temperature, ref_pressure, spec_name_list, spec_dict, reac_list, transport_model
@property
def gas(self):
"""Obtain this mechanism's cantera Solution object"""
return self._cantera_wrapper.solution
@property
def griffon(self):
"""Obtain this mechanism's griffon PyCombustionKernels object"""
return self._griffon
@property
def mech_xml_path(self):
"""Obtain the path of the identified mechanism's XML specification"""
print('Deprecation warning: the "mech_xml_path" property of ChemicalMechanismSpec is deprecated and will be removed.\nUse the "mech_file_path" property instead.')
return self._cantera_wrapper.mech_file_path
@property
def mech_file_path(self):
"""Obtain the path of the identified mechanism's Cantera input file specification"""
return self._cantera_wrapper.mech_file_path
@property
def group_name(self):
"""Obtain the group name of the identified mechanism"""
return self._cantera_wrapper.group_name
@property
def n_species(self):
"""Obtain the number of species in this chemical mechanism"""
return self._cantera_wrapper.solution.n_species
@property
def n_reactions(self):
"""Obtain the number of reactions in this chemical mechanism"""
return self._cantera_wrapper.solution.n_reactions
@property
def species_names(self):
"""Obtain the names of speciesin this chemical mechanism"""
return self._cantera_wrapper.solution.species_names
def species_index(self, name):
"""Obtain the index of a particular species"""
return self._cantera_wrapper.solution.species_index(name)
@property
def molecular_weights(self):
return array([self._cantera_wrapper.solution.molecular_weights[ni] for ni in range(self.n_species)])
def molecular_weight(self, ni):
"""Obtain the molecular weight of a single species from its string name or integer index
"""
if isinstance(ni, str):
return self._cantera_wrapper.solution.molecular_weights[self._cantera_wrapper.solution.species_index(ni)]
elif isinstance(ni, int):
return self._cantera_wrapper.solution.molecular_weights[ni]
else:
raise TypeError('ChemicalMechanismSpec.molecular_weight(ni) takes a string or integer, given ' + str(ni))
def stream(self, properties=None, values=None, stp_air=False):
"""Build a mixture of species with certain properties
Parameters
----------
properties : str
a string of keys used in building a cantera Quantity (e.g., 'TPX' or 'TP' or 'X', etc.)
values : tuple
the values of the properties
stp_air : bool
special option to make a stream of air at standard temperature and pressure (default: False)
This produces a stream of 3.74 mol N2 per mole O2 at 300 K and one atmosphere
Returns
-------
mix : cantera.Quantity
a cantera Quantity object with the specified properties
"""
q = ct.Quantity(self._cantera_wrapper.solution)
if stp_air:
if properties is not None or values is not None:
print('Warning in building a stream of air at standard conditions!'
'The properties and values arguments will be ignored because stp_air=True was set.')
q.TPX = 300., 101325., 'o2:1 n2:3.74'
else:
if properties is None:
raise ValueError('ChemicalMechanismSpec.stream() was called improperly.\n'
'There are two ways to build streams:\n'
' 1) stream(stp_air=True)\n'
' 2) stream(properties, values), e.g. stream(\'X\', \'O2:1, N2:1\')\n'
' '
'or stream(\'TPY\', (300., 101325., \'O2:1, N2:1\'))\n')
else:
if properties is not None and values is None:
raise ValueError('ChemicalMechanismSpec.stream() expects two arguments '
'if properties are set in the construction')
setattr(q, properties, values)
return q
def copy_stream(self, stream):
"""Make a duplicate of a stream - use this to avoid inadvertently modifying a stream by reference."""
q = ct.Quantity(self._cantera_wrapper.solution)
q.TPX = stream.TPX
return q
@staticmethod
def mix_streams(streams, basis, constant='HP'):
"""Mix a number of streams by mass/mole and at constant HP, TP, UV, etc. (as supported by Cantera)
Parameters
----------
streams : list(tuple)
a list of tuples as [(stream, amount)] where amount is the mass/moles (depending on the basis)
basis : str
whether amounts are masses ('mass') or moles ('mole')
constant : str
property pair held constant, such as HP (default), TP, UV - any combination supported by Cantera
Returns
-------
mix : cantera.Quantity
the requested mixture
"""
q_list = []
for stream, amount in streams:
if basis == 'mass':
stream.mass = amount
elif basis == 'mole':
stream.moles = amount
stream.constant = constant
q_list.append(stream)
mix = sum(q_list)
return mix
def mix_for_equivalence_ratio(self, phi, fuel, oxy):
"""Mix a stream of fuel and oxidizer such that the mixture has a specified equivalence ratio."""
self._cantera_wrapper.solution.set_equivalence_ratio(phi, fuel.X, oxy.X)
return ct.Quantity(self._cantera_wrapper.solution)
def mix_for_normalized_equivalence_ratio(self, normalized_phi, fuel, oxy):
"""Mix a stream of fuel and oxidizer such that the mixture has a specified normalized equivalence ratio."""
return self.mix_for_equivalence_ratio(normalized_phi / (1. - normalized_phi), fuel, oxy)
def _get_atoms_in_stream(self, stream, atom_names):
atom_amounts = dict()
for atom in atom_names:
atom_amounts[atom] = 0
for i, species in enumerate(stream.species_names):
mole_fraction = stream.X[i]
for atom in atom_names:
atom_amounts[atom] += mole_fraction * stream.n_atoms(species, atom)
return atom_amounts
def stoich_molar_fuel_to_oxy_ratio(self, fuel_stream, oxy_stream):
"""Get the molar ratio of fuel to oxidizer at stoichiometric conditions.
Assumes C, O, and H combustion of single fuel and single oxidizer streams."""
atom_names = ['H', 'O']
if 'C' in self._cantera_wrapper.solution.element_names:
atom_names.append('C')
fuel_atoms = self._get_atoms_in_stream(fuel_stream, atom_names)
oxy_atoms = self._get_atoms_in_stream(oxy_stream, atom_names)
if 'C' not in self._cantera_wrapper.solution.element_names:
fuel_atoms['C'] = 0
oxy_atoms['C'] = 0
return -(oxy_atoms['O'] - 0.5 * oxy_atoms['H'] - 2.0 * oxy_atoms['C']) / (
fuel_atoms['O'] - 0.5 * fuel_atoms['H'] - 2.0 * fuel_atoms['C'])
def stoich_mass_fuel_to_oxy_ratio(self, fuel_stream, oxy_stream):
"""Get the mass ratio of fuel to oxidizer at stoichiometric conditions.
Assumes C, O, and H combustion of single fuel and single oxidizer streams."""
mf = fuel_stream.mean_molecular_weight
mx = oxy_stream.mean_molecular_weight
return mf / mx * self.stoich_molar_fuel_to_oxy_ratio(fuel_stream, oxy_stream)
def stoich_mixture_fraction(self, fuel_stream, oxy_stream):
"""Get the mixture fraction at stoichiometric conditions.
Assumes C, O, and H combustion of single fuel and single oxidizer streams."""
eta = self.stoich_mass_fuel_to_oxy_ratio(fuel_stream, oxy_stream)
return eta / (1. + eta)
def mix_fuels_for_stoich_mixture_fraction(self, fuel1, fuel2, zstoich, oxy):
"""Mix two fuel streams for a specified stoichiometric mixture fraction given a particular oxidizer.
As an example, this can be used to dilute a fuel with Nitrogen to hit a particular stoichiometric mixture fraction.
Note that it is not possible to reach all stoichiometric mixture fractions with any fuel combinations!
In such a case this function will throw an error."""
atom_names = ['H', 'O']
if 'C' in self._cantera_wrapper.solution.element_names:
atom_names.append('C')
coeffs_a = self._get_atoms_in_stream(fuel1, atom_names)
coeffs_b = self._get_atoms_in_stream(fuel2, atom_names)
coeffs_x = self._get_atoms_in_stream(oxy, atom_names)
if 'C' not in self._cantera_wrapper.solution.element_names:
coeffs_a['C'] = 0
coeffs_b['C'] = 0
coeffs_x['C'] = 0
mfa = fuel1.mean_molecular_weight
mfb = fuel2.mean_molecular_weight
dmf = mfa - mfb
mx = oxy.mean_molecular_weight
etax = coeffs_x['O'] - 0.5 * coeffs_x['H'] - 2. * coeffs_x['C']
netab = -coeffs_b['O'] + 0.5 * coeffs_b['H'] + 2. * coeffs_b['C']
netaa = -coeffs_a['O'] + 0.5 * coeffs_a['H'] + 2. * coeffs_a['C']
lhs = mx / etax * zstoich / (1. - zstoich)
gamma = netaa - netab
kstar = (mfb - lhs * netab) / (lhs * gamma - dmf)
if kstar > 1. or kstar < 0.:
raise ValueError('The provided fuel combination cannot reach the desired stoichiometric mixture fraction!')
else:
return self.mix_streams([(fuel1, kstar), (fuel2, 1. - kstar)], 'mole')
<file_sep>import unittest
import numpy as np
import pickle
from os.path import join, abspath
from spitfire import ChemicalMechanismSpec, Flamelet, FlameletSpec
def construct_adiabatic_flamelet(initialization, grid_type, diss_rate_form):
test_xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
mechanism = ChemicalMechanismSpec(cantera_input=test_xml, group_name='h2-burke')
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
fuel.TP = 300, air.P
if grid_type == 'uniform':
grid_specs = {'grid_points': 8}
elif grid_type == 'clustered-1args':
grid_specs = {'grid_points': 8}
elif grid_type == 'clustered-2args':
grid_specs = {'grid_points': 8, 'grid_cluster_intensity': 4.}
elif grid_type == 'clustered-3args':
grid_specs = {'grid_points': 8, 'grid_cluster_intensity': 4., 'grid_cluster_point': 0.4}
elif grid_type == 'custom':
grid_specs = {'grid': np.linspace(0., 1., 8)}
if diss_rate_form == 'Peters':
drf_specs = {'max_dissipation_rate': 1., 'dissipation_rate_form': diss_rate_form}
elif diss_rate_form == 'uniform':
drf_specs = {'max_dissipation_rate': 1., 'dissipation_rate_form': diss_rate_form}
elif diss_rate_form == 'custom':
drf_specs = {'dissipation_rate': np.linspace(0., 1., 8)}
flamelet_specs = {'mech_spec': mechanism,
'oxy_stream': air,
'fuel_stream': fuel,
'initial_condition': initialization}
flamelet_specs.update(grid_specs)
flamelet_specs.update(drf_specs)
try:
Flamelet(**flamelet_specs)
Flamelet(flamelet_specs=flamelet_specs)
fso = FlameletSpec(**flamelet_specs)
f = Flamelet(fso)
fso_pickle = pickle.dumps(fso)
fso2 = pickle.loads(fso_pickle)
f = Flamelet(fso2)
lib = f.make_library_from_interior_state(f.initial_interior_state)
Flamelet(library_slice=lib)
lib_pickle = pickle.dumps(lib)
lib2 = pickle.loads(lib_pickle)
Flamelet(library_slice=lib2)
return True
except:
return False
def construct_nonadiabatic_flamelet(initialization, grid_type, diss_rate_form):
test_xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
mechanism = ChemicalMechanismSpec(cantera_input=test_xml, group_name='h2-burke')
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
fuel.TP = 300, air.P
if grid_type == 'uniform':
grid_specs = {'grid_points': 8}
elif grid_type == 'clustered-1args':
grid_specs = {'grid_points': 8}
elif grid_type == 'clustered-2args':
grid_specs = {'grid_points': 8, 'grid_cluster_intensity': 4.}
elif grid_type == 'clustered-3args':
grid_specs = {'grid_points': 8, 'grid_cluster_intensity': 4., 'grid_cluster_point': 0.4}
elif grid_type == 'custom':
grid_specs = {'grid': np.linspace(0., 1., 8)}
if diss_rate_form == 'Peters':
drf_specs = {'max_dissipation_rate': 1., 'dissipation_rate_form': diss_rate_form}
elif diss_rate_form == 'uniform':
drf_specs = {'max_dissipation_rate': 1., 'dissipation_rate_form': diss_rate_form}
elif diss_rate_form == 'custom':
drf_specs = {'dissipation_rate': np.linspace(0., 1., 8)}
try:
flamelet_specs = {'mech_spec': mechanism,
'oxy_stream': air,
'fuel_stream': fuel,
'initial_condition': initialization,
'heat_transfer': 'nonadiabatic',
'convection_temperature': 350.,
'convection_coefficient': 0.,
'radiation_temperature': 350.,
'radiative_emissivity': 0.}
flamelet_specs.update(grid_specs)
flamelet_specs.update(drf_specs)
Flamelet(**flamelet_specs)
Flamelet(flamelet_specs=flamelet_specs)
fso = FlameletSpec(**flamelet_specs)
f = Flamelet(fso)
fso_pickle = pickle.dumps(fso)
fso2 = pickle.loads(fso_pickle)
f = Flamelet(fso2)
lib = f.make_library_from_interior_state(f.initial_interior_state)
Flamelet(library_slice=lib)
lib_pickle = pickle.dumps(lib)
lib2 = pickle.loads(lib_pickle)
Flamelet(library_slice=lib2)
flamelet_specs = {'mech_spec': mechanism,
'oxy_stream': air,
'fuel_stream': fuel,
'initial_condition': initialization,
'heat_transfer': 'nonadiabatic',
'scale_heat_loss_by_temp_range': True,
'scale_convection_by_dissipation': True,
'use_linear_ref_temp_profile': True,
'convection_coefficient': 1.e7,
'radiative_emissivity': 0.}
flamelet_specs.update(grid_specs)
flamelet_specs.update(drf_specs)
Flamelet(**flamelet_specs)
Flamelet(flamelet_specs=flamelet_specs)
fso = FlameletSpec(**flamelet_specs)
f = Flamelet(fso)
fso_pickle = pickle.dumps(fso)
fso2 = pickle.loads(fso_pickle)
f = Flamelet(fso2)
lib = f.make_library_from_interior_state(f.initial_interior_state)
Flamelet(library_slice=lib)
lib_pickle = pickle.dumps(lib)
lib2 = pickle.loads(lib_pickle)
Flamelet(library_slice=lib2)
flamelet_specs = {'mech_spec': mechanism,
'oxy_stream': air,
'fuel_stream': fuel,
'initial_condition': initialization,
'heat_transfer': 'nonadiabatic',
'scale_heat_loss_by_temp_range': False,
'scale_convection_by_dissipation': False,
'use_linear_ref_temp_profile': True,
'convection_coefficient': 1.e7,
'radiative_emissivity': 0.}
flamelet_specs.update(grid_specs)
flamelet_specs.update(drf_specs)
Flamelet(**flamelet_specs)
Flamelet(flamelet_specs=flamelet_specs)
fso = FlameletSpec(**flamelet_specs)
f = Flamelet(fso)
fso_pickle = pickle.dumps(fso)
fso2 = pickle.loads(fso_pickle)
f = Flamelet(fso2)
lib = f.make_library_from_interior_state(f.initial_interior_state)
Flamelet(library_slice=lib)
lib_pickle = pickle.dumps(lib)
lib2 = pickle.loads(lib_pickle)
Flamelet(library_slice=lib2)
flamelet_specs = {'mech_spec': mechanism,
'oxy_stream': air,
'fuel_stream': fuel,
'initial_condition': initialization,
'heat_transfer': 'nonadiabatic',
'scale_heat_loss_by_temp_range': False,
'scale_convection_by_dissipation': True,
'use_linear_ref_temp_profile': True,
'convection_coefficient': 1.e7,
'radiative_emissivity': 0.}
flamelet_specs.update(grid_specs)
flamelet_specs.update(drf_specs)
Flamelet(**flamelet_specs)
Flamelet(flamelet_specs=flamelet_specs)
fso = FlameletSpec(**flamelet_specs)
f = Flamelet(fso)
fso_pickle = pickle.dumps(fso)
fso2 = pickle.loads(fso_pickle)
f = Flamelet(fso2)
lib = f.make_library_from_interior_state(f.initial_interior_state)
Flamelet(library_slice=lib)
lib_pickle = pickle.dumps(lib)
lib2 = pickle.loads(lib_pickle)
Flamelet(library_slice=lib2)
return True
except:
return False
def create_test(ht, ic, gt, drf):
if ht == 'adiabatic':
def test(self):
self.assertTrue(construct_adiabatic_flamelet(ic, gt, drf))
elif ht == 'nonadiabatic':
def test(self):
self.assertTrue(construct_nonadiabatic_flamelet(ic, gt, drf))
return test
class Construction(unittest.TestCase):
pass
test_xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
mechanism = ChemicalMechanismSpec(cantera_input=test_xml, group_name='h2-burke')
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
fuel.TP = 300, air.P
flamelet_specs = {'mech_spec': mechanism,
'oxy_stream': air,
'fuel_stream': fuel,
'grid_points': 8,
'grid_cluster_intensity': 4.,
'initial_condition': 'equilibrium',
'max_dissipation_rate': 0.}
temp_flamelet = Flamelet(**flamelet_specs)
for ht in temp_flamelet._heat_transfers:
for ic in ['equilibrium', 'linear-TY', 'unreacted', temp_flamelet.initial_interior_state]:
for gt in ['uniform', 'clustered-1args', 'clustered-2args', 'clustered-3args', 'custom']:
for drf in ['uniform', 'Peters', 'custom']:
ic_str = 'icstate' if isinstance(ic, np.ndarray) else ic
testname = 'test_construct_flamelet_' + ht + '_' + ic_str + '_' + gt + '_' + drf
setattr(Construction, testname, create_test(ht, ic, gt, drf))
if __name__ == '__main__':
unittest.main()
<file_sep>Introduction to Flamelet Models & Spitfire
==========================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - What is a flamelet? What is a ``Flamelet`` in Spitfire? -
Computing steady flamelets and transient extinction trajectories -
Building a steady laminar flamelet model (SLFM) table - Building a
flamelet progress variable (FPV) table
Introduction
------------
Tabulated chemistry models are the workhorse of large-scale turbulent
combustion simulations. They provide a practical means of incorporating
competition between combustion chemistry, turbulence, radiation, and
inter-phase interactions of combustion gases with sprays, coal, and
soot. A fundamental concept in various tabulated chemistry formulations
is that of the *flamelet*, a small, one-dimensional (usually) laminar
flame that cuts through surfaces where fuel and oxidizer mix in a
diffusion flame. Flamelet-based models provide a physics-based model
reduction that separates the fast and small-scale dynamics of a fire
from larger hydrodynamic scales, with the primary assumption that
molecular mixing and chemistry at the reaction front rapidly equilibrate
together. These processes can be affected by radiation and turbulence,
and there are plenty of combustion regimes where the assumptions of a
flamelet model are invalid.
Spitfire’s role is solving the flamelet equations and tabulating the
results for later use in fire simulations. The primary applications of
flamelet models built in Spitfire are pool fires and coal combustion,
but it has been used in a number of other ways. Spitfire can generate
adiabatic and nonadiabatic flamelet libraries, and built-in support for
presumed PDF turbulence modeling is being added.
The focus of this notebook is to introduce the ``Flamelet`` class and
show how to compute steady flamelet profiles and transient extinction
trajectories. With this we can then compose traditional SLFM and FPV
chemistry tables ourselves. Spitfire provides easier methods to generate
SLFM tables (general FPV tables will be added eventually), which we’ll
cover in later demonstrations.
The ``Flamelet`` Class
----------------------
An instance of Spitfire’s ``Flamelet`` class is defined by a set of
governing equations, parameter specifications, and a grid in the mixture
fraction dimension.
The “governing equations” refers to - terms in the interior equations -
boundary streams - initial conditions
The “parameter specifications” refers to - the scalar dissipation rate -
heat loss parameters (e.g., convection coefficient)
The ``FlameletSpec`` class exists to help build flamelets. Below we use
it to build several minimal ``Flamelet``\ s for an n-heptane/air
mixture.
.. code:: ipython3
from spitfire import Flamelet, FlameletSpec, Library, Dimension, ChemicalMechanismSpec
from spitfire import get_ct_solution_array
import matplotlib.pyplot as plt
import numpy as np
.. code:: ipython3
mech = ChemicalMechanismSpec('heptane-liu-hewson-chen-pitsch-highT.xml', 'gas')
air = mech.stream(stp_air=True)
fuel = mech.stream('TPX', (372, air.P, 'NXC7H16:1'))
``FlameletSpec -> Flamelet``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A ``Flamelet`` can be constructed from a ``FlameletSpec`` instance. This
is the best way to get help from an IDE that indexes your Python
interpreter for keywords. Minimally, a ``FlameletSpec`` needs the
chemical mechanism, an initial condition, the fuel and oxidizer streams,
and a number of grid points. Alternatively, one can pass a ``Library``
object as done below.
.. code:: ipython3
flamelets = dict()
fs_unreacted = FlameletSpec(mech_spec=mech,
initial_condition='unreacted',
oxy_stream=air,
fuel_stream=fuel,
grid_points=64)
flamelets['unreacted'] = Flamelet(fs_unreacted)
Direct ``Flamelet`` Construction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A ``Flamelet`` can also be constructed by providing keywords to its
initializer, which internally are passed to a ``FlameletSpec``. This is
simply shorter than the above and not reusable.
.. code:: ipython3
flamelets['equilibrium'] = Flamelet(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,
fuel_stream=fuel,
grid_points=64)
A reusable variant of the above is how early Spitfire users created
``Flamelet`` objects - passing around a dictionary that simply gets
unpacked into keyword arguments. Again, this is internally equivalent to
the ``FlameletSpec`` path. The disadvantage here is not getting error
checking until you try to build the ``Flamelet`` itself.
.. code:: ipython3
fs_burke_schumann_dict = dict(mech_spec=mech,
initial_condition='Burke-Schumann',
oxy_stream=air,
fuel_stream=fuel,
grid_points=64)
flamelets['Burke-Schumann'] = Flamelet(**fs_burke_schumann_dict)
Initial Conditions
------------------
Note above that we used the “unreacted,”equilibrium," and
“Burke-Schumann” strings for the ``initial_condition`` argument. The
temperature and fuel mass fraction profiles for these special states are
plotted below. An unreacted mixture is only mixed, with linear species
and enthalpy profiles. Equilibrium refers to the state with linear
enthalpy but allowed to reach chemical equilibrium (no effects of
mixing). The Burke-Schumann state is an idealized case of perfect,
irreversible combustion.
.. code:: ipython3
for key in ['unreacted', 'equilibrium', 'Burke-Schumann']:
flamelet = flamelets[key]
plt.plot(flamelet.mixfrac_grid, flamelet.initial_temperature, '.-', label=key)
plt.legend()
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('initial temperature (K)')
plt.show()
for key in ['unreacted', 'equilibrium', 'Burke-Schumann']:
flamelet = flamelets[key]
plt.plot(flamelet.mixfrac_grid, flamelet.initial_mass_fraction('NXC7H16'), '.-', label=key)
plt.legend()
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('initial mass fraction n-heptane')
plt.show()
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_12_0.png
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_12_1.png
The Grid
--------
Carefully note in the above plots how the distribution of the grid
points is not uniform. When specifying only the number of grid points, a
clustered grid that focuses grid points near the stoichiometric mixture
fraction is made.
Below we specify the ``grid_type`` to be “uniform” instead of
“clustered” (the default value) and build another equilibrium flamelet.
Zooming in near the stoichiometric point with the highest curvature in
the temperature shows how the uniform grid misses this curvature. In
rare cases when dynamics in very rich mixtures are relevant, a uniform
grid ends up being the most efficient option, but most often the
clustered grid is far superior.
.. code:: ipython3
flamelets['equilibrium-uniform'] = Flamelet(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,fuel_stream=fuel,
grid_points=64,
grid_type='uniform')
for key in ['equilibrium', 'equilibrium-uniform']:
flamelet = flamelets[key]
plt.plot(flamelet.mixfrac_grid, flamelet.initial_temperature, '.-', label=key)
plt.legend()
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('initial temperature (K)')
plt.xlim([0.05, 0.1])
plt.ylim([1750, 2350])
plt.show()
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_14_0.png
Getting a Steady Flamelet at Finite Dissipation
-----------------------------------------------
In the ``Flamelet`` instances above, we avoided specifying the scalar
dissipation rate, which leads to it being zero. To incorporate molecular
mixing, the dissipation rate can be specified a few ways: -
``max_dissipation_rate`` or ``stoich_dissipation_rate``, along with
``dissipation_rate_form`` as either “constant” or “Peters” (the default)
to use a specified functional form of the dissipation rate -
``dissipation_rate`` to directly provide an array of values
.. code:: ipython3
flamelets['eq-Peters-st10Hz'] = Flamelet(FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,
fuel_stream=fuel,
grid_points=64,
stoich_dissipation_rate=10.0))
flamelets['eq-Peters-max10Hz'] = Flamelet(FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,
fuel_stream=fuel,
grid_points=64,
max_dissipation_rate=10.0))
flamelets['eq-constant-10Hz'] = Flamelet(FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,
fuel_stream=fuel,
grid_points=64,
stoich_dissipation_rate=10.0,
dissipation_rate_form='constant'))
flamelets['eq-constant-10Hz-array'] = Flamelet(FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,
fuel_stream=fuel,
grid_points=64,
dissipation_rate=10.0 * np.ones(64)))
The ``compute_steady_state()`` Method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now that we have flamelets with dissipation, the
``compute_steady_state()`` method can be used to compute the steady
temperature and mass fraction profiles that represent the balance
between molecular mixing and combustion chemistry. After calling this
method, the ``current_*`` properties for temperature, mass fractions,
etc. of the flamelet can be accessed.
In the following plots (the second simply zooms in on the first), you
can see the effect of dissipation, mostly to smooth out the equilibrium
profile as chemistry is balanced by mixing.
.. code:: ipython3
for key in ['eq-Peters-st10Hz', 'eq-Peters-max10Hz', 'eq-constant-10Hz-array', 'eq-constant-10Hz']:
flamelets[key].compute_steady_state()
for key in ['unreacted', 'equilibrium', 'Burke-Schumann'] + \
['eq-Peters-st10Hz', 'eq-Peters-max10Hz', 'eq-constant-10Hz-array', 'eq-constant-10Hz']:
flamelet = flamelets[key]
plt.plot(flamelet.mixfrac_grid, flamelet.current_temperature, label=key)
plt.legend()
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('temperature (K)')
plt.show()
for key in ['unreacted', 'equilibrium', 'Burke-Schumann'] + \
['eq-Peters-st10Hz', 'eq-Peters-max10Hz', 'eq-constant-10Hz-array', 'eq-constant-10Hz']:
flamelet = flamelets[key]
plt.plot(flamelet.mixfrac_grid, flamelet.current_temperature, label=key)
plt.legend()
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('temperature (K)')
plt.xlim([0.04, 0.2])
plt.ylim([1000, 2500])
plt.show()
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_18_0.png
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_18_1.png
Transient Extinction
--------------------
Now we’re going to solve the transient flamelet equations to look in
detail at strain-induced extinction of a flamelet initially at chemical
equilibrium. The plots below show the transition from the equilibrium
profiles to the extinguished state.
.. code:: ipython3
flamelet = Flamelet(FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,
fuel_stream=fuel,
grid_points=64,
stoich_dissipation_rate=1.e3))
output = flamelet.integrate_to_steady(write_log=True, first_time_step=1e-9)
.. parsed-literal::
2021-02-25 13:09 : Spitfire running case with method: Kennedy/Carpenter ESDIRK64
|number of | simulation | time step | diff. eqn. | total cpu | cput per |
|time steps | time (s) | size (s) | |residual| | time (s) | step (ms)|
---------------------------------------------------------------------------|
| 100 | 9.26e-07 | 2.95e-08 | 2.60e+05 | 1.88e+00 | 1.88e+01 |
| 200 | 9.78e-06 | 1.49e-07 | 4.83e+04 | 4.21e+00 | 2.10e+01 |
| 300 | 3.22e-05 | 5.43e-07 | 1.35e+04 | 7.21e+00 | 2.40e+01 |
| 400 | 1.58e-04 | 2.70e-06 | 1.67e+02 | 1.03e+01 | 2.58e+01 |
Integration successfully completed!
Statistics:
- number of time steps : 446
- final simulation time: 0.000587475337460484
- smallest time step : 1e-09
- average time step : 1.3172092768172287e-06
- largest time step : 3.73510924976309e-05
CPU time
- total (s) : 1.152887e+01
- per step (ms): 2.584949e+01
Nonlinear iterations
- total : 11480
- per step: 25.7
Linear iterations
- total : 11480
- per step : 25.7
- per nliter: 1.0
Jacobian setups
- total : 156
- steps per : 2.9
- nliter per: 73.6
- liter per : 73.6
2021-02-25 13:09 : Spitfire finished in 1.15288734e+01 seconds!
.. code:: ipython3
plt.plot(output.mixture_fraction_values, output['temperature'].T[:, ::10])
plt.plot(output.mixture_fraction_values, output['temperature'].T[:, 0], 'b-')
plt.plot(output.mixture_fraction_values, output['temperature'].T[:, -1], 'k-')
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('temperature (K)')
plt.show()
plt.plot(output.mixture_fraction_values, output['mass fraction NXC7H16'].T[:, ::10])
plt.plot(output.mixture_fraction_values, output['mass fraction NXC7H16'].T[:, 0], 'b-')
plt.plot(output.mixture_fraction_values, output['mass fraction NXC7H16'].T[:, -1], 'k-')
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('mass fraction n-heptane')
plt.show()
plt.plot(output.mixture_fraction_values, output['mass fraction OH'].T[:, ::10])
plt.plot(output.mixture_fraction_values, output['mass fraction OH'].T[:, 0], 'b-')
plt.plot(output.mixture_fraction_values, output['mass fraction OH'].T[:, -1], 'k-')
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('mass fraction OH')
plt.show()
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_21_0.png
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_21_1.png
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_21_2.png
Parameter Continuation, Transient Extinction, and Progress Variable Tabulation
------------------------------------------------------------------------------
Now we combine the main ideas from this notebook to generate a steady
and transient extinction trajectory for our n-heptane/air mixture. We’ll
do parameter continuation in the stoichiometric dissipation rate until
we get near extinction, and then we’ll jump the dissipation rate and
capture the transient extinction event. Building atop this, we’ll
transform the steady and transient libraries into a single library built
atop the mixture fraction and the stoichiometric value of a progress
variable chosen as the mass fraction of CO2. This requires the source
term of CO2, which we compute with Cantera, leveraging Spitfire’s
``get_ct_solution_array()`` method.
Below the ``slfm_lib`` variable is made one value of
:math:`\chi_{\rm st}` at a time. As with standard SLFM, the extinction
dynamics are not included in the table.
.. code:: ipython3
chi_values = np.logspace(-3, 2, 17)
fs0 = FlameletSpec(mech_spec=mech,
initial_condition='equilibrium',
oxy_stream=air,
fuel_stream=fuel,
grid_points=64,
stoich_dissipation_rate=chi_values[0])
z_values = Flamelet(fs0).mixfrac_grid
slfm_lib = Library(Dimension('mixture_fraction', z_values),
Dimension('dissipation_rate_stoich', chi_values, log_scaled=True))
slfm_lib['temperature'] = slfm_lib.get_empty_dataset()
slfm_lib['pressure'] = slfm_lib.get_empty_dataset()
for s in mech.species_names:
slfm_lib[f'mass fraction {s}'] = slfm_lib.get_empty_dataset()
slfm_lib.extra_attributes['mech_spec'] = mech
print(f'{"chi_st (Hz)":>12} | {"T_max (K)":<12}')
print('-' * 27)
for idx, chi_st in enumerate(chi_values):
fs = fs0 if idx == 0 else FlameletSpec(library_slice=steady_lib, stoich_dissipation_rate=chi_st)
f = Flamelet(fs)
steady_lib = f.compute_steady_state()
print(f'{chi_st:>12.1e} | {steady_lib["temperature"].max():<12.1f}')
for prop in steady_lib.props:
slfm_lib[prop][:, idx] = steady_lib[prop]
print('-' * 27)
fse = FlameletSpec(library_slice=slfm_lib[:, -1], stoich_dissipation_rate=chi_values[-1] * 10.)
fext = Flamelet(fse)
ext_lib = fext.integrate_to_steady(write_log=True)
.. parsed-literal::
chi_st (Hz) | T_max (K)
---------------------------
1.0e-03 | 2237.9
2.1e-03 | 2233.3
4.2e-03 | 2225.9
8.7e-03 | 2215.1
1.8e-02 | 2200.7
3.7e-02 | 2182.8
7.5e-02 | 2161.6
1.5e-01 | 2138.5
3.2e-01 | 2117.9
6.5e-01 | 2092.6
1.3e+00 | 2069.1
2.7e+00 | 2038.9
5.6e+00 | 2001.7
1.2e+01 | 1961.1
2.4e+01 | 1910.2
4.9e+01 | 1840.0
1.0e+02 | 1729.9
---------------------------
2021-02-25 13:09 : Spitfire running case with method: Kennedy/Carpenter ESDIRK64
|number of | simulation | time step | diff. eqn. | total cpu | cput per |
|time steps | time (s) | size (s) | |residual| | time (s) | step (ms)|
---------------------------------------------------------------------------|
| 100 | 9.69e-06 | 1.28e-07 | 4.25e+04 | 2.52e+00 | 2.52e+01 |
| 200 | 2.29e-05 | 4.89e-07 | 1.95e+04 | 4.51e+00 | 2.25e+01 |
| 300 | 1.22e-04 | 1.95e-06 | 6.35e+02 | 7.60e+00 | 2.53e+01 |
Integration successfully completed!
Statistics:
- number of time steps : 363
- final simulation time: 0.0006048045588230816
- smallest time step : 2.5051492225523748e-08
- average time step : 1.6661282612206103e-06
- largest time step : 3.877850229434712e-05
CPU time
- total (s) : 9.151398e+00
- per step (ms): 2.521046e+01
Nonlinear iterations
- total : 10054
- per step: 27.7
Linear iterations
- total : 10054
- per step : 27.7
- per nliter: 1.0
Jacobian setups
- total : 195
- steps per : 1.9
- nliter per: 51.6
- liter per : 51.6
2021-02-25 13:09 : Spitfire finished in 9.15139817e+00 seconds!
.. code:: ipython3
plt.plot(slfm_lib.mixture_fraction_values, slfm_lib['temperature'], 'b')
plt.plot(ext_lib.mixture_fraction_values, ext_lib['temperature'].T[:, ::18], 'c')
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('temperature (K)')
plt.show()
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_24_0.png
To combine the libraries and prepare for progress variable
identification, we first simply map onto :math:`\chi_{\rm st}(1+t)`,
where :math:`t` is the extinction time, for the second dimension to
ensure uniqueness.
.. code:: ipython3
t_step = 18 # just to reduce the data size a little
t_values_step = ext_lib.time_values[1::t_step]
chi_opt = np.hstack((chi_values, chi_values[-1] *(1. + t_values_step)))
combined_lib = Library(Dimension('mixture_fraction', z_values), Dimension('chi_opt', chi_opt))
for prop in slfm_lib.props:
combined_lib[prop] = combined_lib.get_empty_dataset()
combined_lib[prop][:, :chi_values.size] = slfm_lib[prop][:, :chi_values.size]
combined_lib[prop][:, chi_values.size:] = ext_lib[prop][1::t_step, :].T
plt.plot(combined_lib.mixture_fraction_values, combined_lib['temperature'], 'g')
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('temperature (K)')
plt.show()
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_26_0.png
Now we build one-dimensional interpolation to compute stoichiometric
values of every tabulated property over the combined second dimension.
These will be used to define a progress variable.
.. code:: ipython3
from scipy.interpolate import interp1d
stoich_values = Library(Dimension('chi_opt', chi_opt))
z_st = mech.stoich_mixture_fraction(fuel, air)
for prop in combined_lib.props:
stoich_values[prop] = stoich_values.get_empty_dataset()
stoich_values[prop] = interp1d(combined_lib.mixture_fraction_values,
combined_lib[prop],
axis=0)(z_st)
.. code:: ipython3
for s in ['CO2', 'H2O', 'CO']:
plt.plot(stoich_values[f'temperature'], stoich_values[f'mass fraction {s}'], label=s)
plt.grid()
plt.xlabel('stoich. temperature (K)')
plt.ylabel('stoich. mass fraction')
plt.legend()
plt.show()
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_29_0.png
The above shows that CO2 and H2O, unlike CO, are admissible progress
variables as they vary monotonically from the high-temperature
equilibrium state to the extinguished state. Linear combinations of mass
fractions could be employed, but here we’ll keep things simple and just
use CO2.
.. code:: ipython3
Y_CO2_st = stoich_values[f'mass fraction CO2']
Y_CO2_st_scaled = (Y_CO2_st - Y_CO2_st.min()) / (Y_CO2_st.max() - Y_CO2_st.min())
progvar_lib = Library(Dimension('mixture_fraction', z_values),
Dimension('scaled_st_Y_CO2', Y_CO2_st_scaled))
for prop in combined_lib.props:
progvar_lib[prop] = combined_lib[prop]
.. code:: ipython3
plt.contourf(progvar_lib.mixture_fraction_grid,
progvar_lib.scaled_st_Y_CO2_grid,
progvar_lib['temperature'],
cmap='afmhot')
plt.xlabel('$Z$')
plt.ylabel('$C_{\\rm st}$')
plt.colorbar()
plt.show()
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_32_0.png
A requirement for the FPV tabulation is to tabulate the source term of
the progress variable. While Spitfire computes chemical source terms and
much more in order to solve flamelet problems, the most convenient way
of getting reaction rates and other thermochemical properties is to use
Cantera. For this, ``get_ct_solution_array``, which takes a mechanism
and library, can be used to obtain a ``SolutionArray`` object from
Cantera which acts like a single thermochemical state but loops over a
large number behind the scenes. So we can simply call
``net_production_rates`` to get the molar species production rates, and
then reshape them into the library.
.. code:: ipython3
ct_array, lib_shape = get_ct_solution_array(mech, progvar_lib)
co2_idx = mech.species_index('CO2')
co2_mw = mech.molecular_weight('CO2')
progvar_lib['prod rate CO2'] = co2_mw * ct_array.net_production_rates[:, co2_idx].reshape(lib_shape)
progvar_lib['C source'] = progvar_lib['prod rate CO2'] / (Y_CO2_st.max() - Y_CO2_st.min())
.. code:: ipython3
plt.contourf(progvar_lib.mixture_fraction_grid,
progvar_lib.scaled_st_Y_CO2_grid,
progvar_lib['C source'],
cmap='coolwarm')
plt.colorbar()
plt.xlabel('$Z$')
plt.ylabel('$C_{\\rm st}$')
plt.show()
.. image:: introduction_to_flamelets_files/introduction_to_flamelets_35_0.png
Conclusions
-----------
In this demonstration we’ve covered the basics of specifying a flamelet
model with initialization options, dissipation rate forms, and grid
types. Following this we solved the steady and transient flamelet
equations, ultimately performing parameter continuation to build an SLFM
library, and combined with a transient extinction calculation to build
an FPV library.
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
#include "combustion_kernels.h"
#include "blas_lapack_kernels.h"
#include <cmath>
#include <numeric>
namespace griffon
{
void CombustionKernels::chem_rhs_isobaric(const double &rho, const double &cp, const double *h, const double *w,
double *out_rhs) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
out_rhs[0] = -griffon::blas::inner_product(nSpec, w, h) / (rho * cp);
const double invRho = 1. / rho;
for (int i = 0; i < nSpec - 1; ++i)
{
out_rhs[1 + i] = w[i] * invRho;
}
}
void CombustionKernels::heat_rhs_isobaric(const double &temperature, const double &rho, const double &cp,
const double &fluidTemperature, const double &surfTemperature,
const double &hConv, const double &epsRad, const double &surfaceAreaOverVolume,
double *out_heatTransferRate) const
{
*out_heatTransferRate = surfaceAreaOverVolume / (rho * cp) * (hConv * (fluidTemperature - temperature) + epsRad * 5.67e-8 * (surfTemperature * surfTemperature * surfTemperature * surfTemperature - temperature * temperature * temperature * temperature));
}
void CombustionKernels::mass_rhs_isobaric(const double *y, const double *enthalpies, const double *inflowEnthalpies,
const double &rho, const double &cp, const double *inflowY, const double &tau,
double *out_rhs) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
out_rhs[0] = (inflowEnthalpies[nSpec - 1] - enthalpies[nSpec - 1]) * inflowY[nSpec - 1];
for (int i = 0; i < nSpec - 1; ++i)
{
out_rhs[0] += (inflowEnthalpies[i] - enthalpies[i]) * inflowY[i];
out_rhs[1 + i] = inflowY[i] - y[i];
}
out_rhs[0] /= cp;
const double invTau = 1. / tau;
for (int i = 0; i < nSpec; ++i)
{
out_rhs[i] *= invTau;
}
}
void CombustionKernels::chem_jac_isobaric(const double &pressure, const double &temperature, const double *y,
const double &mmw, const double &rho, const double &cp, const double *cpi,
const double &cpsensT, const double *h, const double *w, const double *wsens,
double *out_rhs, double *out_primJac) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
// out_primJac is an n x (n+1) column-major array
// row i col j is i + j * n
chem_rhs_isobaric(rho, cp, h, w, out_rhs);
const double invRhoCp = 1. / (rho * cp);
const double invRho = 1. / rho;
const double invCp = 1. / cp;
// rho column
out_primJac[0] = -invRhoCp * griffon::blas::inner_product(nSpec, wsens, h) - invRho * out_rhs[0];
for (int i = 0; i < nSpec - 1; ++i)
{
out_primJac[1 + i] = invRho * (wsens[i] - invRho * w[i]);
}
// T column
out_primJac[nSpec] = -invRhoCp * (griffon::blas::inner_product(nSpec, &wsens[nSpec + 1], h) + griffon::blas::inner_product(nSpec, w, cpi)) - out_rhs[0] * cpsensT * invCp;
for (int i = 0; i < nSpec - 1; ++i)
{
out_primJac[nSpec + 1 + i] = wsens[nSpec + 1 + i] * invRho;
}
// Yk column
const double cpn = cpi[nSpec - 1];
for (int k = 0; k < nSpec - 1; ++k)
{
const int firstRow = (2 + k) * nSpec;
out_primJac[firstRow] = -invRhoCp * griffon::blas::inner_product(nSpec, &wsens[(2 + k) * (nSpec + 1)], h) - out_rhs[0] * (cpi[k] - cpn) * invCp;
for (int i = 0; i < nSpec; ++i)
{
out_primJac[firstRow + 1 + i] = invRho * wsens[(2 + k) * (nSpec + 1) + i];
}
}
}
void CombustionKernels::mass_jac_isobaric(const double &pressure, const double &temperature, const double *y,
const double &rho, const double &cp, const double &cpsensT, const double *cpi,
const double *enthalpies, const double *inflowEnthalpies,
const double &inflowTemperature, const double *inflowY, const double &tau,
double *out_rhs, double *out_primJac) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
// out_primJac is an n x (n+1) column-major array
// row i col j is i + j * n
mass_rhs_isobaric(y, enthalpies, inflowEnthalpies, rho, cp, inflowY, tau, out_rhs);
const double invCp = 1. / cp;
const double invTau = 1. / tau;
// rho column
for (int i = 0; i < nSpec; ++i)
{
out_primJac[i] = 0.;
}
// T column
out_primJac[nSpec] = -invCp * (cpsensT * out_rhs[0] + invTau * griffon::blas::inner_product(nSpec, inflowY, cpi));
double *Tcolp1 = &out_primJac[nSpec + 1];
for (int i = 0; i < nSpec - 1; ++i)
{
Tcolp1[i] = 0.;
}
// Yk column
for (int k = 0; k < nSpec - 1; ++k)
{
out_primJac[(2 + k) * nSpec] = -out_rhs[0] * (cpi[k] - cpi[nSpec - 1]) * invCp;
double *Ykcolp1 = &out_primJac[(2 + k) * nSpec + 1];
for (int i = 0; i < nSpec - 1; ++i)
{
Ykcolp1[i] = 0.;
}
out_primJac[(2 + k) * nSpec + 1 + k] = -invTau;
}
}
void CombustionKernels::heat_jac_isobaric(const double &temperature, const double &rho, const double &cp,
const double &cpsensT, const double *cpi, const double &convectionTemperature,
const double &radiationTemperature, const double &convectionCoefficient,
const double &radiativeEmissivity, const double &surfaceAreaOverVolume,
double *out_heatTransferRate, double *out_heatTransferRatePrimJac) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
heat_rhs_isobaric(temperature, rho, cp, convectionTemperature, radiationTemperature, convectionCoefficient,
radiativeEmissivity, surfaceAreaOverVolume, out_heatTransferRate);
const double invRhoCp = 1. / (rho * cp);
const double invCp = 1. / cp;
// rho column
out_heatTransferRatePrimJac[0] = -*out_heatTransferRate / rho;
// T column
out_heatTransferRatePrimJac[1] = -invCp * cpsensT * *out_heatTransferRate - surfaceAreaOverVolume * invRhoCp * (convectionCoefficient + 4. * radiativeEmissivity * 5.67e-8 * temperature * temperature * temperature);
// Yk column
double *Yksens = &out_heatTransferRatePrimJac[2];
const double cpn = cpi[nSpec - 1];
for (int k = 0; k < nSpec - 1; ++k)
{
Yksens[k] = invCp * *out_heatTransferRate * (cpn - cpi[k]);
}
}
void CombustionKernels::reactor_rhs_isobaric(const double *state, const double &pressure, const double &inflowTemperature,
const double *inflowY, const double &tau, const double &fluidTemperature,
const double &surfTemperature, const double &hConv, const double &epsRad,
const double &surfaceAreaOverVolume, const int heatTransferOption,
const bool open, double *out_rhs) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
double rho;
double heatTransferRate;
double enthalpies[nSpec];
double w[nSpec];
const double temperature = state[0];
double y[nSpec];
extract_y(&state[1], nSpec, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_density(pressure, temperature, mmw, &rho);
const double cp = cp_mix(temperature, y);
species_enthalpies(temperature, enthalpies);
production_rates(temperature, rho, mmw, y, w);
chem_rhs_isobaric(rho, cp, enthalpies, w, out_rhs);
if (open)
{
double massRhs[nSpec];
double inflowEnthalpies[nSpec];
species_enthalpies(inflowTemperature, inflowEnthalpies);
mass_rhs_isobaric(y, enthalpies, inflowEnthalpies, rho, cp, inflowY, tau, massRhs);
for (int i = 0; i < nSpec; ++i)
{
out_rhs[i] += massRhs[i];
}
}
switch (heatTransferOption)
{
case 0: // adiabatic
break;
case 1: // isothermal
out_rhs[0] = 0.;
break;
case 2: // diathermal
heat_rhs_isobaric(temperature, rho, cp, fluidTemperature, surfTemperature, hConv, epsRad, surfaceAreaOverVolume,
&heatTransferRate);
out_rhs[0] += heatTransferRate;
break;
}
}
void CombustionKernels::reactor_jac_isobaric(const double *state, const double &pressure, const double &inflowTemperature,
const double *inflowY, const double &tau, const double &fluidTemperature,
const double &surfTemperature, const double &hConv, const double &epsRad,
const double &surfaceAreaOverVolume, const int heatTransferOption,
const bool open, const int rates_sensitivity_option,
const int sensitivity_transform_option, double *out_rhs,
double *out_jac) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
// out_jac is an n x n column-major array
// row i col j is i + j * n
double rho;
double cp;
double cpsensT;
double cpi[nSpec];
double cpisensT[nSpec];
double enthalpies[nSpec];
double w[nSpec];
double wsens[(nSpec + 1) * (nSpec + 1)];
double primJac[nSpec * (nSpec + 1)];
double heatTransferRate;
double heatTrasferRatePrimJac[nSpec + 1];
const double temperature = state[0];
double y[nSpec];
extract_y(&state[1], nSpec, y);
const double mmw = mixture_molecular_weight(y);
ideal_gas_density(pressure, temperature, mmw, &rho);
cp_mix_and_species(temperature, y, &cp, cpi);
species_enthalpies(temperature, enthalpies);
cp_sens_T(temperature, y, &cpsensT, cpisensT);
switch (rates_sensitivity_option)
{
case 1:
prod_rates_sens_no_tbaf(temperature, rho, mmw, y, w, wsens);
break;
case 0:
prod_rates_sens_exact(temperature, rho, mmw, y, w, wsens);
break;
case 2:
prod_rates_sens_sparse(temperature, rho, mmw, y, w, wsens);
break;
}
chem_jac_isobaric(pressure, temperature, y, mmw, rho, cp, cpi, cpsensT, enthalpies, w, wsens, out_rhs, primJac);
if (open)
{
double massRhs[nSpec];
double massPrimJac[nSpec * (nSpec + 1)];
double inflowEnthalpies[nSpec];
species_enthalpies(inflowTemperature, inflowEnthalpies);
mass_jac_isobaric(pressure, temperature, y, rho, cp, cpsensT, cpi, enthalpies, inflowEnthalpies,
inflowTemperature, inflowY, tau, massRhs, massPrimJac);
for (int i = 0; i < nSpec * (nSpec + 1); ++i)
{
primJac[i] += massPrimJac[i];
}
for (int i = 0; i < nSpec; ++i)
{
out_rhs[i] += massRhs[i];
}
}
switch (heatTransferOption)
{
case 0: // adiabatic
break;
case 1: // isothermal
for (int k = 0; k < nSpec + 1; ++k)
{
primJac[k * nSpec] = 0.;
}
out_rhs[0] = 0.;
break;
case 2: // diathermal
heat_jac_isobaric(temperature, rho, cp, cpsensT, cpi, fluidTemperature, surfTemperature, hConv, epsRad,
surfaceAreaOverVolume, &heatTransferRate, heatTrasferRatePrimJac);
for (int k = 0; k < nSpec + 1; ++k)
{
primJac[k * nSpec] += heatTrasferRatePrimJac[k];
}
out_rhs[0] += heatTransferRate;
break;
}
switch (sensitivity_transform_option)
{
case 0:
transform_isobaric_primitive_jacobian(rho, pressure, temperature, mmw, primJac, out_jac);
break;
}
}
void CombustionKernels::transform_isobaric_primitive_jacobian(const double &rho, const double &pressure,
const double &temperature, const double &mmw,
const double *primJac, double *out_jac) const
{
const int nSpec = mechanismData.phaseData.nSpecies;
const auto &invMolecularWeights = mechanismData.phaseData.inverseMolecularWeights;
for (int i = 0; i < nSpec * nSpec; ++i)
out_jac[i] = 0.;
const double roT = rho / temperature;
for (int i = 0; i < nSpec; ++i)
{
out_jac[i] = primJac[nSpec + i] - roT * primJac[i];
}
const double negRhoMmw = -rho * mmw;
for (int k = 0; k < nSpec - 1; ++k)
{
for (int i = 0; i < nSpec; ++i)
{
out_jac[(1 + k) * nSpec + i] = primJac[(2 + k) * nSpec + i] + negRhoMmw * (invMolecularWeights[k] - invMolecularWeights[nSpec - 1]) * primJac[i];
}
}
}
} // namespace griffon
<file_sep>"""
This module contains time stepping methods that represent distinct methods of taking a single step in the time integration loop.
Some are explicit, some are implicit.
Some allow adaptive time stepping via control of embedded temporal error estimates while most do not.
Consider a general purpose explicit ODE,
.. math::
\\frac{\\partial \\boldsymbol{q}}{\\partial t} = \\boldsymbol{r}(t, \\boldsymbol{q}),
where :math:`\\boldsymbol{q}=[q_1,q_2,\\ldots]` is the vector of state variables
and :math:`\\boldsymbol{r}=[r_1,r_2,\\ldots]` is the vector of right-hand side functions.
The classes in this module have a ``single_step(q, t, h, r, ...)`` method that steps from time level :math:`t^n` to
the next time, :math:`t^{n+1}=t^n + h`, given a state :math:`q^n` and right-hand side function :math:`r(t,q)`.
For example, the forward Euler method with class ``ForwardEuler`` computes this as :math:`q^{n+1}=q^n + hr(t^n,q^n)`.
In Spitfire's unit testing we verify the order of accuracy of most of these methods.
If you add a new one be sure to add it to the unit tester.
See the file: ``tests/time/test_time_order_of_accuracy.py``.
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
from numpy import sqrt, copy, array, sum, Inf, zeros_like
from scipy.linalg import norm
class TimeStepperBase:
"""Read-only base class for all time stepping methods
**Constructor**: build a StepOutput object, specifying all data here (the object will be read-only)
Parameters
----------
name : str
the name of the method
order : int
the order of the method
is_adaptive : bool
whether or not the method computes embedded error estimates to enable adaptive time-stepping
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
is_implicit : bool
whether or not the method is implicit
nonlinear_solver : int
the nonlinear solver used by an implicit method at each time step
implicit_coefficient : list[float]
the coefficient in the implicit method that pre-multiplies the Jacobian matrix in the linear system
"""
__slots__ = ['name',
'order',
'n_stages',
'is_adaptive',
'norm_weighting',
'norm_order',
'is_implicit',
'nonlinear_solver',
'implicit_coefficient']
def __init__(self, name, order, **kwargs):
self.name = name
self.order = order
self.n_stages = kwargs['n_stages'] if 'n_stages' in kwargs else 1
self.is_adaptive = kwargs['is_adaptive'] if 'is_adaptive' in kwargs else False
self.norm_weighting = kwargs['norm_weighting'] if 'norm_weighting' in kwargs else 1.
self.norm_order = kwargs['norm_order'] if 'norm_order' in kwargs else Inf
self.is_implicit = kwargs['is_implicit'] if 'is_implicit' in kwargs else False
self.nonlinear_solver = kwargs['nonlinear_solver'] if 'nonlinear_solver' in kwargs else None
self.implicit_coefficient = kwargs['implicit_coefficient'] if 'implicit_coefficient' in kwargs else None
def norm(self, x):
return norm(x * self.norm_weighting, ord=self.norm_order)
class StepOutput:
"""Read-only class that holds information about the result of a single time step.
**Constructor**: build a StepOutput object, specifying all data here (the object will be read-only)
Parameters
----------
solution_update : np.ndarray
the update to the solution, the state at the next time level minus that at the current time level
temporal_error : float
the temporal error estimate - for adaptive time stepping through classical error control
nonlinear_iter : int
how many nonlinear iterations the step required - implicit methods only
linear_iter : int
how many linear iterations the step required - implicit methods only
nonlinear_converged : bool
whether or not the nonlinear solver converged - implicit methods only
slow_nonlinear_convergence : bool
whether or not the nonlinear solver detected slow convergence - implicit methods only
projector_setups : int
the number of times the linear system was set up (e.g. Jacobian evaluation-factorization)
extra_errors : list[float]
a list of additional embedded temporal error estimates - for adaptive time stepping through new ratio control
"""
__slots__ = ['solution_update',
'temporal_error',
'nonlinear_iter',
'linear_iter',
'nonlinear_converged',
'slow_nonlinear_convergence',
'projector_setups',
'extra_errors']
def __init__(self, **kwargs):
for slot in self.__slots__:
self.__setattr__(slot, kwargs[slot] if slot in kwargs else None)
self.temporal_error = -1. if self.temporal_error is None else self.temporal_error
class ForwardEulerS1P1(TimeStepperBase):
def __init__(self):
super().__init__(name='forward Euler', order=1, n_stages=1)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
return StepOutput(solution_update=dt * rhs(t, state))
class ExpMidpointS2P2(TimeStepperBase):
def __init__(self):
super().__init__(name='ERK2 midpoint', order=2, n_stages=2)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
return StepOutput(solution_update=rhs(t + 0.5 * dt, state + 0.5 * dt * rhs(t, state)) * dt)
class ExpRalstonS2P2(TimeStepperBase):
def __init__(self):
super().__init__(name='ERK2 Ralston', order=2, n_stages=2)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
k1 = rhs(t, state)
return StepOutput(solution_update=0.25 * (k1 + 3. * rhs(t + 2. / 3. * dt, state + 2. / 3. * dt * k1)) * dt)
class ExpTrapezoidalS2P2Q1(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
def __init__(self, norm_weighting=1., norm_order=Inf):
super().__init__(name='ERK2 trapezoidal', order=2, n_stages=2,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
k1 = rhs(t, state)
r2 = 0.5 * (rhs(t + dt, state + dt * k1) + k1)
return StepOutput(solution_update=dt * r2, temporal_error=dt * self.norm(r2 - k1))
class RK3KuttaS3P3(TimeStepperBase):
def __init__(self):
super().__init__(name='ERK3 Kutta', order=3, n_stages=3)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
k1 = rhs(t, state)
k2 = rhs(t + 0.5 * dt, state + 0.5 * dt * k1)
k3 = rhs(t + 1.0 * dt, state + dt * (2.0 * k2 - k1))
return StepOutput(solution_update=1. / 6. * (k1 + k3 + 4. * k2) * dt)
class BogackiShampineS4P3Q2(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
def __init__(self, norm_weighting=1., norm_order=Inf):
super().__init__(name='ERK4 Bogacki-Shampine', order=3, n_stages=4,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
k1 = rhs(t, state)
k2 = rhs(t + 0.5 * dt, state + 0.5 * dt * k1)
k3 = rhs(t + 0.75 * dt, state + 0.75 * dt * k2)
r1 = 1. / 9. * (2. * k1 + 3. * k2 + 4. * k3)
k4 = rhs(t + dt, state + dt * r1)
r2 = (7. * k1 + 6. * k2 + 8. * k3 + 3. * k4) / 24.
return StepOutput(solution_update=dt * r1, temporal_error=dt * self.norm(r2 - r1))
class RK4ClassicalS4P4(TimeStepperBase):
def __init__(self):
super().__init__(name='ERK4 classical', order=4, n_stages=4)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
k1 = rhs(t, state)
k2 = rhs(t + 0.5 * dt, state + 0.5 * dt * k1)
k3 = rhs(t + 0.5 * dt, state + 0.5 * dt * k2)
k4 = rhs(t + dt, state + dt * k3)
return StepOutput(solution_update=1. / 6. * (k1 + k4 + 2. * (k2 + k3)) * dt)
class CashKarpS6P5Q4(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
def __init__(self, norm_weighting=1., norm_order=Inf):
super().__init__(name='Cash/Karp RK5', order=5, n_stages=6,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
q = state
r = rhs
d = dt
k1 = r(t, q)
k2 = r(t + 0.2 * d, q + 0.2 * d * k1)
k3 = r(t + 0.3 * d, q + 0.025 * d * (3. * k1 + 9. * k2))
k4 = r(t + 0.6 * d, q + 0.1 * d * (3. * k1 - 9. * k2 + 12. * k3))
k5 = r(t + 1.0 * d, q + 1. / 54. * d * (-11. * k1 + 135. * k2 - 140. * k3 + 70. * k4))
k6 = r(t + 7. / 8. * d,
q + 1. / 110592. * d * (3262. * k1 + 3.78e4 * k2 + 4.6e3 * k3 + 44275. * k4 + 6831. * k5))
r4 = 2825. / 27648. * k1 + 18575. / 48384. * k3 + 13525. / 55296. * k4 + 277. / 14336. * k5 + 0.25 * k6
r5 = 37. / 378. * k1 + 250. / 621. * k3 + 125. / 594. * k4 + 512. / 1771. * k6
return StepOutput(solution_update=d * r5, temporal_error=d * self.norm(r5 - r4))
class ZonneveldS5P4Q3(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
def __init__(self, norm_weighting=1., norm_order=Inf):
super().__init__(name='Zonneveld RK4', order=4, n_stages=5,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
q = state
r = rhs
d = dt
k1 = r(t, q)
k2 = r(t + 0.5 * d, q + 0.5 * d * k1)
k3 = r(t + 0.5 * d, q + 0.5 * d * k2)
k4 = r(t + d, q + d * k3)
k5 = r(t + 0.75 * d, q + 1. / 32. * d * (5. * k1 + 7. * k2 + 13. * k3 - k4))
r1 = (k1 + k4 + 2. * (k2 + k3)) / 6.
r2 = (-3. * k1 + 14. * (k2 + k3) + 13. * k4 - 32. * k5) / 6.
return StepOutput(solution_update=d * r1, temporal_error=d * self.norm(r1 - r2))
class ExpKennedyCarpetnerS6P4Q3(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
def __init__(self, norm_weighting=1., norm_order=Inf):
super().__init__(name='Kennedy/Carpenter explicit RK4', order=4, n_stages=6,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
q = state
r = rhs
d = dt
k1 = r(t, q)
k2 = r(t + 0.5 * d, q + 0.5 * d * k1)
k3 = r(t + 83. / 250. * d, q + d / 62500. * (13861. * k1 + 6889. * k2))
k4 = r(t + 31. / 50. * d, q + d * (9408046702089. / 11113171139209. * k3 -
116923316275. / 2393684061468. * k1 -
2731218467317. / 15368042101831. * k2))
k5 = r(t + 17. / 20. * d, q + d * (-451086348788. / 2902428689909. * k1 +
-2682348792572. / 7519795681897. * k2 +
12662868775082. / 11960479115383. * k3 +
3355817975965. / 11060851509271. * k4))
k6 = r(t + d, q + d * (647845179188. / 3216320057751. * k1 +
73281519250. / 8382639484533. * k2 +
552539513391. / 3454668386233. * k3 +
3354512671639. / 8306763924573. * k4 +
4040. / 17871. * k5))
r1 = (82889. / 524892. * k1 +
15625. / 83664. * k3 +
69875. / 102672. * k4 -
2260. / 8211. * k5 +
0.25 * k6)
r2 = (4586570599. / 29645900160. * k1 +
178811875. / 945068544. * k3 +
814220225. / 1159782912. * k4 -
3700637. / 11593932. * k5 +
61727. / 225920. * k6)
return StepOutput(solution_update=d * r1, temporal_error=d * self.norm(r1 - r2))
class BackwardEulerS1P1Q1(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
nonlinear_solver : spitfire.time.nonlinear.NonlinearSolver
the solver used in each implicit stage
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
def __init__(self, nonlinear_solver, norm_weighting=1., norm_order=Inf):
super().__init__(name='backward Euler', order=1, n_stages=1,
is_implicit=True, implicit_coefficient=1., nonlinear_solver=nonlinear_solver,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
def single_step(self, state, t, dt, rhs, lhs_setup, lhs_solve, *args, **kwargs):
state_n = copy(state)
def residual(state_arg, existing_rhs=None, evaluate_new_rhs=True):
rhs_val = rhs(t + dt, state_arg) if evaluate_new_rhs else existing_rhs
return dt * rhs_val - (state_arg - state_n), rhs_val
def linear_setup(state_arg):
lhs_setup(t + dt, state_arg)
max_nliter = self.nonlinear_solver.max_nonlinear_iter
self.nonlinear_solver.max_nonlinear_iter = 1
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=rhs(t + dt, state))
state_predictor = output.solution
nonlinear_iter = output.iter
linear_iter = output.liter
projector_setups = output.projector_setups
self.nonlinear_solver.max_nonlinear_iter = max_nliter
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=output.rhs_at_converged)
nonlinear_iter += output.iter
linear_iter += output.liter
projector_setups += output.projector_setups
return StepOutput(solution_update=output.solution - state,
temporal_error=self.norm(output.solution - state_predictor),
nonlinear_iter=output.iter,
linear_iter=output.liter,
nonlinear_converged=output.converged,
slow_nonlinear_convergence=output.slow_convergence,
projector_setups=output.projector_setups)
class CrankNicolsonS2P2(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
nonlinear_solver : spitfire.time.nonlinear.NonlinearSolver
the solver used in each implicit stage
"""
def __init__(self, nonlinear_solver):
super().__init__(name='<NAME>', order=2, n_stages=2,
is_implicit=True, implicit_coefficient=0.5, nonlinear_solver=nonlinear_solver)
def single_step(self, state, t, dt, rhs, lhs_setup, lhs_solve, *args, **kwargs):
state_n = copy(state)
rhs_n = rhs(t, state_n)
def residual(state_arg, existing_rhs=None, evaluate_new_rhs=True):
rhs_val = rhs(t + dt, state_arg) if evaluate_new_rhs else existing_rhs
return 0.5 * dt * (rhs_val + rhs_n) - (state_arg - state_n), rhs_val
def linear_setup(state_arg):
lhs_setup(t + dt, state_arg)
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=rhs(t + dt, state))
return StepOutput(solution_update=output.solution - state,
nonlinear_iter=output.iter,
linear_iter=output.liter,
nonlinear_converged=output.converged,
slow_nonlinear_convergence=output.slow_convergence,
projector_setups=output.projector_setups)
class KennedyCarpenterS6P4Q3(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
nonlinear_solver : spitfire.time.nonlinear.NonlinearSolver
the solver used in each implicit stage
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
__slots__ = ['gamma', 'a21', 'a31', 'a32', 'a41', 'a42', 'a43', 'a51', 'a52', 'a53', 'a54',
'a61', 'a62', 'a63', 'a64', 'a65',
'b1', 'b2', 'b3', 'b4', 'b5', 'b6',
'b1h', 'b2h', 'b3h', 'b4h', 'b5h', 'b6h', 'A', 'c']
def __init__(self, nonlinear_solver, norm_weighting=1., norm_order=Inf):
super().__init__(name='Kennedy/Carpenter ESDIRK64', order=4, n_stages=6,
is_implicit=True, implicit_coefficient=0.25, nonlinear_solver=nonlinear_solver,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
self.gamma = 0.25
self.a21 = 0.25
self.a31 = 8611. / 62500.
self.a32 = -1743. / 31250.
self.a41 = 5012029. / 34652500.
self.a42 = -654441. / 2922500.
self.a43 = 174375. / 388108.
self.a51 = 15267082809. / 155376265600.
self.a52 = -71443401. / 120774400.
self.a53 = 730878875. / 902184768.
self.a54 = 2285395. / 8070912.
self.a61 = 82889. / 524892.
self.a62 = 0.
self.a63 = 15625. / 83664.
self.a64 = 69875. / 102672.
self.a65 = -2260. / 8211.
self.b1 = self.a61
self.b2 = self.a62
self.b3 = self.a63
self.b4 = self.a64
self.b5 = self.a65
self.b6 = self.gamma
self.b1h = 4586570599. / 29645900160.
self.b2h = 0.
self.b3h = 178811875. / 945068544.
self.b4h = 814220225. / 1159782912.
self.b5h = -3700637. / 11593932.
self.b6h = 61727. / 225920.
self.A = array([[0., 0., 0., 0., 0., 0.],
[self.a21, self.gamma, 0., 0., 0., 0.],
[self.a31, self.a32, self.gamma, 0., 0., 0.],
[self.a41, self.a42, self.a43, self.gamma, 0., 0.],
[self.a51, self.a52, self.a53, self.a54, self.gamma, 0.],
[self.a61, self.a62, self.a63, self.a64, self.a65, self.gamma]])
self.c = sum(self.A, axis=1)
def single_step(self, state, t, dt, rhs, lhs_setup, lhs_solve, *args, **kwargs):
nonlinear_iter = 0
linear_iter = 0
nonlinear_converged = True
slow_nonlinear_convergence = False
projector_setups = 0
current_c_value = None
prior_stage_k = None
state_n = copy(state)
def residual(state_arg, existing_rhs=None, evaluate_new_rhs=True):
rhs_val = rhs(t + current_c_value * dt, state_arg) if evaluate_new_rhs else existing_rhs
return dt * (self.gamma * rhs_val + prior_stage_k) - (state_arg - state_n), rhs_val
def linear_setup(state_arg):
lhs_setup(t + current_c_value * dt, state_arg)
# stage 1
k1 = rhs(t, state)
prior_stage_k = self.a21 * k1
current_c_value = self.c[1]
# stage 2
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k1)
state = output.solution
k2 = output.rhs_at_converged
prior_stage_k = self.a32 * k2 + self.a31 * k1
current_c_value = self.c[2]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 3
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k2)
state = output.solution
k3 = output.rhs_at_converged
prior_stage_k = self.a43 * k3 + self.a42 * k2 + self.a41 * k1
current_c_value = self.c[3]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 4
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k3)
state = output.solution
k4 = output.rhs_at_converged
prior_stage_k = self.a54 * k4 + self.a53 * k3 + self.a52 * k2 + self.a51 * k1
current_c_value = self.c[4]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 5
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k4)
state = output.solution
k5 = output.rhs_at_converged
prior_stage_k = self.a65 * k5 + self.a64 * k4 + self.a63 * k3 + self.a62 * k2 + self.a61 * k1
current_c_value = self.c[5]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 6
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k5)
k6 = output.rhs_at_converged
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# accumulation
dstate = dt * (self.b1 * k1 + self.b2 * k2 + self.b3 * k3 + self.b4 * k4 + self.b5 * k5 + self.b6 * k6)
dstate_h = dt * (self.b1h * k1 + self.b2h * k2 + self.b3h * k3 + self.b4h * k4 + self.b5h * k5 + self.b6h * k6)
return StepOutput(solution_update=dstate,
temporal_error=self.norm(dstate - dstate_h),
nonlinear_iter=nonlinear_iter,
linear_iter=linear_iter,
nonlinear_converged=nonlinear_converged,
slow_nonlinear_convergence=slow_nonlinear_convergence,
projector_setups=projector_setups)
class KvaernoS4P3Q2(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
nonlinear_solver : spitfire.time.nonlinear.NonlinearSolver
the solver used in each implicit stage
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
__slots__ = ['gamma', 'a21', 'a31', 'a32', 'a41', 'a42', 'a43',
'b1', 'b2', 'b3', 'b4',
'b1h', 'b2h', 'b3h', 'b4h', 'A', 'c']
def __init__(self, nonlinear_solver, norm_weighting=1., norm_order=Inf):
super().__init__(name='<NAME>', order=3, n_stages=4,
is_implicit=True, implicit_coefficient=0.4358665215, nonlinear_solver=nonlinear_solver,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
self.gamma = 0.4358665215
self.a21 = 0.4358665215
self.a31 = 0.490563388419108
self.a32 = 0.073570090080892
self.a41 = 0.308809969973036
self.a42 = 1.490563388254106
self.a43 = -1.235239879727145
self.b1 = self.a41
self.b2 = self.a42
self.b3 = self.a43
self.b4 = self.gamma
self.b1h = 0.490563388419108
self.b2h = 0.073570090080892
self.b3h = 0.4358665215
self.b4h = 0.
self.A = array([[0., 0., 0., 0.],
[self.a21, self.gamma, 0., 0.],
[self.a31, self.a32, self.gamma, 0.],
[self.a41, self.a42, self.a43, self.gamma], ])
self.c = sum(self.A, axis=1)
def single_step(self, state, t, dt, rhs, lhs_setup, lhs_solve, *args, **kwargs):
nonlinear_iter = 0
linear_iter = 0
nonlinear_converged = True
slow_nonlinear_convergence = False
projector_setups = 0
current_c_value = None
prior_stage_k = None
state_n = copy(state)
def residual(state_arg, existing_rhs=None, evaluate_new_rhs=True):
rhs_val = rhs(t + current_c_value * dt, state_arg) if evaluate_new_rhs else existing_rhs
return dt * (self.gamma * rhs_val + prior_stage_k) - (state_arg - state_n), rhs_val
def linear_setup(state_arg):
lhs_setup(t + current_c_value * dt, state_arg)
# stage 1
k1 = rhs(t, state)
prior_stage_k = self.a21 * k1
current_c_value = self.c[1]
# stage 2
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k1)
state = output.solution
k2 = output.rhs_at_converged
prior_stage_k = self.a32 * k2 + self.a31 * k1
current_c_value = self.c[2]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 3
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k2)
state = output.solution
k3 = output.rhs_at_converged
prior_stage_k = self.a43 * k3 + self.a42 * k2 + self.a41 * k1
current_c_value = self.c[3]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 4
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k3)
state = output.solution
k4 = output.rhs_at_converged
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# accumulation
dstate = dt * (self.b1 * k1 + self.b2 * k2 + self.b3 * k3 + self.b4 * k4)
dstate_h = dt * (self.b1h * k1 + self.b2h * k2 + self.b3h * k3 + self.b4h * k4)
return StepOutput(solution_update=dstate,
temporal_error=self.norm(dstate - dstate_h),
nonlinear_iter=nonlinear_iter,
linear_iter=linear_iter,
nonlinear_converged=nonlinear_converged,
slow_nonlinear_convergence=slow_nonlinear_convergence,
projector_setups=projector_setups)
class KennedyCarpenterS4P3Q2(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
nonlinear_solver : spitfire.time.nonlinear.NonlinearSolver
the solver used in each implicit stage
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
__slots__ = ['gamma', 'a21', 'a31', 'a32', 'a41', 'a42', 'a43',
'b1', 'b2', 'b3', 'b4',
'b1h', 'b2h', 'b3h', 'b4h', 'A', 'c']
def __init__(self, nonlinear_solver, norm_weighting=1., norm_order=Inf):
super().__init__(name='Kennedy/Carpenter ESDIRK43', order=3, n_stages=4,
is_implicit=True, implicit_coefficient=1767732205903. / 4055673282236.,
nonlinear_solver=nonlinear_solver,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
self.gamma = 1767732205903. / 4055673282236.
self.a21 = self.gamma
self.a31 = 2746238789719. / 10658868560708.
self.a32 = -640167445237. / 6845629431997.
self.a41 = 1471266399579. / 7840856788654.
self.a42 = -4482444167858. / 7529755066697.
self.a43 = 11266239266428. / 11593286722821.
self.b1 = self.a41
self.b2 = self.a42
self.b3 = self.a43
self.b4 = self.gamma
self.b1h = 2756255671327. / 12835298489170.
self.b2h = -10771552573575. / 22201958757719.
self.b3h = 9247589265047. / 10645013368117.
self.b4h = 2193209047091. / 5459859503100.
self.A = array([[0., 0., 0., 0.],
[self.a21, self.gamma, 0., 0.],
[self.a31, self.a32, self.gamma, 0.],
[self.a41, self.a42, self.a43, self.gamma], ])
self.c = sum(self.A, axis=1)
def single_step(self, state, t, dt, rhs, lhs_setup, lhs_solve, *args, **kwargs):
nonlinear_iter = 0
linear_iter = 0
nonlinear_converged = True
slow_nonlinear_convergence = False
projector_setups = 0
current_c_value = None
prior_stage_k = None
state_n = copy(state)
def residual(state_arg, existing_rhs=None, evaluate_new_rhs=True):
rhs_val = rhs(t + current_c_value * dt, state_arg) if evaluate_new_rhs else existing_rhs
return dt * (self.gamma * rhs_val + prior_stage_k) - (state_arg - state_n), rhs_val
def linear_setup(state_arg):
lhs_setup(t + current_c_value * dt, state_arg)
# stage 1
k1 = rhs(t, state)
prior_stage_k = self.a21 * k1
current_c_value = self.c[1]
# stage 2
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k1)
state = output.solution
k2 = output.rhs_at_converged
prior_stage_k = self.a32 * k2 + self.a31 * k1
current_c_value = self.c[2]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 3
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k2)
state = output.solution
k3 = output.rhs_at_converged
prior_stage_k = self.a43 * k3 + self.a42 * k2 + self.a41 * k1
current_c_value = self.c[3]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 4
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k3)
state = output.solution
k4 = output.rhs_at_converged
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# accumulation
dstate = dt * (self.b1 * k1 + self.b2 * k2 + self.b3 * k3 + self.b4 * k4)
dstate_h = dt * (self.b1h * k1 + self.b2h * k2 + self.b3h * k3 + self.b4h * k4)
return StepOutput(solution_update=dstate,
temporal_error=self.norm(dstate - dstate_h),
nonlinear_iter=nonlinear_iter,
linear_iter=linear_iter,
nonlinear_converged=nonlinear_converged,
slow_nonlinear_convergence=slow_nonlinear_convergence,
projector_setups=projector_setups)
class KennedyCarpenterS8P5Q4(TimeStepperBase):
"""
**Constructor**:
Parameters
----------
nonlinear_solver : spitfire.time.nonlinear.NonlinearSolver
the solver used in each implicit stage
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
__slots__ = ['gamma', 'a21', 'a31', 'a32', 'a41', 'a42', 'a43', 'a51', 'a52', 'a53', 'a54',
'a61', 'a62', 'a63', 'a64', 'a65',
'a71', 'a72', 'a73', 'a74', 'a75', 'a76',
'a81', 'a82', 'a83', 'a84', 'a85', 'a86', 'a87',
'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8',
'b1h', 'b2h', 'b3h', 'b4h', 'b5h', 'b6h', 'b7h', 'b8h', 'A', 'c']
def __init__(self, nonlinear_solver, norm_weighting=1., norm_order=Inf):
super().__init__(name='Kennedy/Carpenter ESDIRK85', order=5, n_stages=8,
is_implicit=True, implicit_coefficient=41. / 200., nonlinear_solver=nonlinear_solver,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
self.gamma = 41. / 200.
self.a21 = 41. / 200.
self.a31 = 41. / 400.
self.a32 = -567603406766. / 11931857230679.
self.a41 = 683785636431. / 9252920307686.
self.a42 = 0.
self.a43 = -110385047103. / 1367015193373.
self.a51 = 3016520224154. / 10081342136671.
self.a52 = 0.
self.a53 = 30586259806659. / 12414158314087.
self.a54 = -22760509404356. / 11113319521817.
self.a61 = 218866479029. / 1489978393911.
self.a62 = 0.
self.a63 = 638256894668. / 5436446318841.
self.a64 = -1179710474555. / 5321154724896.
self.a65 = -60928119172. / 8023461067671.
self.a71 = 1020004230633. / 5715676835656.
self.a72 = 0.
self.a73 = 25762820946817. / 25263940353407.
self.a74 = -2161375909145. / 9755907335909.
self.a75 = -211217309593. / 5846859502534.
self.a76 = -4269925059573. / 7827059040749.
self.a81 = -872700587467. / 9133579230613.
self.a82 = 0.
self.a83 = 0.
self.a84 = 22348218063261. / 9555858737531.
self.a85 = -1143369518992. / 8141816002931.
self.a86 = -39379526789629. / 19018526304540.
self.a87 = 32727382324388. / 42900044865799.
self.b1 = self.a81
self.b2 = self.a82
self.b3 = self.a83
self.b4 = self.a84
self.b5 = self.a85
self.b6 = self.a86
self.b7 = self.a87
self.b8 = self.gamma
self.b1h = -975461918565. / 9796059967033.
self.b2h = 0.
self.b3h = 0.
self.b4h = 78070527104295. / 32432590147079.
self.b5h = -548382580838. / 3424219808633.
self.b6h = -33438840321285. / 15594753105479.
self.b7h = 3629800801594. / 4656183773603.
self.b8h = 4035322873751. / 18575991585200.
self.A = array([[0., 0., 0., 0., 0., 0., 0., 0.],
[self.a21, self.gamma, 0., 0., 0., 0., 0., 0.],
[self.a31, self.a32, self.gamma, 0., 0., 0., 0., 0.],
[self.a41, self.a42, self.a43, self.gamma, 0., 0., 0., 0.],
[self.a51, self.a52, self.a53, self.a54, self.gamma, 0., 0., 0.],
[self.a61, self.a62, self.a63, self.a64, self.a65, self.gamma, 0., 0.],
[self.a71, self.a72, self.a73, self.a74, self.a75, self.a76, self.gamma, 0.],
[self.a81, self.a82, self.a83, self.a84, self.a85, self.a86, self.a87, self.gamma]])
self.c = sum(self.A, axis=1)
def single_step(self, state, t, dt, rhs, lhs_setup, lhs_solve, *args, **kwargs):
nonlinear_iter = 0
linear_iter = 0
nonlinear_converged = True
slow_nonlinear_convergence = False
projector_setups = 0
current_c_value = None
prior_stage_k = None
state_n = copy(state)
def residual(state_arg, existing_rhs=None, evaluate_new_rhs=True):
rhs_val = rhs(t + current_c_value * dt, state_arg) if evaluate_new_rhs else existing_rhs
return dt * (self.gamma * rhs_val + prior_stage_k) - (state_arg - state_n), rhs_val
def linear_setup(state_arg):
lhs_setup(t + current_c_value * dt, state_arg)
# stage 1
k1 = rhs(t, state)
prior_stage_k = self.a21 * k1
current_c_value = self.c[1]
# stage 2
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k1)
state = output.solution
k2 = output.rhs_at_converged
prior_stage_k = self.a32 * k2 + self.a31 * k1
current_c_value = self.c[2]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 3
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k2)
state = output.solution
k3 = output.rhs_at_converged
prior_stage_k = self.a43 * k3 + self.a42 * k2 + self.a41 * k1
current_c_value = self.c[3]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 4
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k3)
state = output.solution
k4 = output.rhs_at_converged
prior_stage_k = self.a54 * k4 + self.a53 * k3 + self.a52 * k2 + self.a51 * k1
current_c_value = self.c[4]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 5
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k4)
state = output.solution
k5 = output.rhs_at_converged
prior_stage_k = self.a65 * k5 + self.a64 * k4 + self.a63 * k3 + self.a62 * k2 + self.a61 * k1
current_c_value = self.c[5]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 6
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k5)
k6 = output.rhs_at_converged
prior_stage_k = self.a76 * k6 + self.a75 * k5 + self.a74 * k4 + self.a73 * k3 + self.a72 * k2 + self.a71 * k1
current_c_value = self.c[6]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 7
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k6)
k7 = output.rhs_at_converged
prior_stage_k = self.a87 * k7 + self.a86 * k6 + self.a85 * k5 + self.a84 * k4 + \
self.a83 * k3 + self.a82 * k2 + self.a81 * k1
current_c_value = self.c[7]
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# stage 8
output = self.nonlinear_solver(residual_method=residual,
setup_method=linear_setup,
solve_method=lhs_solve,
initial_guess=state,
initial_rhs=k7)
k8 = output.rhs_at_converged
nonlinear_iter += output.iter
linear_iter += output.liter
nonlinear_converged = nonlinear_converged and output.converged
slow_nonlinear_convergence = slow_nonlinear_convergence or output.slow_convergence
projector_setups += output.projector_setups
# accumulation
dstate = dt * (self.b1 * k1 + self.b2 * k2 + self.b3 * k3 +
self.b4 * k4 + self.b5 * k5 + self.b6 * k6 + self.b7 * k7 + self.b8 * k8)
dstate_h = dt * (self.b1h * k1 + self.b2h * k2 + self.b3h * k3 +
self.b4h * k4 + self.b5h * k5 + self.b6h * k6 + self.b7h * k7 + self.b8h * k8)
return StepOutput(solution_update=dstate,
temporal_error=self.norm(dstate - dstate_h),
nonlinear_iter=nonlinear_iter,
linear_iter=linear_iter,
nonlinear_converged=nonlinear_converged,
slow_nonlinear_convergence=slow_nonlinear_convergence,
projector_setups=projector_setups)
class GeneralAdaptiveERK(TimeStepperBase):
"""
A general-purpose explicit Runge-Kutta method with embedded error estimation for adaptive time stepping
**Constructor**:
Parameters
----------
name : str
name of the TimeStepper, e.g. 'Forward Euler' or 'Runge Kutta 4'
order : int
order of accuracy of the time stepping method
A : np.ndarray
Runge-Kutta stage coefficients for the method
b : np.ndarray
quadrature coefficients for the method
bhat : np.ndarray
embedded error estimation quadrature coefficients (default: None - not adaptive)
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
def __init__(self, name, order, A, b, bhat=None, norm_weighting=1., norm_order=Inf):
# todo: should add checks that A is explicit and that the coefficients match the provided error
self.A = copy(A)
self.b = copy(b)
self.bhat = copy(bhat) if bhat is not None else None
super().__init__(name='General ERK: ' + name, order=order, n_stages=b.size,
is_adaptive=bhat is not None, norm_weighting=norm_weighting, norm_order=norm_order)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
q = state
r = rhs
d = dt
s = self.n_stages
A = self.A
b = self.b
c = sum(A, axis=1)
k = [r(t, q)]
for i in range(1, s):
stage_update = 0.
for j in range(i):
stage_update += A[i, j] * k[j]
k.append(r(t + c[i] * d, q + d * stage_update))
update = b[0] * k[0]
error = zeros_like(update)
if self.bhat is not None:
error = (b[0] - self.bhat[0]) * k[0]
for i in range(1, s):
update += b[i] * k[i]
if self.bhat is not None:
error += (b[i] - self.bhat[i]) * k[i]
return StepOutput(solution_update=d * update, temporal_error=d * self.norm(error))
class GeneralAdaptiveERKMultipleEmbedded(TimeStepperBase):
"""
A general-purpose explicit Runge-Kutta method with embedded error estimation for adaptive time stepping
This class is used for advanced adaptive methods that utilize multiple embedded error estimates.
**Constructor**:
Parameters
----------
name : str
name of the TimeStepper, e.g. 'Forward Euler' or 'Runge Kutta 4'
order : int
order of accuracy of the time stepping method
A : np.ndarray
Runge-Kutta stage coefficients for the method
b : np.ndarray
quadrature coefficients for the method
bhats : list[np.ndarray]
list of embedded error estimation quadrature coefficients
norm_weighting : float or np.ndarray the size of the state vector
multiplies the embedded error estimate prior to computing the norm (default: 1.)
norm_order : int or np.Inf
order of the norm of the error estimate (default: np.Inf)
"""
def __init__(self, name, order, A, b, bhats, norm_weighting=1., norm_order=Inf):
# todo: add checks that A is explicit and that the coefficients match the provided error
self.A = copy(A)
self.b = copy(b)
self.bhats = bhats
super().__init__(name='General ERK: ' + name, order=order, n_stages=b.size,
is_adaptive=True, norm_weighting=norm_weighting, norm_order=norm_order)
def single_step(self, state, t, dt, rhs, *args, **kwargs):
q = state
r = rhs
d = dt
s = self.n_stages
A = self.A
b = self.b
c = sum(A, axis=1)
nb = len(self.bhats)
k = [r(t, q)]
for i in range(1, s):
stage_update = 0.
for j in range(i):
stage_update += A[i, j] * k[j]
k.append(r(t + c[i] * d, q + d * stage_update))
update = b[0] * k[0]
error = zeros_like(update)
extra_errors = [zeros_like(update)] * (nb - 1)
if self.bhats is not None:
error = (b[0] - self.bhats[0][0]) * k[0]
for j in range(nb - 1):
extra_errors[j] = (b[0] - self.bhats[j][0]) * k[0]
for i in range(1, s):
update += b[i] * k[i]
if self.bhats is not None:
error += (b[i] - self.bhats[0][i]) * k[i]
for j in range(nb - 1):
extra_errors[j] = (b[0] - self.bhats[j][i]) * k[i]
return StepOutput(solution_update=d * update,
temporal_error=d * self.norm(error),
extra_errors=[d * self.norm(e) for e in extra_errors])
<file_sep>Transient Flamelet Example: Ignition Sensitivity to Rate Parameter
==================================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - Solving transient flamelet ignition trajectories -
Observing sensitivity of the ignition behavior to a key reaction rate
parameter
In this demonstration we use the ``integrate_to_steady`` method as in
previous notebooks, this time to look at how ignition behavior is
affected by the pre-exponential factor of a key chain-branching reaction
in hydrogen-air ignition. Cantera is used to load the nominal chemistry
and modify the reaction rate accordingly.
.. code:: ipython3
import cantera as ct
from spitfire import ChemicalMechanismSpec, Flamelet, FlameletSpec
import matplotlib.pyplot as plt
import numpy as np
from os.path import abspath, join
.. code:: ipython3
sol = ct.Solution('h2-burke.xml', 'h2-burke')
Tair = 1200.
pressure = 101325.
zstoich = 0.1
chi_max = 1.e3
npts_interior = 32
k1mult_list = [0.02, 0.1, 0.2, 1.0, 10.0, 100.0]
sol_dict = dict()
max_time = 0.
max_temp = 0.
A0_original = np.copy(sol.reaction(0).rate.pre_exponential_factor)
for i, k1mult in enumerate(k1mult_list):
print(f'running {k1mult:.2f}A ...')
r0 = sol.reaction(0)
new_rate = ct.Arrhenius(k1mult * A0_original,
r0.rate.temperature_exponent,
r0.rate.activation_energy)
new_rxn = ct.ElementaryReaction(r0.reactants, r0.products)
new_rxn.rate = new_rate
sol.modify_reaction(0, new_rxn)
m = ChemicalMechanismSpec.from_solution(sol)
air = m.stream(stp_air=True)
air.TP = Tair, pressure
fuel = m.mix_fuels_for_stoich_mixture_fraction(m.stream('X', 'H2:1'), m.stream('X', 'N2:1'), zstoich, air)
fuel.TP = 300., pressure
flamelet_specs = FlameletSpec(mech_spec=m,
initial_condition='unreacted',
oxy_stream=air,
fuel_stream=fuel,
grid_points=npts_interior + 2,
grid_cluster_intensity=4.,
max_dissipation_rate=chi_max)
ft = Flamelet(flamelet_specs)
output = ft.integrate_to_steady(first_time_step=1.e-9)
t = output.time_grid * 1.e3
z = output.mixture_fraction_grid
T = output['temperature']
OH = output['mass fraction OH']
max_time = max([max_time, np.max(t)])
max_temp = max([max_temp, np.max(T)])
sol_dict[k1mult] = (i, t, z, T, OH)
print('done')
.. parsed-literal::
running 0.02A ...
running 0.10A ...
running 0.20A ...
running 1.00A ...
running 10.00A ...
running 100.00A ...
done
Next we simply show the profiles of temperature and hydroxyl mass
fraction with the various rate parameters. We not only see the expected
decrease in ignition delay with larger pre-exponential factor, but also
that ignition does not occur at lower values as chain-branching is
entirely overwhelmed by dissipation.
.. code:: ipython3
fig, axarray = plt.subplots(1, len(k1mult_list), sharex=True, sharey=True)
for k1mult in k1mult_list:
sol = sol_dict[k1mult]
axarray[sol[0]].contourf(sol[2], sol[1] * 1.e3, sol[3],
cmap=plt.get_cmap('magma'),
levels=np.linspace(300., max_temp, 20))
axarray[sol[0]].set_title(f'{k1mult:.2f}A')
axarray[sol[0]].set_xlim([0, 1])
axarray[sol[0]].set_ylim([1.e0, max_time * 1.e3])
axarray[sol[0]].set_yscale('log')
axarray[sol[0]].set_xlabel('Z')
axarray[0].set_ylabel('t (ms)')
plt.show()
fig, axarray = plt.subplots(1, len(k1mult_list), sharex=True, sharey=True)
print('Mass fraction OH profiles')
for k1mult in k1mult_list:
sol = sol_dict[k1mult]
axarray[sol[0]].contourf(sol[2], sol[1] * 1.e3, sol[4],
cmap=plt.get_cmap('magma'))
axarray[sol[0]].set_title(f'{k1mult:.2f}A')
axarray[sol[0]].set_xlim([0, 1])
axarray[sol[0]].set_ylim([1.e0, max_time * 1.e3])
axarray[sol[0]].set_yscale('log')
axarray[sol[0]].set_xlabel('Z')
axarray[0].set_ylabel('t (ms)')
plt.show()
.. image:: example_transient_flamelet_rate_sensitivity_files/example_transient_flamelet_rate_sensitivity_4_0.png
.. parsed-literal::
Mass fraction OH profiles
.. image:: example_transient_flamelet_rate_sensitivity_files/example_transient_flamelet_rate_sensitivity_4_2.png
<file_sep>/*
* Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
* Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
*
* You should have received a copy of the 3-clause BSD License
* along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
*
* Questions? Contact <NAME> (<EMAIL>)
*/
#include "btddod_matrix_kernels.h"
#include "blas_lapack_kernels.h"
namespace griffon
{
namespace btddod
{
void btddod_full_factorize(double *out_d_factors, const int num_blocks, const int block_size, double *out_l_values,
int *out_d_pivots)
{
const int nelem_block = block_size * block_size;
const int nelem_offdiagonal = (num_blocks - 1) * block_size;
const int nelem_blockdiagonals = num_blocks * nelem_block;
double identity_matrix[nelem_block];
for (int i = 0; i < nelem_block; ++i)
{
identity_matrix[i] = 0.;
}
for (int i = 0; i < block_size; ++i)
{
identity_matrix[i * (block_size + 1)] = 1.;
}
const double *sub = &out_d_factors[nelem_blockdiagonals];
const double *sup = &out_d_factors[nelem_blockdiagonals + nelem_offdiagonal];
int info;
char trans = 'N';
griffon::lapack::dgetrf_(&block_size, &block_size, out_d_factors, &block_size, out_d_pivots, &info);
for (int i = 1; i < num_blocks; ++i)
{
const int o1 = i * nelem_block;
const int om = o1 - nelem_block;
for (int l = 0; l < nelem_block; ++l)
{
out_l_values[o1 + l] = identity_matrix[l];
}
griffon::lapack::dgetrs_(&trans, &block_size, &block_size, &out_d_factors[om], &block_size,
&out_d_pivots[(i - 1) * block_size], &out_l_values[o1], &block_size, &info);
const int im1_base = (i - 1) * block_size;
for (int j = 0; j < block_size; ++j)
{
const int o2 = o1 + j * block_size;
for (int k = 0; k < block_size; ++k)
{
out_l_values[o2 + k] *= sub[im1_base + k];
}
}
for (int j = 0; j < block_size; ++j)
{
const int o2 = j * block_size;
const int o3 = o1 + o2;
const double fac = -sup[im1_base + j];
for (int k = 0; k < block_size; ++k)
{
out_d_factors[o3 + k] += fac * out_l_values[o3 + k];
}
}
griffon::lapack::dgetrf_(&block_size, &block_size, &out_d_factors[o1], &block_size,
&out_d_pivots[i * block_size], &info);
}
}
void btddod_full_solve(const double *d_factors, const double *l_values, const int *d_pivots, const double *rhs,
const int num_blocks, const int block_size, double *out_solution)
{
const int nelem_block = block_size * block_size;
const int nelem_offdiagonal = (num_blocks - 1) * block_size;
const int nelem_blockdiagonals = num_blocks * nelem_block;
const int nelem_vector = num_blocks * block_size;
const double *sup = &d_factors[nelem_blockdiagonals + nelem_offdiagonal];
double y[nelem_vector];
double local_tmp[block_size];
for (int i = 0; i < block_size; ++i)
y[i] = rhs[i];
for (int i = 1; i < num_blocks; ++i)
{
for (int l = 0; l < block_size; ++l)
y[i * block_size + l] = rhs[i * block_size + l];
griffon::blas::matrix_vector_multiply(block_size, &y[i * block_size], -1., &l_values[i * nelem_block],
&y[(i - 1) * block_size], 1.);
}
const int i = num_blocks - 1;
griffon::lapack::lu_solve_with_copy(block_size, &d_factors[i * nelem_block], &d_pivots[i * block_size],
&y[i * block_size], &out_solution[i * block_size]);
for (int i = num_blocks - 2; i >= 0; --i)
{
const int i_base = i * block_size;
const int ip1_base = (i + 1) * block_size;
for (int j = 0; j < block_size; ++j)
{
local_tmp[j] = y[i * block_size + j] - sup[i_base + j] * out_solution[ip1_base + j];
}
griffon::lapack::lu_solve_with_copy(block_size, &d_factors[i * nelem_block], &d_pivots[i * block_size],
local_tmp, &out_solution[i * block_size]);
}
}
void btddod_full_matvec(const double *matrix_values, const double *vec, const int num_blocks, const int block_size,
double *out_matvec)
{
const int nelem_block = block_size * block_size;
const int nelem_offdiagonal = (num_blocks - 1) * block_size;
const int nelem_blockdiagonals = num_blocks * nelem_block;
// block diagonal contribution
for (int i = 0; i < num_blocks; ++i)
{
griffon::blas::matrix_vector_multiply(block_size, &out_matvec[i * block_size], 1.,
&matrix_values[i * nelem_block], &vec[i * block_size], 0.);
}
const double *sub = &matrix_values[nelem_blockdiagonals];
const double *sup = &matrix_values[nelem_blockdiagonals + nelem_offdiagonal];
// off diagonal contributions
for (int iz = 1; iz < num_blocks - 1; ++iz)
{
const int i_base = iz * block_size;
const int im1_base = (iz - 1) * block_size;
const int ip1_base = (iz + 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i_base + iq] += sup[i_base + iq] * vec[ip1_base + iq] + sub[im1_base + iq] * vec[im1_base + iq];
}
}
const int iz1 = num_blocks - 1;
const int i1_base = iz1 * block_size;
const int im1_base = (iz1 - 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i1_base + iq] += sub[im1_base + iq] * vec[im1_base + iq];
}
const int iz2 = 0;
const int i2_base = iz2 * block_size;
const int ip1_base = (iz2 + 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i2_base + iq] += sup[i2_base + iq] * vec[ip1_base + iq];
}
}
void btddod_blockdiag_matvec(const double *matrix_values, const double *vec, const int num_blocks, const int block_size,
double *out_matvec)
{
const int nelem_block = block_size * block_size;
for (int i = 0; i < num_blocks; ++i)
{
griffon::blas::matrix_vector_multiply(block_size, &out_matvec[i * block_size], 1.,
&matrix_values[i * nelem_block], &vec[i * block_size], 0.);
}
}
void btddod_offdiag_matvec(const double *matrix_values, const double *vec, const int num_blocks, const int block_size,
double *out_matvec)
{
const int nelem_block = block_size * block_size;
const int nelem_offdiagonal = (num_blocks - 1) * block_size;
const int nelem_blockdiagonals = num_blocks * nelem_block;
const int nelem_vector = num_blocks * block_size;
for (int i = 0; i < nelem_vector; ++i)
{
out_matvec[i] = 0.;
}
const double *sub = &matrix_values[nelem_blockdiagonals];
const double *sup = &matrix_values[nelem_blockdiagonals + nelem_offdiagonal];
// off diagonal contributions
for (int iz = 1; iz < num_blocks - 1; ++iz)
{
const int i_base = iz * block_size;
const int im1_base = (iz - 1) * block_size;
const int ip1_base = (iz + 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i_base + iq] += sup[i_base + iq] * vec[ip1_base + iq] + sub[im1_base + iq] * vec[im1_base + iq];
}
}
const int iz1 = num_blocks - 1;
const int i1_base = iz1 * block_size;
const int im1_base = (iz1 - 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i1_base + iq] += sub[im1_base + iq] * vec[im1_base + iq];
}
const int iz2 = 0;
const int i2_base = iz2 * block_size;
const int ip1_base = (iz2 + 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i2_base + iq] += sup[i2_base + iq] * vec[ip1_base + iq];
}
}
void btddod_lowerfulltriangle_matvec(const double *matrix_values, const double *vec, const int num_blocks,
const int block_size, double *out_matvec)
{
const int nelem_block = block_size * block_size;
const int nelem_blockdiagonals = num_blocks * nelem_block;
// block diagonal contribution
for (int i = 0; i < num_blocks; ++i)
{
griffon::blas::matrix_vector_multiply(block_size, &out_matvec[i * block_size], 1.,
&matrix_values[i * nelem_block], &vec[i * block_size], 0.);
}
const double *sub = &matrix_values[nelem_blockdiagonals];
// off diagonal contributions
for (int iz = 1; iz < num_blocks - 1; ++iz)
{
const int i_base = iz * block_size;
const int im1_base = (iz - 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i_base + iq] += sub[im1_base + iq] * vec[im1_base + iq];
}
}
const int iz1 = num_blocks - 1;
const int i1_base = iz1 * block_size;
const int im1_base = (iz1 - 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i1_base + iq] += sub[im1_base + iq] * vec[im1_base + iq];
}
}
void btddod_upperfulltriangle_matvec(const double *matrix_values, const double *vec, const int num_blocks,
const int block_size, double *out_matvec)
{
const int nelem_block = block_size * block_size;
const int nelem_offdiagonal = (num_blocks - 1) * block_size;
const int nelem_blockdiagonals = num_blocks * nelem_block;
// block diagonal contribution
for (int i = 0; i < num_blocks; ++i)
{
griffon::blas::matrix_vector_multiply(block_size, &out_matvec[i * block_size], 1.,
&matrix_values[i * nelem_block], &vec[i * block_size], 0.);
}
const double *sup = &matrix_values[nelem_blockdiagonals + nelem_offdiagonal];
// off diagonal contributions
for (int iz = 1; iz < num_blocks - 1; ++iz)
{
const int i_base = iz * block_size;
const int ip1_base = (iz + 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i_base + iq] += sup[i_base + iq] * vec[ip1_base + iq];
}
}
const int iz2 = 0;
const int i2_base = iz2 * block_size;
const int ip1_base = (iz2 + 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i2_base + iq] += sup[i2_base + iq] * vec[ip1_base + iq];
}
}
void btddod_lowerofftriangle_matvec(const double *matrix_values, const double *vec, const int num_blocks,
const int block_size, double *out_matvec)
{
const int nelem_block = block_size * block_size;
const int nelem_blockdiagonals = num_blocks * nelem_block;
const int nelem_vector = num_blocks * block_size;
for (int i = 0; i < nelem_vector; ++i)
{
out_matvec[i] = 0.;
}
const double *sub = &matrix_values[nelem_blockdiagonals];
// off diagonal contributions
for (int iz = 1; iz < num_blocks - 1; ++iz)
{
const int i_base = iz * block_size;
const int im1_base = (iz - 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i_base + iq] += sub[im1_base + iq] * vec[im1_base + iq];
}
}
const int iz1 = num_blocks - 1;
const int i1_base = iz1 * block_size;
const int im1_base = (iz1 - 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i1_base + iq] += sub[im1_base + iq] * vec[im1_base + iq];
}
}
void btddod_upperofftriangle_matvec(const double *matrix_values, const double *vec, const int num_blocks,
const int block_size, double *out_matvec)
{
const int nelem_block = block_size * block_size;
const int nelem_offdiagonal = (num_blocks - 1) * block_size;
const int nelem_blockdiagonals = num_blocks * nelem_block;
const int nelem_vector = num_blocks * block_size;
for (int i = 0; i < nelem_vector; ++i)
{
out_matvec[i] = 0.;
}
const double *sup = &matrix_values[nelem_blockdiagonals + nelem_offdiagonal];
// off diagonal contributions
for (int iz = 1; iz < num_blocks - 1; ++iz)
{
const int i_base = iz * block_size;
const int ip1_base = (iz + 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i_base + iq] += sup[i_base + iq] * vec[ip1_base + iq];
}
}
const int iz2 = 0;
const int i2_base = iz2 * block_size;
const int ip1_base = (iz2 + 1) * block_size;
for (int iq = 0; iq < block_size; ++iq)
{
out_matvec[i2_base + iq] += sup[i2_base + iq] * vec[ip1_base + iq];
}
}
void btddod_blockdiag_factorize(const double *matrix_values, const int num_blocks, const int block_size, int *out_pivots,
double *out_factors)
{
const int nelem_block = block_size * block_size;
for (int i = 0; i < num_blocks; ++i)
{
griffon::lapack::lu_factorize_with_copy(block_size, &matrix_values[i * nelem_block],
&out_pivots[i * block_size], &out_factors[i * nelem_block]);
}
}
void btddod_blockdiag_solve(const int *pivots, const double *factors, const double *rhs, const int num_blocks,
const int block_size, double *out_solution)
{
const int nelem_block = block_size * block_size;
for (int i = 0; i < num_blocks; ++i)
{
griffon::lapack::lu_solve_with_copy(block_size, &factors[i * nelem_block], &pivots[i * block_size],
&rhs[i * block_size], &out_solution[i * block_size]);
}
}
void btddod_lowerfulltriangle_solve(const int *pivots, const double *factors, const double *matrix_values,
const double *rhs, const int num_blocks, const int block_size, double *out_solution)
{
const int nelem_block = block_size * block_size;
const int nelem_blockdiagonals = num_blocks * nelem_block;
double rhsTemp[block_size];
griffon::lapack::lu_solve_with_copy(block_size, factors, pivots, rhs, out_solution);
const double *sub = &matrix_values[nelem_blockdiagonals];
for (int i = 1; i < num_blocks; ++i)
{
for (int iq = 0; iq < block_size; ++iq)
{
rhsTemp[iq] = rhs[i * block_size + iq] - sub[(i - 1) * block_size + iq] * out_solution[(i - 1) * block_size + iq];
}
griffon::lapack::lu_solve_with_copy(block_size, &factors[i * nelem_block], &pivots[i * block_size], rhsTemp,
&out_solution[i * block_size]);
}
}
void btddod_upperfulltriangle_solve(const int *pivots, const double *factors, const double *matrix_values,
const double *rhs, const int num_blocks, const int block_size, double *out_solution)
{
const int nelem_block = block_size * block_size;
const int nelem_offdiagonal = (num_blocks - 1) * block_size;
const int nelem_blockdiagonals = num_blocks * nelem_block;
double rhsTemp[block_size];
const int i = num_blocks - 1;
griffon::lapack::lu_solve_with_copy(block_size, &factors[i * nelem_block], &pivots[i * block_size],
&rhs[i * block_size], &out_solution[i * block_size]);
const double *sup = &matrix_values[nelem_blockdiagonals + nelem_offdiagonal];
for (int i = num_blocks - 2; i >= 0; --i)
{
for (int iq = 0; iq < block_size; ++iq)
{
rhsTemp[iq] = rhs[i * block_size + iq] - sup[i * block_size + iq] * out_solution[(i + 1) * block_size + iq];
}
griffon::lapack::lu_solve_with_copy(block_size, &factors[i * nelem_block], &pivots[i * block_size], rhsTemp,
&out_solution[i * block_size]);
}
}
// A <- matrix_scale * A + diag_scale * block_diag
void btddod_scale_and_add_scaled_block_diagonal(double *in_out_matrix_values, const double matrix_scale,
const double *block_diag, const double diag_scale, const int num_blocks,
const int block_size)
{
const int nelem_block = block_size * block_size;
const int nelem_matrix = block_size * (num_blocks * block_size + 2 * (num_blocks - 1));
const int nelem_blockdiag = nelem_block * num_blocks;
for (int i = 0; i < nelem_matrix; ++i)
{
in_out_matrix_values[i] *= matrix_scale;
}
for (int i = 0; i < nelem_blockdiag; ++i)
{
in_out_matrix_values[i] += block_diag[i] * diag_scale;
}
}
// A <- matrix_scale * A + diag_scale * diagonal
void btddod_scale_and_add_diagonal(double *in_out_matrix_values, const double matrix_scale, const double *diagonal,
const double diag_scale, const int num_blocks, const int block_size)
{
const int nelem_block = block_size * block_size;
const int nelem_matrix = block_size * (num_blocks * block_size + 2 * (num_blocks - 1));
for (int i = 0; i < nelem_matrix; ++i)
{
in_out_matrix_values[i] *= matrix_scale;
}
for (int iz = 0; iz < num_blocks; ++iz)
{
for (int iq = 0; iq < block_size; ++iq)
{
in_out_matrix_values[iz * nelem_block + iq * (block_size + 1)] += diag_scale * diagonal[iz * block_size + iq];
}
}
}
} // namespace btddod
} // namespace griffon
<file_sep>import unittest
from numpy import log, mean
from spitfire.time.methods import *
from spitfire.time.nonlinear import *
from spitfire import odesolve
def direct_solve(fun):
def append_iteration_count_of_one_and_converged(x, *args, **kwargs):
output = fun(x, *args, **kwargs)
return output, 1, True
return append_iteration_count_of_one_and_converged
def validate_method(method):
theta = 3.03623184819656
q0 = np.array([0., theta * np.tanh(0.25 * theta)])
rhs = lambda t, q: np.array([q[1], -np.exp(1. + q[0])])
dtlist = [0.06, 0.02, 0.01, 0.009, 0.008, 0.006]
errors = []
tf = 1.0
for dt in dtlist:
qf = odesolve(rhs,
q0,
array([tf]),
method=method,
step_size=dt)
errors.append(norm(qf[0, 0]))
order_list = []
for idx in range(len(errors) - 1):
order_list.append(log(errors[idx] / errors[idx + 1]) / log(dtlist[idx] / dtlist[idx + 1]))
observed_order = mean(array(order_list))
success = method.order - 0.1 < observed_order < method.order + 0.1
if not success:
print(method.name, method.order, observed_order)
return success
def create_test(m):
def test(self):
self.assertTrue(validate_method(m))
return test
class TestOrderOfAccuracy(unittest.TestCase):
pass
for method in [ForwardEulerS1P1,
ExpMidpointS2P2,
ExpTrapezoidalS2P2Q1,
ExpRalstonS2P2,
RK3KuttaS3P3,
RK4ClassicalS4P4,
BogackiShampineS4P3Q2,
ZonneveldS5P4Q3,
ExpKennedyCarpetnerS6P4Q3,
CashKarpS6P5Q4, ]:
setattr(TestOrderOfAccuracy, 'test_' + str(method().name), create_test(method()))
for method in [BackwardEulerS1P1Q1,
CrankNicolsonS2P2,
KennedyCarpenterS6P4Q3,
KennedyCarpenterS4P3Q2,
KvaernoS4P3Q2,
KennedyCarpenterS8P5Q4, ]:
for solver in [SimpleNewtonSolver]:
setattr(TestOrderOfAccuracy, 'test_' + str(method(solver()).name) + '_' + str(solver),
create_test(method(solver())))
if __name__ == '__main__':
unittest.main()
<file_sep>import pickle
from os.path import abspath, join
def run():
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.chemistry.reactors import HomogeneousReactor
from numpy import sin as sin, pi as pi, array
from os.path import abspath, join
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
mechanism = ChemicalMechanismSpec(cantera_input=xml,
group_name='h2-burke')
air = mechanism.stream(stp_air=True)
fuel = mechanism.stream('X', 'H2:1')
mix = mechanism.mix_for_equivalence_ratio(1.0, fuel, air)
mix.TP = 800., 101325.
feed = mechanism.copy_stream(mix)
reactor = HomogeneousReactor(mechanism, mix,
configuration='isobaric',
heat_transfer='adiabatic',
mass_transfer='open',
mixing_tau=1.e-5,
feed_temperature=lambda t: 800. + 400. * sin(2. * pi * 10. * t),
feed_mass_fractions=feed.Y)
output = reactor.integrate_to_time(0.1, transient_tolerance=1.e-10, write_log=False, log_rate=200)
Y = array([output['mass fraction ' + s].copy() for s in mechanism.species_names])
return output.time_values.copy(), output['temperature'], Y
if __name__ == '__main__':
output = run()
gold_pkl = abspath(join('tests', 'reactor', 'oscillating_feed_temperature', 'gold.pkl'))
with open(gold_pkl, 'wb') as file_output:
pickle.dump(output, file_output)
<file_sep>import pickle
import unittest
from os.path import join, abspath
from numpy.testing import assert_allclose
from tests.time_integration.chemistry_abc_implicit.rebless import run
class Test(unittest.TestCase):
def test(self):
output = run()
gold_file = abspath(join('tests',
'time_integration',
'chemistry_abc_implicit',
'gold.pkl'))
with open(gold_file, 'rb') as gold_input:
gold_output = pickle.load(gold_input)
for key in gold_output:
t, sol = output[key]
gold_t, gold_sol = gold_output[key]
self.assertIsNone(assert_allclose(t, gold_t, atol=1.e-8))
self.assertIsNone(assert_allclose(sol, gold_sol, atol=1.e-8))
if __name__ == '__main__':
unittest.main()
<file_sep>Custom Tabulation Example: 4D Coal Combustion Model
===================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - building a table with user-defined continuation loops -
varying the fuel stream and incorporating nonadiabatic effects in a
quasisteady manner - stacking contour plots to visualize a 3D field
This example showcases a flamelet library built with manual loops over
the tabulation dimensions. We build a four-dimensional table of states
over the mixture fraction, scalar dissipation rate (stoichiometric
value), heat transfer coefficient, and fraction of volatiles and char
(from coal particle gasification) in the fuel stream. The heat transfer
dimension is expanded in a quasisteady manner, with steady states
calcalated at each heat transfer coefficient (or, at each enthalpy
defect), as an alternative to transient heat loss calculations in the
provided ``build_nonadiabatic_defect_transient_slfm_library`` method
(but very similar to the
``build_nonadiabatic_defect_steady_slfm_library`` method).
Here we manually loop over table dimensions and use the ``Flamelet``
class directly instead of the higher-level convenience methods provided
in the ``spitfire.chemistry.tabulation`` module. While the tabulation
methods are much more convenient, this provides a finer level of control
and customizability for tabulation techniques not currently wrapped in a
high-level interface.
.. code:: ipython3
import numpy as np
import matplotlib.pyplot as plt
import pickle
from time import perf_counter
from spitfire import ChemicalMechanismSpec, Flamelet, FlameletSpec, Dimension, Library
First we define a helper function for mixing char and volatiles and load
some stream data for later use.
.. code:: ipython3
def get_fuel_stream(coal_fuels, alpha, mechanism, pressure=101325.):
"""
Fuel streams representative of coal combustion, spanning char to volatiles, with volatiles fraction alpha.
Personal communication with <NAME>, University of Utah, 2018.
"""
volatiles = mechanism.stream('TPY', (coal_fuels['volatiles']['T'], pressure, coal_fuels['volatiles']['Y']))
char = mechanism.stream('TPY', (coal_fuels['char']['T'], pressure, coal_fuels['char']['Y']))
return mechanism.mix_streams([(volatiles, alpha), (char, 1. - alpha)], 'mass', 'HP')
with open('coalflamelet_bcs.pkl', 'rb') as bcs_src:
coal_fuels = pickle.load(bcs_src)
Next we load up a wrapper of the GRI-3.0 methane combustion mechanism
and make an air stream.
.. code:: ipython3
mechanism = ChemicalMechanismSpec(cantera_xml='methane-gri30.xml', group_name='gri30_mix')
pressure = 101325.
oxy = mechanism.stream(stp_air=True)
oxy.TP = 350., pressure
Next we specify the table dimensions for the char/volatiles fraction,
dissipation rate, heat transfer coefficient, and mixture fraction. From
the set of values of each variable we make a ``Library`` object. Then
for each property to be tabulated we set up an empty dataset in the
library to fill later as we perform continuation across each library
dimension.
.. code:: ipython3
mixfrac_vec = np.linspace(0., 1., 96)
alpha_vec = np.array([0.0, 0.1, 0.3, 0.5, 0.7])
chist_vec = np.logspace(-1., 3., 8)
h_vec = np.hstack([0., np.logspace(-8, 1, 24)])
zdim = Dimension('mixture_fraction', mixfrac_vec)
xdim = Dimension('dissipation_rate_stoich', chist_vec, log_scaled=True)
hdim = Dimension('heat_transfer_coefficient', h_vec)
adim = Dimension('alpha', alpha_vec)
l = Library(adim, hdim, xdim, zdim)
l.extra_attributes['mech_spec'] = mechanism
for q in ['temperature', 'pressure'] + ['mass fraction ' + s for s in mechanism.species_names]:
l[q] = l.get_empty_dataset()
Now we make a specifications for the flamelet.
.. code:: ipython3
particle_temperature = 350.
flamelet_specs = {'mech_spec': mechanism,
'oxy_stream': oxy,
'fuel_stream': get_fuel_stream(coal_fuels, 0., mechanism, pressure),
'grid': mixfrac_vec,
'heat_transfer': 'nonadiabatic',
'convection_temperature': particle_temperature,
'convection_coefficient': 0.,
'scale_heat_loss_by_temp_range': False,
'scale_convection_by_dissipation': False,
'use_linear_ref_temp_profile': False,
'radiation_temperature': particle_temperature,
'radiative_emissivity': 0.,
'rates_sensitivity_type': 'sparse'}
Now we enter into the loops. In continuation calculations it is critical
to get the best initial guess, as this determines convergence rates and
often the solution that is ultimately computed. We treat different
values of :math:`\alpha` (the char/volatiles fraction) as separate
problems entirely, not using the solution from one value to inform the
next, as the chemistry is so different between them given our coarse
resolution of the :math:`\alpha` line.
For each :math:`\alpha`, then, we build a three-dimensional library over
the dissipation rate (:math:`\chi_{\rm st}`), heat transfer coefficient
(:math:`h`), and mixture fraction (:math:`\mathcal{Z}`). Note that each
three-dimensional table could be generated in parallel with the
``multiprocessing`` module. A relevant approach to parallelization is
taken in the ``build_nonadiabatic_defect_*_slfm_library`` methods in
Spitfire. An annoyance that Cantera solution objects cannot be directly
pickled (a form of serialization required by ``multiprocessing``).
However ``ChemicalMechanismSpec`` instances can be pickled and so
incorporation of multiprocessing isn’t too bad.
In building the three-dimensional library, we first iterate over serial
calculations in the dissipation rate direction with zero heat loss
(adiabatic flamelets), where each prior solution provides an excellent
initial guess for the next dissipation rate. From this line of
solutions, then, we have even more parallel work in the heat loss
dimension, which may be solved for each dissipation rate independently
of the others. Again, each extension of the heat loss dimension is
treated serially, using the prior solution as the initial guess.
Here we do not exploit the available parallelism in any way to keep
things simple, but factors of ten or more speedup could be easily
obtained with a bit of extra work for either Python-based
multiprocessing or simply running multiple scripts and combining the
libraries after the fact.
.. code:: ipython3
flamelet_specs['initial_condition'] = 'equilibrium'
if 'library_slice' in flamelet_specs:
flamelet_specs.pop('library_slice')
cput000 = perf_counter()
for ia, alpha in enumerate(alpha_vec):
print(f'Running alpha = {alpha:4.2f} ...')
flamelet_specs.update({'fuel_stream': get_fuel_stream(coal_fuels, alpha, mechanism)})
adiabatic_solutions = list()
cput00 = perf_counter()
for ichi, chist in enumerate(chist_vec):
flamelet_specs.update({'stoich_dissipation_rate': chist})
if ichi > 0:
flamelet_specs['library_slice'] = Library.squeeze(l[ia, 0, ichi - 1, :])
else:
if 'library_slice' in flamelet_specs:
flamelet_specs.pop('library_slice')
f = Flamelet(**flamelet_specs)
steady_adiabatic_lib = f.compute_steady_state()
for quantity in steady_adiabatic_lib.props:
l[quantity][ia, 0, ichi, :] = steady_adiabatic_lib[quantity].ravel()
cput1 = perf_counter()
print(f'Converged adiabatic solutions in {cput1-cput00:6.2f} s {"":24} | total cpu time is {cput1 - cput000:6.2f} s')
for ichi, chist in enumerate(chist_vec):
flamelet_specs.update({'stoich_dissipation_rate': chist})
cput0 = perf_counter()
for ih, h in enumerate(h_vec):
flamelet_specs.update({'convection_coefficient': h})
flamelet_specs['library_slice'] = Library.squeeze(l[ia, ih - 1 if ih > 0 else 0, ichi, :])
f = Flamelet(**flamelet_specs)
output = f.compute_steady_state()
for quantity in output.props:
l[quantity][ia, ih, ichi, :] = output[quantity].ravel()
cput1 = perf_counter()
print(f'{"":9} heat loss solutions for chi_st = {chist:7.2e} Hz in {cput1-cput0:6.2f} s | {"":14} is {cput1 - cput000:6.2f} s')
cput1 = perf_counter()
print(f'Completed alpha = {alpha:4.2f} in {cput1-cput00:6.2f} s')
print('-' * 95)
.. parsed-literal::
Running alpha = 0.00 ...
Converged adiabatic solutions in 2.94 s | total cpu time is 2.94 s
heat loss solutions for chi_st = 1.00e-01 Hz in 2.90 s | is 5.84 s
heat loss solutions for chi_st = 3.73e-01 Hz in 0.75 s | is 6.59 s
heat loss solutions for chi_st = 1.39e+00 Hz in 0.69 s | is 7.28 s
heat loss solutions for chi_st = 5.18e+00 Hz in 0.68 s | is 7.96 s
heat loss solutions for chi_st = 1.93e+01 Hz in 0.68 s | is 8.64 s
heat loss solutions for chi_st = 7.20e+01 Hz in 0.69 s | is 9.34 s
heat loss solutions for chi_st = 2.68e+02 Hz in 0.68 s | is 10.01 s
heat loss solutions for chi_st = 1.00e+03 Hz in 0.68 s | is 10.69 s
Completed alpha = 0.00 in 10.69 s
-----------------------------------------------------------------------------------------------
Running alpha = 0.10 ...
Converged adiabatic solutions in 9.16 s | total cpu time is 19.85 s
heat loss solutions for chi_st = 1.00e-01 Hz in 29.99 s | is 49.84 s
heat loss solutions for chi_st = 3.73e-01 Hz in 13.01 s | is 62.86 s
heat loss solutions for chi_st = 1.39e+00 Hz in 1.28 s | is 64.14 s
heat loss solutions for chi_st = 5.18e+00 Hz in 0.80 s | is 64.94 s
heat loss solutions for chi_st = 1.93e+01 Hz in 0.76 s | is 65.70 s
heat loss solutions for chi_st = 7.20e+01 Hz in 0.73 s | is 66.43 s
heat loss solutions for chi_st = 2.68e+02 Hz in 0.73 s | is 67.16 s
heat loss solutions for chi_st = 1.00e+03 Hz in 0.76 s | is 67.92 s
Completed alpha = 0.10 in 57.23 s
-----------------------------------------------------------------------------------------------
Running alpha = 0.30 ...
Converged adiabatic solutions in 5.95 s | total cpu time is 73.87 s
heat loss solutions for chi_st = 1.00e-01 Hz in 30.48 s | is 104.35 s
heat loss solutions for chi_st = 3.73e-01 Hz in 17.18 s | is 121.53 s
heat loss solutions for chi_st = 1.39e+00 Hz in 1.35 s | is 122.88 s
heat loss solutions for chi_st = 5.18e+00 Hz in 0.80 s | is 123.68 s
heat loss solutions for chi_st = 1.93e+01 Hz in 0.74 s | is 124.42 s
heat loss solutions for chi_st = 7.20e+01 Hz in 0.75 s | is 125.17 s
heat loss solutions for chi_st = 2.68e+02 Hz in 0.74 s | is 125.90 s
heat loss solutions for chi_st = 1.00e+03 Hz in 0.74 s | is 126.64 s
Completed alpha = 0.30 in 58.72 s
-----------------------------------------------------------------------------------------------
Running alpha = 0.50 ...
Converged adiabatic solutions in 6.25 s | total cpu time is 132.89 s
heat loss solutions for chi_st = 1.00e-01 Hz in 25.93 s | is 158.82 s
heat loss solutions for chi_st = 3.73e-01 Hz in 12.21 s | is 171.03 s
heat loss solutions for chi_st = 1.39e+00 Hz in 1.31 s | is 172.34 s
heat loss solutions for chi_st = 5.18e+00 Hz in 0.91 s | is 173.25 s
heat loss solutions for chi_st = 1.93e+01 Hz in 0.77 s | is 174.01 s
heat loss solutions for chi_st = 7.20e+01 Hz in 0.77 s | is 174.78 s
heat loss solutions for chi_st = 2.68e+02 Hz in 0.77 s | is 175.55 s
heat loss solutions for chi_st = 1.00e+03 Hz in 0.78 s | is 176.33 s
Completed alpha = 0.50 in 49.69 s
-----------------------------------------------------------------------------------------------
Running alpha = 0.70 ...
Converged adiabatic solutions in 7.56 s | total cpu time is 183.90 s
heat loss solutions for chi_st = 1.00e-01 Hz in 23.49 s | is 207.39 s
heat loss solutions for chi_st = 3.73e-01 Hz in 8.83 s | is 216.21 s
heat loss solutions for chi_st = 1.39e+00 Hz in 1.02 s | is 217.23 s
heat loss solutions for chi_st = 5.18e+00 Hz in 0.79 s | is 218.02 s
heat loss solutions for chi_st = 1.93e+01 Hz in 0.79 s | is 218.81 s
heat loss solutions for chi_st = 7.20e+01 Hz in 0.80 s | is 219.60 s
heat loss solutions for chi_st = 2.68e+02 Hz in 0.80 s | is 220.40 s
heat loss solutions for chi_st = 1.00e+03 Hz in 0.84 s | is 221.24 s
Completed alpha = 0.70 in 44.90 s
-----------------------------------------------------------------------------------------------
Saving a library file for later use
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Saving a library file to disk to be reloaded later is straightforward.
The rest of the notebook consists of some visualizations of the library
data.
.. code:: ipython3
l.save_to_file('coal_library.pkl')
library = Library.load_from_file('coal_library.pkl')
.. code:: ipython3
z_dim = library.dim('mixture_fraction')
x_dim = library.dim('dissipation_rate_stoich')
h_dim = library.dim('heat_transfer_coefficient')
a_dim = library.dim('alpha')
Here are the adiabatic temperature profiles at minimium and moderate
:math:`\chi_{\rm st}` for various mixtures of volatiles and char.
.. code:: ipython3
for ia, a in enumerate(a_dim.values):
plt.plot(z_dim.values, library['temperature'][ia, 0, 0, :], label='$\\' + a_dim.name + '$' + f'={a:.2f}')
plt.legend(loc='best')
plt.xlabel(z_dim.name)
plt.ylabel('temperature')
plt.show()
for ia, a in enumerate(a_dim.values):
plt.plot(z_dim.values, library['temperature'][ia, 0, 6, :], label='$\\' + a_dim.name + '$' + f'={a:.2f}')
plt.legend(loc='best')
plt.xlabel(z_dim.name)
plt.ylabel('temperature')
plt.show()
.. image:: example_coal_combustion_model_files/example_coal_combustion_model_16_0.png
.. image:: example_coal_combustion_model_files/example_coal_combustion_model_16_1.png
And here are some contour plots of adiabatic profiles over
:math:`(\mathcal{Z},\chi_{\rm st})` for each :math:`\alpha` value. Note
the effect of :math:`\alpha` on the availablity of acetylene, a key
ingredient in soot formation.
.. code:: ipython3
from mpl_toolkits.mplot3d import axes3d
from matplotlib.colors import Normalize
fig = plt.figure()
ax = fig.gca(projection='3d')
z = library.mixture_fraction_grid[0, 0, :, :]
x = np.log10(library.dissipation_rate_stoich_grid[0, 0, :, :])
for ia, alpha in enumerate(adim.values):
ax.contourf(z, x, l['temperature'][ia, 0, :, :], offset=alpha,
cmap='inferno', levels=30, norm=Normalize(vmin=300, vmax=2400))
ax.set_zlim([0, 0.7])
ax.set_xlabel('$\\mathcal{Z}$')
ax.set_ylabel('$\\log_{10}\\chi_{\\rm st}$ (Hz)')
ax.set_zlabel('$\\alpha$')
ax.set_zticks([0, 0.1, 0.3, 0.5, 0.7])
ax.set_title('gas temperature (K)')
fig.set_size_inches(8, 8)
plt.show()
fig = plt.figure()
ax = fig.gca(projection='3d')
for ia, alpha in enumerate(adim.values):
ax.contourf(z, x, l['mass fraction OH'][ia, 0, :, :], offset=alpha,
cmap='Purples', norm=Normalize(vmin=0, vmax=1e-2), alpha=0.8)
ax.set_zlim([0, 0.7])
ax.set_xlabel('$\\mathcal{Z}$')
ax.set_ylabel('$\\log_{10}\\chi_{\\rm st}$ (Hz)')
ax.set_zlabel('$\\alpha$')
ax.set_zticks([0, 0.1, 0.3, 0.5, 0.7])
ax.set_title('mass fraction OH')
fig.set_size_inches(8, 8)
plt.show()
fig = plt.figure()
ax = fig.gca(projection='3d')
for ia, alpha in enumerate(adim.values):
ax.contourf(z, x, l['mass fraction C2H2'][ia, 0, :, :], offset=alpha,
cmap='Oranges', norm=Normalize(vmin=0, vmax=1e-2), alpha=0.8)
ax.set_zlim([0, 0.7])
ax.set_xlabel('$\\mathcal{Z}$')
ax.set_ylabel('$\\log_{10}\\chi_{\\rm st}$ (Hz)')
ax.set_zlabel('$\\alpha$')
ax.set_zticks([0, 0.1, 0.3, 0.5, 0.7])
ax.set_title('mass fraction C2H2')
fig.set_size_inches(8, 8)
plt.show()
.. image:: example_coal_combustion_model_files/example_coal_combustion_model_18_0.png
.. image:: example_coal_combustion_model_files/example_coal_combustion_model_18_1.png
.. image:: example_coal_combustion_model_files/example_coal_combustion_model_18_2.png
<file_sep># Spitfire
A Python-C++ library for building tabulated chemistry models and solving differential equations
Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
Version 1.02.01
Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this
software.
Questions? Contact <NAME> (<EMAIL>)
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------
Licenses of third-party libraries may be found at the following locations.
- NumPy: https://numpy.org/license.html
- SciPy: https://github.com/scipy/scipy/blob/master/LICENSE.txt
- Cantera: https://github.com/Cantera/cantera/blob/master/License.txt
- matplotlib (also, see below): https://matplotlib.org/users/license.html
- Cython (also, see below): https://github.com/cython/cython/blob/master/LICENSE.txt
- sphinx: https://github.com/sphinx-doc/sphinx/blob/master/LICENSE
- sphinx-rtd-theme: https://pypi.python.org/pypi/sphinx_rtd_theme/
- numpydoc: https://github.com/numpy/numpydoc/blob/master/LICENSE.txt
----------------------------------------------------------------
----
Cython copyright notice
----
Copyright 2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, et al..
All rights reserved. Licensed under the Apache License, Version 2.0, you may not use this file except in
compliance with the Apache License. You may obtain a copy of the Apache License at
http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing,
software distributed under the Apache License is distributed on an “AS IS” BASIS, WITHOUT WARRENTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the Apache License for the specific language
governing permissions and limitations under the Apache License.
----
Matplotlib license agreement Copyright © 2012-2013 Matplotlib Development Team; All Rights Reserved
----
Copyright Policy <NAME> began matplotlib around 2003. Since shortly before his passing in 2012, Michael
Droettboom has been the lead maintainer of matplotlib, but, as has always been the case, matplotlib is the
work of many.
Prior to July of 2013, and the 1.3.0 release, the copyright of the source code was held by John Hunter. As
of July 2013, and the 1.3.0 release, matplotlib has moved to a shared copyright model.
matplotlib uses a shared copyright model. Each contributor maintains copyright over their contributions to
matplotlib. But, it is important to note that these contributions are typically only changes to the
repositories. Thus, the matplotlib source code, in its entirety, is not the copyright of any single person
or institution. Instead, it is the collective copyright of the entire matplotlib Development Team. If
individual contributors want to maintain a record of what changes/contributions they have specific copyright
on, they should indicate their copyright in the commit message of the change, when they commit the change to
one of the matplotlib repositories.
The Matplotlib Development Team is the set of all contributors to the matplotlib project. A full list can be
obtained from the git version control logs.
License agreement for matplotlib 3.1.1 1. This LICENSE AGREEMENT is between the Matplotlib Development Team
("MDT"), and the Individual or Organization ("Licensee") accessing and otherwise using matplotlib software
in source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, MDT hereby grants Licensee a nonexclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare
derivative works, distribute, and otherwise use matplotlib 3.1.1 alone or in any derivative version,
provided, however, that MDT's License Agreement and MDT's notice of copyright, i.e., "Copyright (c)
2012-2013 Matplotlib Development Team; All Rights Reserved" are retained in matplotlib 3.1.1 alone or in any
derivative version prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib 3.1.1 or any
part thereof, and wants to make the derivative work available to others as provided herein, then Licensee
hereby agrees to include in any such work a brief summary of the changes made to matplotlib 3.1.1.
4. MDT is making matplotlib 3.1.1 available to Licensee on an "AS IS" basis. MDT MAKES NO REPRESENTATIONS OR
WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, MDT MAKES NO AND DISCLAIMS ANY
REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
MATPLOTLIB 3.1.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. MDT SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB 3.1.1 FOR ANY INCIDENTAL, SPECIAL,
OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB
3.1.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or
joint venture between MDT and Licensee. This License Agreement does not grant permission to use MDT
trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any
third party.
8. By copying, installing or otherwise using matplotlib 3.1.1, Licensee agrees to be bound by the terms and
conditions of this License Agreement.
License agreement for matplotlib versions prior to 1.3.0 1. This LICENSE AGREEMENT is between <NAME>
("JDH"), and the Individual or Organization ("Licensee") accessing and otherwise using matplotlib software
in source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, JDH hereby grants Licensee a nonexclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare
derivative works, distribute, and otherwise use matplotlib 3.1.1 alone or in any derivative version,
provided, however, that JDH's License Agreement and JDH's notice of copyright, i.e., "Copyright (c)
2002-2009 <NAME>; All Rights Reserved" are retained in matplotlib 3.1.1 alone or in any derivative
version prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib 3.1.1 or any
part thereof, and wants to make the derivative work available to others as provided herein, then Licensee
hereby agrees to include in any such work a brief summary of the changes made to matplotlib 3.1.1.
4. JDH is making matplotlib 3.1.1 available to Licensee on an "AS IS" basis. JDH MAKES NO REPRESENTATIONS OR
WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND DISCLAIMS ANY
REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
MATPLOTLIB 3.1.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB 3.1.1 FOR ANY INCIDENTAL, SPECIAL,
OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB
3.1.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or
joint venture between JDH and Licensee. This License Agreement does not grant permission to use JDH
trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any
third party.
8. By copying, installing or otherwise using matplotlib 3.1.1, Licensee agrees to be bound by the terms and
conditions of this License Agreement.
<file_sep>import unittest
from numpy import exp, log, mean, array, abs
from spitfire import GeneralAdaptiveERK, odesolve
class ExponentialDecayProblem(object):
def __init__(self):
self.decay_constant = -1.
self.lhs_inverse = None
def rhs(self, t, state):
return self.decay_constant * state
def validate_method(method):
edp = ExponentialDecayProblem()
rhs = edp.rhs
dtlist = [0.1, 0.05, 0.025, 0.0125]
errors = []
tf = 1.0
for dt in dtlist:
qf = odesolve(rhs, array([1.]), array([tf]), method=method, step_size=dt)
errors.append(abs(exp(-tf) - qf))
order_list = []
for idx in range(len(errors) - 1):
order_list.append(log(errors[idx] / errors[idx + 1]) / log(dtlist[idx] / dtlist[idx + 1]))
observed_order = mean(array(order_list))
success = method.order - 0.1 < observed_order < method.order + 0.1
return success
def create_test(m):
def test(self):
self.assertTrue(validate_method(m))
return test
class TestOrderOfAccuracy(unittest.TestCase):
pass
explicit_methods = [{'name': 'Forward Euler',
'A': array([[0.]]),
'b': array([1.]),
'order': 1},
{'name': 'Trapezoidal',
'A': array([[0., 0.],
[1., 0.]]),
'b': array([0.5, 0.5]),
'order': 2},
{'name': 'Trapezoidal_with_Euler',
'A': array([[0., 0.],
[1., 0.]]),
'b': array([0.5, 0.5]),
'bhat': array([1., 0.]),
'order': 2},
{'name': 'Midpoint',
'A': array([[0., 0.],
[0.5, 0.]]),
'b': array([0., 1.]),
'order': 2},
{'name': 'Ralston',
'A': array([[0., 0.],
[2. / 3., 0.]]),
'b': array([0.25, 0.75]),
'order': 2},
{'name': 'Classical RK4',
'A': array([[0., 0., 0., 0.],
[0.5, 0., 0., 0.],
[0., 0.5, 0., 0.],
[0., 0., 1., 0.]]),
'b': array([1. / 6., 1. / 3., 1. / 3., 1. / 6.]),
'order': 4}]
for method_dict in explicit_methods:
method = GeneralAdaptiveERK(name=method_dict['name'],
order=method_dict['order'],
A=method_dict['A'],
b=method_dict['b'],
bhat=None if 'bhat' not in method_dict else method_dict['bhat'])
setattr(TestOrderOfAccuracy, 'test_general_erk_' + method_dict['name'], create_test(method))
if __name__ == '__main__':
unittest.main()
<file_sep>"""
This module contains Spitfire's analytical Jacobian and numerical methods 'engine' named griffon, which is written in C++ and wrapped by Cython
"""
<file_sep>import unittest
from spitfire import Library, Dimension
import numpy as np
from os import remove
from shutil import rmtree
from os.path import isfile
import pickle
machine_epsilon = np.finfo(float).eps
class SaveAndLoad(unittest.TestCase):
def test_save_and_load_1d(self):
file_name = 'l1test.pkl'
if isfile(file_name):
remove(file_name)
l1 = Library(Dimension('x', np.linspace(0, 1, 16)))
l1['f'] = l1.x_grid
l1['g'] = np.exp(l1.x_grid)
l1.extra_attributes['name'] = 'my_library_name'
l1.save_to_file(file_name)
l2 = Library.load_from_file(file_name)
remove(file_name)
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['g'] - l2['g']) < 10. * machine_epsilon))
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_save_and_load_2d(self):
file_name = 'l1test.pkl'
if isfile(file_name):
remove(file_name)
l1 = Library(Dimension('x', np.linspace(0, 1, 16)),
Dimension('y', np.linspace(1, 2, 8)))
l1['f'] = l1.x_grid + l1.y_grid
l1['g'] = np.exp(l1.x_grid) * np.cos(np.pi * 2. * l1.y_grid)
l1.extra_attributes['name'] = 'my_library_name'
l1.save_to_file(file_name)
l2 = Library.load_from_file(file_name)
remove(file_name)
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['g'] - l2['g']) < 10. * machine_epsilon))
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_save_and_load_2d_log_scaled(self):
file_name = 'l1test.pkl'
if isfile(file_name):
remove(file_name)
l1 = Library(Dimension('x', np.linspace(0, 1, 16)),
Dimension('y', np.logspace(1, 2, 8), log_scaled=True))
l1['f'] = l1.x_grid + l1.y_grid
l1['g'] = np.exp(l1.x_grid) * np.cos(np.pi * 2. * l1.y_grid)
l1.extra_attributes['name'] = 'my_library_name'
l1.save_to_file(file_name)
l2 = Library.load_from_file(file_name)
remove(file_name)
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['g'] - l2['g']) < 10. * machine_epsilon))
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
self.assertFalse(l1.dim('x').log_scaled)
self.assertFalse(l2.dim('x').log_scaled)
self.assertTrue(l1.dim('y').log_scaled)
self.assertTrue(l2.dim('y').log_scaled)
def test_save_and_load_3d(self):
file_name = 'l1test.pkl'
if isfile(file_name):
remove(file_name)
l1 = Library(Dimension('x', np.linspace(0, 1, 16)),
Dimension('y', np.linspace(1, 2, 8)),
Dimension('z', np.linspace(2, 3, 4)))
l1['f'] = l1.x_grid + l1.y_grid + l1.z_grid
l1['g'] = np.exp(l1.x_grid) * np.cos(np.pi * 2. * l1.y_grid) * l1.z_grid
l1.extra_attributes['name'] = 'my_library_name'
l1.save_to_file(file_name)
l2 = Library.load_from_file(file_name)
remove(file_name)
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['g'] - l2['g']) < 10. * machine_epsilon))
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_raw_pickle_3d(self):
file_name = 'l1test.pkl'
if isfile(file_name):
remove(file_name)
l1 = Library(Dimension('x', np.linspace(0, 1, 16)),
Dimension('y', np.linspace(1, 2, 8)),
Dimension('z', np.linspace(2, 3, 4)))
l1['f'] = l1.x_grid + l1.y_grid + l1.z_grid
l1['g'] = np.exp(l1.x_grid) * np.cos(np.pi * 2. * l1.y_grid) * l1.z_grid
l1.extra_attributes['name'] = 'my_library_name'
with open(file_name, 'wb') as f:
pickle.dump(l1, f)
with open(file_name, 'rb') as f:
l2 = pickle.load(f)
remove(file_name)
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['g'] - l2['g']) < 10. * machine_epsilon))
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_save_to_text(self):
xvalues = np.linspace(0, 1, 16)
yvalues = np.linspace(1, 2, 8)
zvalues = np.linspace(2, 3, 4)
l1 = Library(Dimension('x', xvalues),
Dimension('y', yvalues),
Dimension('z', zvalues))
fvalues = l1.x_grid + l1.y_grid + l1.z_grid
gvalues = np.exp(l1.x_grid) * np.cos(np.pi * 2. * l1.y_grid) * l1.z_grid
lib_shape = fvalues.shape
l1['f'] = fvalues
l1['g'] = gvalues
lib_name = 'my_library_name'
l1.extra_attributes['name'] = lib_name
dir_name = 'out'
l1.save_to_text_directory(dir_name, ravel_order='F')
xread = np.loadtxt(dir_name + f'/bulkdata_ivar_x.txt')
yread = np.loadtxt(dir_name + f'/bulkdata_ivar_y.txt')
zread = np.loadtxt(dir_name + f'/bulkdata_ivar_z.txt')
fread = np.loadtxt(dir_name + f'/bulkdata_dvar_f.txt').reshape(lib_shape, order='F')
gread = np.loadtxt(dir_name + f'/bulkdata_dvar_g.txt').reshape(lib_shape, order='F')
with open(dir_name + '/metadata_user_defined_attributes.txt', 'r') as f:
ea_read = f.readline()
with open(dir_name + '/metadata_independent_variables.txt', 'r') as f:
iv_lines = f.readlines()
with open(dir_name + '/metadata_dependent_variables.txt', 'r') as f:
dv_lines = f.readlines()
rmtree(dir_name)
self.assertTrue(np.all(np.abs(xvalues - xread) < 100. * machine_epsilon))
self.assertTrue(np.all(np.abs(yvalues - yread) < 100. * machine_epsilon))
self.assertTrue(np.all(np.abs(zvalues - zread) < 100. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvalues - fread) < 100. * machine_epsilon))
self.assertTrue(np.all(np.abs(gvalues - gread) < 100. * machine_epsilon))
self.assertTrue(ea_read, str(l1.extra_attributes))
self.assertTrue(all([ivf.strip() == ivn for (ivf, ivn) in zip(iv_lines, [d.name for d in l1.dims])]))
self.assertTrue(all([dvf.strip() == dvn.replace(' ', '_') for (dvf, dvn) in zip(dv_lines, l1.props)]))
if __name__ == '__main__':
unittest.main()
<file_sep>
[](https://opensource.org/licenses/BSD-3-Clause)
[](https://spitfire.readthedocs.io/en/latest/?badge=latest)
Spitfire is a Python/C++ library for solving complex chemistry and reaction-diffusion problems. It is most often used to construct tabulated chemistry models for reacting flow simulations. It also solves canonical reactor models and provides efficient, extensible numerical time integration capabilities. Spitfire has been used and developed primarily at Sandia National Laboratories and the University of Utah.
- [Installing Spitfire](#installing-spitfire)
- [Prerequisites](#prerequisites)
- [Python and C++ Dependencies](#python-and-c-dependencies)
- [`TabProps` for Presumed PDF Mixing Models](#tabprops-for-presumed-pdf-mixing-models)
- [Building and Installing Spitfire](#building-and-installing-spitfire)
- [Running the Tests](#running-the-tests)
- [Building the Documentation](#building-the-documentation)
# Installing Spitfire
## Prerequisites
### Python and C++ Dependencies
Spitfire requires Python3 (tested with 3.6, 3.7) with the following packages:
- `NumPy`
- `SciPy`
- `matplotlib`
- `Cython`
- `Cantera`
- `sphinx`
- `NumPydoc`
- `GitPython`
We also highly recommend installing `jupyter`.
Conda provides the easiest method of installing Spitfire's Python dependencies, primarily because it can install the Cantera Python interface easily.
The lines below will install Spitfire's dependencies.
On some systems, installing dependencies such as NumPy through conda-forge can be required.
```
conda install numpy scipy matplotlib Cython sphinx numpydoc
conda install -c conda-forge gitpython
conda install -c cantera cantera
```
Along with the optional `conda install -c anaconda jupyter`.
The pip package manager may also be used although this is more difficult because you'll have to install the Cantera Python interface yourself (see their [GitHub repository](https://github.com/Cantera/cantera) for guidance).
Before installing Cantera, install the packages noted above, most of which can be done with `pip3`.
Finally, Spitfire requires a C++11 compiler and the BLAS/LAPACK libraries, which are commonly available on many systems
and conda-based toolchains can provide these. Often simply installing NumPy, as already required, is sufficient.
### `TabProps` for Presumed PDF Mixing Models
Spitfire can leverage the [TabProps](https://gitlab.multiscale.utah.edu/common/TabProps/) code developed at the University of Utah
to provide presumed PDF mixing models. TabProps also provides arbitrary order piecewise Lagrange interpolants for structured data
in up to five dimensions. A Python interface may be built to enable these capabilities in Spitfire.
Without TabProps, Spitfire still provides fully featured reaction modeling capabilities,
so if you aren't interested in mixing models, installing TabProps is optional.
TabProps and its Python interface can be installed with a conda toolchain using the following commands.
Fortunately conda can install a version of boost for C++ dependency.
```
conda install -c anaconda cmake
conda install -c conda-forge boost-cpp
conda install -c conda-forge pybind11
git clone https://gitlab.multiscale.utah.edu/common/TabProps.git
cd TabProps
mkdir build
cd build
cmake .. \
-DENABLE_PYTHON=ON \
-DENABLE_MIXMDL=ON \
-DTabProps_UTILS=OFF \
-DTabProps_PREPROCESSOR=OFF \
-DTabProps_ENABLE_TESTING=ON \
-DCMAKE_BUILD_TYPE=Release
make -j4 install
```
Note that `cmake` may struggle to find the Python interpreter of your conda environment.
If this happens (you might see permission issues or see `/usr/lib` in the python paths, etc.),
you can add these lines to the `cmake` call above.
Substitute `[anaconda-path]` with something like `/opt/anaconda3`, change `[env-name]` to
the name of your conda environment, and replace `[py_minor_version]` with 6 or 7 for python 3.6, 3.7.
```
-DPYTHON_LIBRARY=[anaconda-path]/envs/[env-name]/lib/libpython3.[py_minor_version]m.a \
-DPYTHON_INCLUDE_DIR=[anaconda-path]/envs/[env-name]/bin/python3.[py_minor_version]m \
-DPYTHON_EXECUTABLE=[anaconda-path]/envs/[env-name]/bin/python3.[py_minor_version] \
```
## Building and Installing Spitfire
After installing the prerequisites, clone the Spitfire repository, `cd` to the base repository directory,
and run the following command.
```
python3 setup.py install
```
If you want to run tests and build the documentation yourself, an in-place build is also required:
```
python3 setup.py build_ext --inplace install
```
## Running the Tests
Spitfire has a number of tests that verify correctness or regression of the code.
After installing Spitfire or developing code it is a great idea to run these tests.
To do this, go to the base repository directory and enter the following command:
```
python3 -m unittest discover -s tests
```
## Building the Documentation
First, be aware that documentation for Spitfire is hosted by [Read the Docs](https://spitfire.readthedocs.io/en/latest/).
A number of demonstrations as well as some basic theory are available in the documentation.
Second, documenting multi-language software in scientific applications, especially when extensibility is an explicit aim, is hard!
Any questions, suggestions, or help you could provide would be appreciated greatly.
If you want your own copy of the docs, or if you're developing in Spitfire and want to make sure your new documentation looks good, you can simply run the following commands,
```
cd docs
make html
```
and then point your favorite web browser to the `build/html/index.html` file.
Sphinx enables other forms of documentation but HTML has been our primary target.
<file_sep>try:
import importlib.resources as pkg_resources
except ImportError:
import importlib_resources as pkg_resources
def datafile(filename):
"""Obtain the complete path to the installed file in the src/spitfire/data directory."""
with pkg_resources.path('spitfire.data', filename) as p:
path = str(p)
return path
<file_sep>import unittest
from spitfire import Library, Dimension
from spitfire.chemistry.library import LibraryIndexError
import numpy as np
from copy import copy, deepcopy
machine_epsilon = np.finfo(float).eps
class Slice1D(unittest.TestCase):
def test_full(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 16)))
l1['f'] = np.exp(l1.x_grid)
l1.extra_attributes['name'] = 'my_library_name'
l2 = l1[:]
self.assertTrue(np.all(np.abs(l1.x_grid - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(l2.shape == l1.x_grid.shape)
self.assertTrue(l2.size == l1.x_grid.size)
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_partial(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 16)))
l1['f'] = np.exp(l1.x_grid)
l1.extra_attributes['name'] = 'my_library_name'
n1 = 2
n2 = 8
l2 = l1[n1:n2]
self.assertTrue(np.all(np.abs(l1.x_grid[n1:n2] - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'][n1:n2] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(l2.shape == l1.x_grid[n1:n2].shape)
self.assertTrue(l2.size == l1.x_grid[n1:n2].size)
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_single(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 16)))
l1['f'] = np.exp(l1.x_grid)
l1.extra_attributes['name'] = 'my_library_name'
n1 = 2
n2 = n1 + 1
l2 = l1[n1:n2]
self.assertTrue(np.all(np.abs(l1.x_grid[n1:n2] - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'][n1:n2] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(l2.shape == l1.x_grid[n1:n2].shape)
self.assertTrue(l2.size == l1.x_grid[n1:n2].size)
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_copy(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 16)))
l1['f'] = np.exp(l1.x_grid)
l1.extra_attributes['name'] = 'my_library_name'
l2 = copy(l1)
l3 = deepcopy(l1)
l4 = Library.deepcopy(l1)
self.assertTrue(np.all(np.abs(l1.x_grid - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.x_grid - l3.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l3['f']) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.x_grid - l4.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l4['f']) < 10. * machine_epsilon))
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_invalid_number(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 16)))
try:
l2 = l1[:, :]
self.assertTrue(False)
except LibraryIndexError:
self.assertTrue(True)
def test_multiple_nonslice_args_1(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 16)))
try:
l2 = l1['f', :]
self.assertTrue(False)
except LibraryIndexError:
self.assertTrue(True)
def test_multiple_nonslice_args_2(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 16)))
try:
l2 = l1[:, 'g']
self.assertTrue(False)
except LibraryIndexError:
self.assertTrue(True)
def test_multiple_nonslice_args_3(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 16)))
try:
l2 = l1['f', 'g']
self.assertTrue(False)
except LibraryIndexError:
self.assertTrue(True)
class Slice2D(unittest.TestCase):
def test_full(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 2)), Dimension('y', np.linspace(-1, 1, 3)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid)
l1.extra_attributes['name'] = 'my_library_name'
l2 = l1[:, :]
self.assertTrue(np.all(np.abs(l1.x_grid - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.y_grid - l2.y_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(l2.shape == l1.x_grid.shape)
self.assertTrue(l2.size == l1.x_grid.size)
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
l3 = l1[:]
self.assertTrue(np.all(np.abs(l1.x_grid - l3.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.y_grid - l3.y_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l3['f']) < 10. * machine_epsilon))
self.assertTrue(l3.shape == l1.x_grid.shape)
self.assertTrue(l3.size == l1.x_grid.size)
self.assertTrue(l1.extra_attributes['name'] == l3.extra_attributes['name'])
def test_partial(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 10)), Dimension('y', np.linspace(-1, 1, 10)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid)
l1.extra_attributes['name'] = 'my_library_name'
n1x = 2
n2x = 8
n1y = 1
n2y = -1
l2 = l1[n1x:n2x, n1y:n2y]
self.assertTrue(np.all(np.abs(l1.x_grid[n1x:n2x, n1y:n2y] - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'][n1x:n2x, n1y:n2y] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(l2.shape == l1.x_grid[n1x:n2x, n1y:n2y].shape)
self.assertTrue(l2.size == l1.x_grid[n1x:n2x, n1y:n2y].size)
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_single(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 10)), Dimension('y', np.linspace(-1, 1, 10)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid)
l1.extra_attributes['name'] = 'my_library_name'
n1x = 2
n2x = n1x + 1
n1y = 1
n2y = -1
l2 = l1[n1x:n2x, n1y:n2y]
self.assertTrue(np.all(np.abs(l1.x_grid[n1x:n2x, n1y:n2y] - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'][n1x:n2x, n1y:n2y] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(l2.shape == l1.x_grid[n1x:n2x, n1y:n2y].shape)
self.assertTrue(l2.size == l1.x_grid[n1x:n2x, n1y:n2y].size)
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_squeeze(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 10)), Dimension('y', np.linspace(-1, 1, 10)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid)
l1.extra_attributes['name'] = 'my_library_name'
iy = 3
l3 = Library.squeeze(l1[:, iy])
self.assertTrue(np.all(np.abs(l1['f'][:, iy] - l3['f']) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(np.squeeze(l1.x_grid[:, iy]) - l3.x_grid) < 10. * machine_epsilon))
self.assertTrue(l1.extra_attributes['name'] == l3.extra_attributes['name'])
def test_copy(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 10)), Dimension('y', np.linspace(-1, 1, 10)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid)
l1.extra_attributes['name'] = 'my_library_name'
l2 = copy(l1)
l3 = Library.copy(l1)
self.assertTrue(np.all(np.abs(l1.x_grid - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.y_grid - l2.y_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.x_grid - l3.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.y_grid - l3.y_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l3['f']) < 10. * machine_epsilon))
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
self.assertTrue(l1.extra_attributes['name'] == l3.extra_attributes['name'])
def test_invalid_number_3(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 2)), Dimension('y', np.linspace(-1, 1, 3)))
try:
l2 = l1[:, :, :]
self.assertTrue(False)
except LibraryIndexError:
self.assertTrue(True)
class Slice3D(unittest.TestCase):
def test_full(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 2)),
Dimension('y', np.linspace(-1, 1, 3)),
Dimension('z', np.logspace(-1, 1, 4)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1.extra_attributes['name'] = 'my_library_name'
l2 = l1[:, :, :]
self.assertTrue(np.all(np.abs(l1.x_grid - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.y_grid - l2.y_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.z_grid - l2.z_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(l2.shape == l1.x_grid.shape)
self.assertTrue(l2.size == l1.x_grid.size)
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
l3 = l1[:]
self.assertTrue(np.all(np.abs(l1.x_grid - l3.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.y_grid - l3.y_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.z_grid - l3.z_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l3['f']) < 10. * machine_epsilon))
self.assertTrue(l3.shape == l1.x_grid.shape)
self.assertTrue(l3.size == l1.x_grid.size)
self.assertTrue(l1.extra_attributes['name'] == l3.extra_attributes['name'])
def test_partial(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 10)),
Dimension('y', np.linspace(-1, 1, 4)),
Dimension('z', np.logspace(-1, 1, 7)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1.extra_attributes['name'] = 'my_library_name'
n1x = 2
n2x = 8
n1y = 1
n2y = -1
n1z = 3
n2z = 5
l2 = l1[n1x:n2x, n1y:n2y, n1z:n2z]
self.assertTrue(np.all(np.abs(l1.x_grid[n1x:n2x, n1y:n2y, n1z:n2z] - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'][n1x:n2x, n1y:n2y, n1z:n2z] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(l2.shape == l1.x_grid[n1x:n2x, n1y:n2y, n1z:n2z].shape)
self.assertTrue(l2.size == l1.x_grid[n1x:n2x, n1y:n2y, n1z:n2z].size)
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_single(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 10)),
Dimension('y', np.linspace(-1, 1, 4)),
Dimension('z', np.logspace(-1, 1, 7)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1.extra_attributes['name'] = 'my_library_name'
n1x = 2
n2x = 8
n1y = 1
n2y = -1
n1z = 3
n2z = n1z + 1
l2 = l1[n1x:n2x, n1y:n2y, n1z:n2z]
self.assertTrue(np.all(np.abs(l1.x_grid[n1x:n2x, n1y:n2y, n1z:n2z] - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'][n1x:n2x, n1y:n2y, n1z:n2z] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(l2.shape == l1.x_grid[n1x:n2x, n1y:n2y, n1z:n2z].shape)
self.assertTrue(l2.size == l1.x_grid[n1x:n2x, n1y:n2y, n1z:n2z].size)
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_single_internal(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 10)),
Dimension('y', np.linspace(-1, 1, 4)),
Dimension('z', np.logspace(-1, 1, 7)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1.extra_attributes['name'] = 'my_library_name'
n1x = 2
n2x = 8
n1y = 1
n2y = n1y + 1
n1z = 3
n2z = 6
l2 = l1[n1x:n2x, n1y:n2y, n1z:n2z]
self.assertTrue(np.all(np.abs(l1.x_grid[n1x:n2x, n1y:n2y, n1z:n2z] - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'][n1x:n2x, n1y:n2y, n1z:n2z] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(l2.shape == l1.x_grid[n1x:n2x, n1y:n2y, n1z:n2z].shape)
self.assertTrue(l2.size == l1.x_grid[n1x:n2x, n1y:n2y, n1z:n2z].size)
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
def test_squeeze(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 10)),
Dimension('y', np.linspace(-1, 1, 4)),
Dimension('z', np.logspace(-1, 1, 7)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1.extra_attributes['name'] = 'my_library_name'
iy = 2
l3 = Library.squeeze(l1[:, iy, :])
self.assertTrue(np.all(np.abs(np.squeeze(l1.x_grid[:, iy, :]) - l3.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(np.squeeze(l1.z_grid[:, iy, :]) - l3.z_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(np.squeeze(l1['f'][:, iy, :]) - l3['f']) < 10. * machine_epsilon))
self.assertTrue(l1.extra_attributes['name'] == l3.extra_attributes['name'])
def test_copy(self):
l1 = Library(Dimension('x', np.linspace(0, 1, 10)),
Dimension('y', np.linspace(-1, 1, 4)),
Dimension('z', np.logspace(-1, 1, 7)))
l1['f'] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1.extra_attributes['name'] = 'my_library_name'
l2 = copy(l1)
l3 = Library.copy(l1)
self.assertTrue(np.all(np.abs(l1.x_grid - l2.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.y_grid - l2.y_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.z_grid - l2.z_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l2['f']) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.x_grid - l3.x_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.y_grid - l3.y_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1.z_grid - l3.z_grid) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1['f'] - l3['f']) < 10. * machine_epsilon))
self.assertTrue(l1.extra_attributes['name'] == l2.extra_attributes['name'])
self.assertTrue(l1.extra_attributes['name'] == l3.extra_attributes['name'])
def test_view(self):
slices = (slice(0, None, None), slice(1, 3, None), slice(1, -3, None))
l1 = Library(Dimension('x', np.linspace(0, 1, 10)),
Dimension('y', np.linspace(-1, 1, 4)),
Dimension('z', np.logspace(-1, 1, 7)))
gold_float = 0.5
gold_array = np.exp(-2. * l1.x_grid[slices])
fvals = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
# start with float argument
g = gold_float
# set slice of original array
fvals[:, :, :] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1['f'] = fvals
l2 = l1[slices]
fvals[slices] = g
self.assertTrue(np.all(np.abs(l1['f'][slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1[slices]['f'] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvals[slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l2['f'] - g) < 10. * machine_epsilon))
# set slice of library property
fvals[:, :, :] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1['f'] = fvals
l2 = l1[slices]
l1['f'][slices] = g
self.assertTrue(np.all(np.abs(l1['f'][slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1[slices]['f'] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvals[slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l2['f'] - g) < 10. * machine_epsilon))
# set property of library slice
fvals[:, :, :] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1['f'] = fvals
l2 = l1[slices]
l1[slices]['f'] = g
self.assertTrue(np.all(np.abs(l1['f'][slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1[slices]['f'] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvals[slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l2['f'] - g) < 10. * machine_epsilon))
# set slice of library view property
fvals[:, :, :] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1['f'] = fvals
l2 = l1[slices]
l2['f'][:, :, :] = g
self.assertTrue(np.all(np.abs(l1['f'][slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1[slices]['f'] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvals[slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l2['f'] - g) < 10. * machine_epsilon))
# set property of library view
fvals[:, :, :] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1['f'] = fvals
l2 = l1[slices]
l2['f'] = g
self.assertTrue(np.all(np.abs(l1['f'][slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1[slices]['f'] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvals[slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l2['f'] - g) < 10. * machine_epsilon))
# repeat with numpy array argument
g = gold_array
# set slice of original array
fvals[:, :, :] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1['f'] = fvals
l2 = l1[slices]
fvals[slices] = g
self.assertTrue(np.all(np.abs(l1['f'][slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1[slices]['f'] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvals[slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l2['f'] - g) < 10. * machine_epsilon))
# set slice of library property
fvals[:, :, :] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1['f'] = fvals
l2 = l1[slices]
l1['f'][slices] = g
self.assertTrue(np.all(np.abs(l1['f'][slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1[slices]['f'] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvals[slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l2['f'] - g) < 10. * machine_epsilon))
# set property of library slice
fvals[:, :, :] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1['f'] = fvals
l2 = l1[slices]
l1[slices]['f'] = g
self.assertTrue(np.all(np.abs(l1['f'][slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1[slices]['f'] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvals[slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l2['f'] - g) < 10. * machine_epsilon))
# set slice of library view property
fvals[:, :, :] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1['f'] = fvals
l2 = l1[slices]
l2['f'][:, :, :] = g
self.assertTrue(np.all(np.abs(l1['f'][slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1[slices]['f'] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvals[slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l2['f'] - g) < 10. * machine_epsilon))
# set property of library view
fvals[:, :, :] = np.exp(l1.x_grid) * np.cos(l1.y_grid) * np.log(l1.z_grid)
l1['f'] = fvals
l2 = l1[slices]
l2['f'] = g
self.assertTrue(np.all(np.abs(l1['f'][slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l1[slices]['f'] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(fvals[slices] - g) < 10. * machine_epsilon))
self.assertTrue(np.all(np.abs(l2['f'] - g) < 10. * machine_epsilon))
if __name__ == '__main__':
unittest.main()
<file_sep>import unittest
from numpy import ones, hstack
from cantera import Solution, one_atm
import numpy as np
from spitfire import ChemicalMechanismSpec
from os.path import join, abspath
from subprocess import getoutput
test_mech_directory = abspath(join('tests', 'test_mechanisms', 'old_xmls'))
mechs = [x.replace('.yaml', '') for x in getoutput('ls ' + test_mech_directory + ' | grep .yaml').split('\n')]
def validate_on_mechanism(mech, temperature, pressure, full_Jacobian, isochoric):
xml = join(test_mech_directory, mech + '.yaml')
r = ChemicalMechanismSpec(xml, 'gas').griffon
gas = Solution(xml)
ns = gas.n_species
T = temperature
p = pressure
gas.TPX = T, p, ones(ns)
y = gas.Y
rho = gas.density_mass
if full_Jacobian and isochoric:
state = hstack((rho, T, y[:-1]))
rhsGRTemporary = np.empty(ns + 1)
jac_dense = np.empty((ns + 1) * (ns + 1))
jac_sparse = np.empty((ns + 1) * (ns + 1))
r.reactor_jac_isochoric(state, 0, 0, np.ndarray(1), 0, 0, 0, 0, 0, 0, 0, False, 0, rhsGRTemporary, jac_dense)
r.reactor_jac_isochoric(state, 0, 0, np.ndarray(1), 0, 0, 0, 0, 0, 0, 0, False, 2, rhsGRTemporary, jac_sparse)
jac_dense = jac_dense.reshape((ns + 1, ns + 1), order='F')
jac_sparse = jac_sparse.reshape((ns + 1, ns + 1), order='F')
elif full_Jacobian and not isochoric:
state = hstack((T, y[:-1]))
k = np.empty(ns)
jac_dense = np.empty(ns * ns)
jac_sparse = np.empty(ns * ns)
r.reactor_jac_isobaric(state, p, 0, np.ndarray(1), 0, 0, 0, 0, 0, 0, 0, False, 0, 0, k, jac_dense)
r.reactor_jac_isobaric(state, p, 0, np.ndarray(1), 0, 0, 0, 0, 0, 0, 0, False, 2, 0, k, jac_sparse)
jac_dense = jac_dense.reshape((ns, ns), order='F')
jac_sparse = jac_sparse.reshape((ns, ns), order='F')
else:
jac_dense = np.zeros((ns + 1) * (ns + 1))
jac_sparse = np.zeros((ns + 1) * (ns + 1))
r.prod_rates_primitive_sensitivities(rho, T, y, 0, jac_dense)
r.prod_rates_primitive_sensitivities(rho, T, y, 2, jac_sparse)
jac_dense = jac_dense.reshape((ns + 1, ns + 1), order='F')[:-1, :]
jac_sparse = jac_sparse.reshape((ns + 1, ns + 1), order='F')[:-1, :]
jac_fd = np.zeros_like(jac_dense)
rhsGR1 = np.zeros(ns)
rhsGR2 = np.zeros(ns)
dT = 1.e-4
dr = 1.e-4
dY = 1.e-4
r.production_rates(T, rho + dr, y, rhsGR1)
r.production_rates(T, rho - dr, y, rhsGR2)
jac_fd[:, 0] = (rhsGR1 - rhsGR2) / dr * 0.5
r.production_rates(T + dT, rho, y, rhsGR1)
r.production_rates(T - dT, rho, y, rhsGR2)
jac_fd[:, 1] = (rhsGR1 - rhsGR2) / dT * 0.5
for spec_idx in range(ns - 1):
Yp = np.copy(y)
Yp[spec_idx] += dY
Yp[-1] -= dY
Ym = np.copy(y)
Ym[spec_idx] -= dY
Ym[-1] += dY
r.production_rates(T, rho, Yp, rhsGR1)
r.production_rates(T, rho, Ym, rhsGR2)
jac_fd[:, 2 + spec_idx] = (rhsGR1 - rhsGR2) / dY * 0.5
pass_sparse_vs_dense_jac = np.linalg.norm(jac_dense.ravel() - jac_sparse.ravel(), ord=np.Inf) < 1.e-10
# if not pass_sparse_vs_dense_jac:
# print(mech)
# diff = abs(jac_dense - jac_sparse) / (abs(jac_dense) + 1.)
# nr, nc = jac_dense.shape
# print('dense')
# for ir in range(nr):
# for ic in range(nc):
# print(f'{jac_dense[ir, ic]:8.0e}', end=', ')
# print('')
# print('sparse')
# for ir in range(nr):
# for ic in range(nc):
# print(f'{jac_sparse[ir, ic]:8.0e}', end=', ')
# print('')
# print('finite difference')
# for ir in range(nr):
# for ic in range(nc):
# print(f'{jac_fd[ir, ic]:8.0e}', end=', ')
# print('')
# print('diff')
# for ir in range(nr):
# for ic in range(nc):
# print(f'{diff[ir, ic]:8.0e}' if diff[ir, ic] > 1.e-12 else f'{"":8}', end=', ')
# print('')
return pass_sparse_vs_dense_jac
def create_test(m, T, p, full_Jacobian, isochoric=True):
def test(self):
self.assertTrue(validate_on_mechanism(m, T, p, full_Jacobian, isochoric))
return test
class Accuracy(unittest.TestCase):
pass
temperature_dict = {'600K': 600., '1200K': 1200.}
pressure_dict = {'1atm': one_atm, '2atm': 2. * one_atm}
for mech in mechs:
for temperature in temperature_dict:
for pressure in pressure_dict:
jsdname = 'test_jac_sparse_vs_dense_isochoric_' + mech + '_' + temperature + '_' + pressure
setattr(Accuracy, jsdname, create_test(mech, temperature_dict[temperature], pressure_dict[pressure],
full_Jacobian=True, isochoric=True))
jsdname = 'test_jac_sparse_vs_dense_isobaric_' + mech + '_' + temperature + '_' + pressure
setattr(Accuracy, jsdname, create_test(mech, temperature_dict[temperature], pressure_dict[pressure],
full_Jacobian=True, isochoric=False))
jsdname = 'test_jac_sparse_vs_dense_sensitivites_' + mech + '_' + temperature + '_' + pressure
setattr(Accuracy, jsdname, create_test(mech, temperature_dict[temperature], pressure_dict[pressure],
full_Jacobian=False))
if __name__ == '__main__':
unittest.main()
<file_sep>Ignition Delay Profiles for a Two-Stage Ignition Fuel
=====================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - Computing the ignition delay of a DME-air mixture for a
range of temperatures and pressures
Introduction
------------
This demonstration shows how to use Spitfire to compute the ignition
delay of a homogeneous mixture. Next, we vary the temperature and
pressure to show the surprising ’’negative temperature coefficient"
(NTC) behavior in fuels that undergo two-stage ignition.
.. code:: ipython3
from spitfire import ChemicalMechanismSpec, HomogeneousReactor
import matplotlib.pyplot as plt
After some imports, we load up a dimethyl ether (DME) ignition mechanism
and blend equal parts DME/methane with air to obtain a stoichiometric
mixture.
.. code:: ipython3
mech = ChemicalMechanismSpec(cantera_xml='dme-bhagatwala.xml', group_name='dme-bhagatwala')
air = mech.stream(stp_air=True)
fuel = mech.stream('X', 'CH3OCH3:1, CH4:1')
blend = mech.mix_for_equivalence_ratio(1.0, fuel, air)
Computing Ignition Delay
------------------------
Next we specify the temperature and pressure of the mixture, put it into
a constant-pressure reactor, and use ``compute_ignition_delay()``.
.. code:: ipython3
from cantera import one_atm
blend.TP = 1200, 4 * one_atm
r = HomogeneousReactor(mech, blend, 'isobaric', 'adiabatic', 'closed')
tau = r.compute_ignition_delay()
print(f'Ignition delay for {blend.T:.1f} K, {blend.P / one_atm:.1f} atm is {tau*1e3:.2f} ms')
.. parsed-literal::
Ignition delay for 1200.0 K, 4.0 atm is 1.01 ms
Plotting Ignition Delay over T, P
---------------------------------
Now simply loop over temperature and pressure, resetting the blend
temperature and pressure as we go. Note that we specify
``first_time_step=1.e-9`` for ``compute_ignition_delay()``. This is
important for time integrator stability for the largest pressures which
ignite very early. The default initial time step of
:math:`10^{-6}\,{\rm s}` is a bit too large there.
.. code:: ipython3
from numpy import linspace, zeros_like
from time import perf_counter as timer
.. code:: ipython3
temperature_list = linspace(600., 1400., 20)
pressure_atm_list = [4., 10., 20., 50., 100., 200.]
tau_list = zeros_like(temperature_list)
colors_list = ['b', 'g', 'r', 'c', 'y', 'm']
markers_list = ['o', 's', '^', 'D', 'P', '*']
fig = plt.figure()
ax = plt.gca()
ax.set_xlabel('Temperature (K)')
ax.set_ylabel('Ignition Delay (us)')
ax.set_xlim([temperature_list.min() - 10, temperature_list.max() + 10])
plt.ion()
for pressure, marker, color in zip(pressure_atm_list, markers_list, colors_list):
for idx, temperature in enumerate(temperature_list):
blend.TP = temperature, pressure * one_atm
r = HomogeneousReactor(mech, blend, 'isobaric', 'adiabatic', 'closed')
tau_list[idx] = r.compute_ignition_delay(first_time_step=1.e-9)
ax.semilogy(temperature_list, tau_list * 1.e6, '-' + color + marker, label='{:.1f} atm'.format(pressure))
plt.legend()
plt.grid()
plt.show()
.. image:: ignition_delay_NTC_DME_files/ignition_delay_NTC_DME_9_0.png
Fuels such as DME and biodiesel are of interest partially due to their
low-temperature ignition pathways (advantageous for pollutant reduction)
but their chemistry is extremely complex. A reasonable first expectation
is that increasing temperature and pressure should always increase a
mixture’s overall reactivity, thus *decreasing* its ignition delay. This
is typically observed with most fuels (pressure is not trivial though -
even hydrogen-air mixtures show nonmonotonic behavior with pressure
variation - see CK Law’s combustion text for an excellent description).
However here we see increases in the ignition delay with temperature in
a range of temperatures, which seems to be pressure-dependent. This is
called “negative temperature coefficient” behavior and is due to
degenerate chain branching in the low-temperature chemical pathways.
It’s a very complex subject, and being able to quickly simulate ignition
behavior to match experimental data is a crucial aspect of our
understanding.
Conclusions
-----------
This notebook shows how to compute ignition delays of homogeneous
mixtures. This is a common task in chemical mechanism development for
combustion, and Spitfire makes it relatively painless.
<file_sep>"""
This is the base spitfire module directory.
"""
from .chemistry.library import Dimension, Library
from .chemistry.analysis import get_ct_solution_array, explosive_mode_analysis
from .chemistry.mechanism import ChemicalMechanismSpec, CanteraLoadError
from .chemistry.flamelet import Flamelet, FlameletSpec, compute_dissipation_rate
from .chemistry.reactors import HomogeneousReactor
from .chemistry.tabulation import build_adiabatic_eq_library, \
build_adiabatic_bs_library, \
build_adiabatic_slfm_library, \
build_unreacted_library, \
build_nonadiabatic_defect_bs_library, \
build_nonadiabatic_defect_eq_library, \
build_nonadiabatic_defect_transient_slfm_library, \
build_nonadiabatic_defect_steady_slfm_library, \
apply_mixing_model, \
PDFSpec
from .griffon.griffon import PyCombustionKernels
from .time.integrator import odesolve
from .time.nonlinear import SimpleNewtonSolver
from .time.stepcontrol import PIController
from .time.methods import (ForwardEulerS1P1,
ExpMidpointS2P2,
ExpTrapezoidalS2P2Q1,
ExpRalstonS2P2,
RK3KuttaS3P3,
RK4ClassicalS4P4,
BogackiShampineS4P3Q2,
ZonneveldS5P4Q3,
ExpKennedyCarpetnerS6P4Q3,
CashKarpS6P5Q4,
BackwardEulerS1P1Q1,
CrankNicolsonS2P2,
KennedyCarpenterS6P4Q3,
KvaernoS4P3Q2,
KennedyCarpenterS4P3Q2,
KennedyCarpenterS8P5Q4,
GeneralAdaptiveERK,
GeneralAdaptiveERKMultipleEmbedded)
from .data.get import datafile as datafile
<file_sep>"""
This module contains the Flamelet class that provides a high-level interface for nonpremixed flamelets,
namely setting up models and solving both unsteady and steady flamelets
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
from spitfire.time.integrator import odesolve
from spitfire.time.methods import KennedyCarpenterS6P4Q3
from spitfire.time.nonlinear import SimpleNewtonSolver
from spitfire.time.stepcontrol import PIController
from spitfire.chemistry.library import Dimension, Library
import numpy as np
from numpy import array
from numpy import any, logical_or, isinf, isnan
from scipy.special import erfinv
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import splu as superlu_factor
from numpy.linalg import norm
from spitfire.griffon.griffon import py_btddod_full_factorize, py_btddod_full_solve, \
py_btddod_scale_and_add_diagonal
_pressure_depr_warning = 'Deprecation warning in building Spitfire Flamelet instance. ' + \
'Specifying pressure in flamelet construction is no longer used, ' + \
'and will be removed in a future version. The pressure is now obtained from the fuel and ' + \
'oxidizer streams.'
class FlameletSpec(object):
"""
**Constructor**: specify boundary streams, the mixture fraction grid, and terms in the flamelet equations,
including chemical source terms, dissipation, heat loss, and enthalpy equation transformation terms.
Parameters
----------
mech_spec : spitfire.chemistry.mechanism.ChemicalMechanismSpec instance
the chemical mechanism, including species thermodynamics and transport data and chemical reaction rate data
initial_condition : str or np.ndarray
the initial state of the flamelet, either 'equilibrium', 'unreacted', 'linear-TY', 'Burke-Schumann',
or the interior state vector from another flamelet (obtained with Flamelet.*_interior_state properties)
library_slice : spitfire.chemistry.library.Library
obtain the mechanism, initial condition, boundary streams, and grid from a library with the "mixture_fraction" dimension
oxy_stream : Cantera.Quantity (a Spitfire stream) or Cantera.Solution object
the oxidizer stream (Z=0 boundary condition)
fuel_stream : Cantera.Quantity (a Spitfire stream) or Cantera.Solution object
the fuel stream (Z=1 boundary condition)
max_dissipation_rate : float
the maximum dissipation rate (requires the dissipation_rate_form argument, default is 'Peters')
stoich_dissipation_rate : float
the stoichiometric dissipation rate (requires the dissipation_rate_form argument, default is 'Peters')
dissipation_rate_form : str
the form of dissipation rate to use if the maximum or stoichiometric value is specified ('Peters' (default) or 'constant')
dissipation_rate : np.ndarray
an array of dissipation rates over mixture fraction (cannot be specified along with maximum or stoichiometric value)
grid : np.ndarray
an array of grid points locations (specifying this argument overrides other grid arguments)
grid_points : int
the number of grid points to use (if the grid argument is not specified, this is required)
grid_type : str
the type of grid, either 'clustered' (default) or 'uniform'
grid_cluster_intensity : float
how tightly clustered grid points will be around the grid_cluster_point if grid_type is 'clustered' (default: 4)
grid_cluster_point : float
the location of grid point clustering (default is the stoichiometric mixture fraction)
heat_transfer : str
whether the flamelet is 'adiabatic' or 'nonadiabatic'
convection_temperature : float or np.ndarray
the convective heat loss reference temperature
radiation_temperature : float or np.ndarray
the radiation heat loss reference temperature
convection_coefficient : float or np.ndarray
the convective heat loss coefficient
radiative_emissivity : float or np.ndarray
the radiative heat loss coefficient
use_scaled_heat_loss : bool or np.ndarray
whether or not to use a special form of reference temperature and coefficients for heat loss
include_enthalpy_flux : bool
whether or not to use a consistent formulation of the enthalpy flux (True, default) or the simpler flamelet formulation (False)
include_variable_cp : bool
whether or not to include variation of the heat capacity (True, default) or use the simpler flamelet formulation (False)
rates_sensitivity_type : str
how the chemical source term Jacobian is formed, either 'dense' or 'sparse' for exact formulations
or 'no-TBAF' which ignores third-body and falloff sensitivities. The default is 'dense'.
For large mechanisms (over 100 species) the 'sparse' formulation is far faster than 'dense',
especially for mechanisms of more than 300 species.
sensitivity_transform_type : str
how the Jacobian is transformed, currently only 'exact' is supported
"""
def __init__(self,
mech_spec=None,
initial_condition=None,
oxy_stream=None,
fuel_stream=None,
grid=None,
grid_points=None,
grid_type='clustered',
grid_cluster_intensity=4.,
grid_cluster_point='stoichiometric',
library_slice=None,
max_dissipation_rate=None,
stoich_dissipation_rate=None,
dissipation_rate=None,
dissipation_rate_form='Peters',
heat_transfer='adiabatic',
convection_temperature=None,
radiation_temperature=None,
convection_coefficient=None,
radiative_emissivity=None,
scale_heat_loss_by_temp_range=False,
scale_convection_by_dissipation=False,
use_linear_ref_temp_profile=False,
rates_sensitivity_type='dense',
sensitivity_transform_type='exact',
include_enthalpy_flux=True,
include_variable_cp=True,
pressure=None):
if pressure is not None:
print(_pressure_depr_warning)
if library_slice is not None:
lib_shape = library_slice.shape
if len(lib_shape) >= 1:
for s in lib_shape[1:]:
if s > 1:
raise ValueError(
f'Error in Flamelet construction from library_slice. The library provided does not '
f'appear to have the right dimensions: shape = {lib_shape}. '
f'The library must be one-dimensional, with mixture fraction as the first dimension. '
f'It can have trivial dimensions that can be squeezed to yield a one-dimensional form.')
if len(lib_shape) > 1:
library_slice = Library.squeeze(library_slice)
else:
raise ValueError(
f'Error in Flamelet construction from library_slice. The library provided does not '
f'appear to have the right dimensions: shape = {lib_shape}. '
f'The library must be one-dimensional, with mixture fraction as the first dimension. '
f'It can have trivial dimensions that can be squeezed to yield a one-dimensional form.')
if 'mixture_fraction' not in library_slice.dims[0].name:
raise ValueError(
f'Error in Flamelet construction from library_slice. The library provided does not '
f'appear to have mixture fraction as the first dimension. '
f'The library provided is:\n {library_slice}')
self.mech_spec = library_slice.extra_attributes['mech_spec']
oxyY = [library_slice[f'mass fraction {s}'][0] for s in self.mech_spec.species_names]
fuelY = [library_slice[f'mass fraction {s}'][-1] for s in self.mech_spec.species_names]
oxyT = library_slice['temperature'][0]
fuelT = library_slice['temperature'][-1]
pressure = library_slice['pressure'][0]
self.oxy_stream = self.mech_spec.stream('TPY', (oxyT, pressure, oxyY))
self.fuel_stream = self.mech_spec.stream('TPY', (fuelT, pressure, fuelY))
self.grid = library_slice.mixture_fraction_values
self.grid_points = None
self.grid_type = None
self.grid_cluster_intensity = None
self.grid_cluster_point = None
initial_condition = np.zeros((self.grid.size - 2, self.mech_spec.n_species))
initial_condition[:, 0] = library_slice['temperature'][1:-1]
for i, s in enumerate(self.mech_spec.species_names[:-1]):
initial_condition[:, 1 + i] = library_slice['mass fraction ' + s][1:-1]
self.initial_condition = initial_condition.ravel()
else:
self.mech_spec = mech_spec
self.initial_condition = initial_condition
self.oxy_stream = oxy_stream
self.fuel_stream = fuel_stream
self.grid = grid
self.grid_points = grid_points
self.grid_type = grid_type
self.grid_cluster_intensity = grid_cluster_intensity
self.grid_cluster_point = grid_cluster_point
if grid is not None:
self.grid_points = None
self.grid_type = None
self.grid_cluster_intensity = None
self.grid_cluster_point = None
if grid_points is not None:
self.grid = None
self.max_dissipation_rate = max_dissipation_rate
self.stoich_dissipation_rate = stoich_dissipation_rate
self.dissipation_rate = dissipation_rate
self.dissipation_rate_form = dissipation_rate_form
self.heat_transfer = heat_transfer
self.convection_temperature = convection_temperature
self.radiation_temperature = radiation_temperature
self.convection_coefficient = convection_coefficient
self.radiative_emissivity = radiative_emissivity
self.scale_heat_loss_by_temp_range = scale_heat_loss_by_temp_range
self.scale_convection_by_dissipation = scale_convection_by_dissipation
self.use_linear_ref_temp_profile = use_linear_ref_temp_profile
self.rates_sensitivity_type = rates_sensitivity_type
self.sensitivity_transform_type = sensitivity_transform_type
self.include_enthalpy_flux = include_enthalpy_flux
self.include_variable_cp = include_variable_cp
def __getstate__(self):
d = dict(self.__dict__)
d.pop('oxy_stream')
d.pop('fuel_stream')
d['oxyY'] = self.oxy_stream.Y.copy()
d['oxyT'] = self.oxy_stream.T
d['fuelY'] = self.fuel_stream.Y.copy()
d['fuelT'] = self.fuel_stream.T
d['pressure'] = self.oxy_stream.P
return d
def __setstate__(self, state):
mech_spec = state['mech_spec']
pressure = state.pop('pressure')
state['oxy_stream'] = mech_spec.stream('TPY', (state.pop('oxyT'), pressure, state.pop('oxyY')))
state['fuel_stream'] = mech_spec.stream('TPY', (state.pop('fuelT'), pressure, state.pop('fuelY')))
self.__init__(**state)
def compute_dissipation_rate(mixture_fraction,
max_dissipation_rate,
form='Peters'):
"""Compute the scalar dissipation rate across mixture fraction
Parameters
----------
mixture_fraction : array_like
the locations of grid points in mixture fraction space
max_dissipation_rate : float
the maximum value of the dissipation rate
form : str, optional
the form of the dissipation rate's dependency on mixture fraction, defaults to 'Peters', which
uses the form of N. Peters, Turbulent Combustion, 2000.
Specifying anything else will yield a constant scalar dissipation rate.
Returns
-------
x : array_like
the scalar dissipation rate on the given mixture fraction grid
"""
if form == 'Peters' or form == 'peters':
x = max_dissipation_rate * np.exp(-2. * (erfinv(2. * mixture_fraction - 1.)) ** 2)
else:
x = np.zeros_like(mixture_fraction)
x[:] = max_dissipation_rate
return x
class Flamelet(object):
"""An API for solving flamelet equations in composing tabulated chemistry libraries
"""
_heat_transfers = ['adiabatic', 'nonadiabatic']
_initializations = ['unreacted', 'equilibrium', 'Burke-Schumann', 'linear-TY']
_grid_types = ['uniform', 'clustered']
_rates_sensitivity_option_dict = {'dense': 0, 'no-TBAF': 1, 'sparse': 2}
_sensitivity_transform_option_dict = {'exact': 0}
@classmethod
def _uniform_grid(cls, grid_points):
"""Make a uniform grid in mixture fraction space with a particular number of grid points
Parameters
----------
grid_points : int
the number of uniformly-distributed grid points
Returns
-------
z : array_like
Locations of grid points, including the boundary points
dz : array_like
Spacings between grid points
"""
z = np.linspace(0., 1., grid_points)
dz = z[1:] - z[:-1]
return z, dz
@classmethod
def _clustered_grid(cls, grid_points, grid_cluster_point, grid_cluster_intensity=6.):
"""Make a grid in mixture fraction space with clustering around a particular mixture fraction.
Parameters
----------
grid_points : int
the number of grid points
grid_cluster_point : float
the location around which grid points will be clustered
grid_cluster_intensity : float, optional
clustering coefficient, increase for more dense clustering, must be positive, defaults to 6.0
Returns
-------
z : array_like
Locations of grid points, including the boundary points
dz : array_like
Spacings between grid points
Notes
-----
This function uses the clustering method given in [1]_.
.. [1] <NAME>, "Computational Fluid Dynamics: the Basics with Applications," McGraw-Hill Inc., 1995 pp. 585-588, 1996.
"""
if grid_cluster_intensity < 1.e-16:
raise ValueError('cluster_coeff must be strictly positive! Given value: ' + str(grid_cluster_intensity))
if grid_cluster_point < 0. or grid_cluster_point > 1.:
raise ValueError('z_cluster must be between 0 and 1! Given value: ' + str(grid_cluster_point))
z = np.linspace(0., 1., grid_points)
zo = 1.0 / (2.0 * grid_cluster_intensity) * np.log(
(1. + (np.exp(grid_cluster_intensity) - 1.) * grid_cluster_point) / (
1. + (np.exp(-grid_cluster_intensity) - 1.) * grid_cluster_point))
a = np.sinh(grid_cluster_intensity * zo)
for i in range(grid_points):
z[i] = grid_cluster_point / a * (np.sinh(grid_cluster_intensity * (z[i] - zo)) + a)
z[-1] = 1.
dz = z[1:] - z[:-1]
return z, dz
@classmethod
def make_clustered_grid(cls, grid_points, grid_cluster_point, grid_cluster_intensity=6.):
return cls._clustered_grid(grid_points, grid_cluster_point, grid_cluster_intensity)[0]
@classmethod
def _compute_dissipation_rate(cls,
mixture_fraction,
max_dissipation_rate,
form='Peters'):
return compute_dissipation_rate(mixture_fraction, max_dissipation_rate, form)
def _set_heat_transfer_arg_as_np_array(self, input_value, input_name, attr_name):
if input_value is None:
raise ValueError('Flamelet specifications: Nonadiabatic heat transfer was selected but no ' + \
input_name + ' argument was given.')
else:
if isinstance(input_value, float):
setattr(self, attr_name, input_value + np.zeros(self._nz_interior))
elif isinstance(input_value, np.ndarray):
setattr(self, attr_name, input_value)
else:
raise ValueError(input_name + ' was not given as a float (constant) or numpy array')
def __init__(self,
flamelet_specs=None,
*args,
**kwargs):
if isinstance(flamelet_specs, dict):
fs = FlameletSpec(**flamelet_specs)
elif flamelet_specs is None:
fs = FlameletSpec(*args, **kwargs)
else:
fs = flamelet_specs
self._oxy_stream = fs.oxy_stream
self._fuel_stream = fs.fuel_stream
pressure_error = np.abs(self._fuel_stream.P - self._oxy_stream.P) / self._oxy_stream.P
if pressure_error > 1.e-6:
raise ValueError(f'Error in building Spitfire Flamelet instance. The pressure of the fuel and oxidizer '
f'streams must be the same. Fuel pressure = {self._fuel_stream.P}, '
f'oxidizer pressure = {self._oxy_stream.P}.'
f'Error is |fuel.P - oxy.P|/oxy.P = {pressure_error}')
self._pressure = np.copy(self._oxy_stream.P)
self._mechanism = fs.mech_spec
self._n_species = self._mechanism.n_species
self._n_reactions = self._mechanism.n_reactions
self._n_equations = self._n_species
self._state_fuel = np.hstack([self.fuel_stream.T, self.fuel_stream.Y[:-1]])
self._state_oxy = np.hstack([self.oxy_stream.T, self.oxy_stream.Y[:-1]])
# build the grid
# if the grid argument is given, then use that and warn if any other grid arguments ar given
# if the grid argument is not given, then grid_points must be given, while other grid arguments are all optional
if fs.grid is not None:
self._z = np.copy(fs.grid)
self._dz = self._z[1:] - self._z[:-1]
warning_message = lambda arg: 'Flamelet specifications: Warning! Setting the grid argument ' \
'nullifies the ' + arg + ' argument.'
if fs.grid_points is not None:
print(warning_message('grid_points'))
if fs.grid_type is not None:
print(warning_message('grid_type'))
if fs.grid_cluster_intensity is not None:
print(warning_message('grid_cluster_intensity'))
if fs.grid_cluster_point is not None:
print(warning_message('grid_cluster_point'))
else:
if fs.grid_points is None:
raise ValueError('Flamelet specifications: one of either grid or grid_points must be given.')
if fs.grid_type == 'uniform':
self._z, self._dz = self._uniform_grid(fs.grid_points)
elif fs.grid_type == 'clustered':
grid_cluster_point = fs.grid_cluster_point
if fs.grid_cluster_point == 'stoichiometric':
grid_cluster_point = self._mechanism.stoich_mixture_fraction(self._fuel_stream, self._oxy_stream)
self._z, self._dz = self._clustered_grid(fs.grid_points, grid_cluster_point, fs.grid_cluster_intensity)
else:
error_message = 'Flamelet specifications: Bad grid_type argument detected: ' + fs.grid_type + '\n' + \
' Acceptable values: ' + self._grid_types
raise ValueError(error_message)
self._nz_interior = self._z.size - 2
self._n_dof = self._n_equations * self._nz_interior
# set up the dissipation rate
if fs.dissipation_rate is not None:
warning_message = lambda arg: 'Flamelet specifications: Warning! Setting the dissipation_rate argument ' \
'nullifies the ' + arg + ' argument.'
if fs.max_dissipation_rate is not None:
warning_message('max_dissipation_rate')
if fs.stoich_dissipation_rate is not None:
warning_message('stoich_dissipation_rate')
if fs.dissipation_rate_form is not None:
warning_message('dissipation_rate_form')
self._x = np.copy(fs.dissipation_rate)
self._max_dissipation_rate = np.max(self._x)
self._dissipation_rate_form = 'custom'
else:
warning_message = lambda arg: 'Flamelet specifications: Warning! Setting the dissipation_rate_form ' \
'nullifies the ' + arg + ' argument.'
if fs.dissipation_rate is not None:
warning_message('dissipation_rate')
if fs.dissipation_rate_form not in ['peters', 'Peters', 'constant'] or \
(fs.max_dissipation_rate is None and fs.stoich_dissipation_rate is None):
self._x = np.zeros_like(self._z)
self._max_dissipation_rate = np.max(self._x)
self._dissipation_rate_form = 'unspecified-set-to-0'
else:
if fs.max_dissipation_rate is not None:
self._max_dissipation_rate = fs.max_dissipation_rate
self._dissipation_rate_form = fs.dissipation_rate_form
self._x = compute_dissipation_rate(self._z, self._max_dissipation_rate, self._dissipation_rate_form)
elif fs.stoich_dissipation_rate is not None:
if fs.dissipation_rate_form in ['peters', 'Peters']:
z_st = self.mechanism.stoich_mixture_fraction(self.fuel_stream, self.oxy_stream)
self._max_dissipation_rate = fs.stoich_dissipation_rate / np.exp(
-2. * (erfinv(2. * z_st - 1.)) ** 2)
elif fs.dissipation_rate_form == 'constant':
self._max_dissipation_rate = fs.stoich_dissipation_rate
self._dissipation_rate_form = fs.dissipation_rate_form
self._x = compute_dissipation_rate(self._z, self._max_dissipation_rate, self._dissipation_rate_form)
self._lewis_numbers = np.ones(self._n_species)
# set up the heat transfer
if fs.heat_transfer not in self._heat_transfers:
error_message = 'Flamelet specifications: Bad heat_transfer argument detected: ' + fs.heat_transfer + '\n' + \
' Acceptable values: ' + str(self._heat_transfers)
raise ValueError(error_message)
else:
self._heat_transfer = fs.heat_transfer
self._T_conv = None
self._T_rad = None
self._h_conv = None
self._h_rad = None
self._scale_heat_loss_by_temp_range = fs.scale_heat_loss_by_temp_range
self._scale_convection_by_dissipation = fs.scale_convection_by_dissipation
self._use_linear_ref_temp_profile = fs.use_linear_ref_temp_profile
if self._heat_transfer == 'adiabatic':
self._convection_temperature = None
self._radiation_temperature = None
warning_message = lambda arg: 'Flamelet specifications: Warning! Setting heat_transfer to adiabatic ' \
'nullifies the ' + arg + ' argument.'
if fs.convection_temperature is not None:
print(warning_message('convection_temperature'))
if fs.radiation_temperature is not None:
print(warning_message('radiation_temperature'))
if self._heat_transfer == 'adiabatic':
self._convection_coefficient = None
self._radiative_emissivity = None
if fs.convection_coefficient is not None:
print(warning_message('convection_coefficient'))
if fs.radiative_emissivity is not None:
print(warning_message('radiative_emissivity'))
else:
self._set_heat_transfer_arg_as_np_array(fs.convection_coefficient, 'convection_coefficient', '_h_conv')
self._set_heat_transfer_arg_as_np_array(fs.radiative_emissivity, 'radiative_emissivity', '_h_rad')
if self._use_linear_ref_temp_profile:
self._T_conv = self.oxy_stream.T + self._z[1:-1] * (self.fuel_stream.T - self.oxy_stream.T)
self._T_rad = self._T_conv.copy()
else:
self._set_heat_transfer_arg_as_np_array(fs.radiation_temperature, 'radiation_temperature', '_T_rad')
self._set_heat_transfer_arg_as_np_array(fs.convection_temperature, 'convection_temperature', '_T_conv')
if self._scale_convection_by_dissipation:
zst = self._mechanism.stoich_mixture_fraction(self.fuel_stream, self.oxy_stream)
factor = np.max(self._x) / (1. - zst) / zst
self._h_conv *= factor
self._h_rad *= factor
# set up the initialization
if isinstance(fs.initial_condition, str):
state_interior = np.ndarray((self._nz_interior, self._n_equations))
if fs.initial_condition == 'unreacted':
for i in range(self._nz_interior):
z = self._z[1 + i]
mixed_stream = self._mechanism.mix_streams([(self._oxy_stream, 1 - z),
(self._fuel_stream, z)],
basis='mass',
constant='HP')
state_interior[i, :] = np.hstack((mixed_stream.T, mixed_stream.Y[:-1]))
self._initial_state = np.copy(state_interior.ravel())
elif fs.initial_condition == 'linear-TY':
oxy_state = self._state_oxy
fuel_state = self._state_fuel
z = self._z[1:-1]
for i in range(self._n_equations):
state_interior[:, i] = oxy_state[i] + (fuel_state[i] - oxy_state[i]) * z
self._initial_state = np.copy(state_interior.ravel())
elif fs.initial_condition == 'equilibrium':
for i in range(self._nz_interior):
z = self._z[1 + i]
mixed_stream = self._mechanism.mix_streams([(self._oxy_stream, 1 - z),
(self._fuel_stream, z)],
basis='mass',
constant='HP')
mixed_stream.equilibrate('HP')
state_interior[i, :] = np.hstack((mixed_stream.T, mixed_stream.Y[:-1]))
self._initial_state = np.copy(state_interior.ravel())
elif fs.initial_condition == 'Burke-Schumann':
atom_names = ['H', 'C', 'O', 'N']
zst = self._mechanism.stoich_mixture_fraction(self._fuel_stream, self._oxy_stream)
stmix = self._mechanism.mix_streams([(self._oxy_stream, 1 - zst), (self._fuel_stream, zst)],
'mass', 'HP')
stat = self._mechanism._get_atoms_in_stream(stmix, atom_names)
aw = 0.5 * stat['H']
ad = stat['C']
at = stat['N']
mole_fraction_str = 'N2: ' + str(at / 2) + ' H2O: ' + str(aw)
if 'CO2' in self._mechanism.species_names:
mole_fraction_str += ' CO2: ' + str(ad)
sw = self._mechanism.stream('HPX', (stmix.H, self._pressure,
mole_fraction_str))
Y_st = sw.Y
Y_o = self._oxy_stream.Y
Y_f = self._fuel_stream.Y
for i in range(self._nz_interior):
z = self._z[1 + i]
h_mix = self._mechanism.mix_streams([(self._oxy_stream, 1 - z), (self._fuel_stream, z)],
'mass', 'HP').H
if z <= zst:
Y_mix = Y_o + z / zst * (Y_st - Y_o)
else:
Y_mix = Y_st + (z - zst) / (1. - zst) * (Y_f - Y_st)
mixed_stream = self._mechanism.stream('HPY', (h_mix, self.pressure, Y_mix))
state_interior[i, :] = np.hstack((mixed_stream.T, mixed_stream.Y[:-1]))
self._initial_state = np.copy(state_interior.ravel())
else:
msg = 'Flamelet specifications: bad string argument for initial_condition\n' + \
' given: ' + fs.initial_condition + '\n' + \
' allowable: ' + str(self._initializations)
raise ValueError(msg)
elif isinstance(fs.initial_condition, np.ndarray):
if fs.initial_condition.size != self._n_dof:
raise ValueError('size of initial condition is incorrect!')
else:
self._initial_state = np.copy(fs.initial_condition)
else:
msg = 'Flamelet specifications: bad argument for initial_condition\n' + \
' must be either another Flamelet instance or a string\n' + \
' allowable strings: ' + str(self._initializations)
raise ValueError(msg)
self._current_state = np.copy(self._initial_state)
self._initial_time = 0.
self._current_time = 0.
self._griffon = self._mechanism.griffon
self._include_enthalpy_flux = fs.include_enthalpy_flux
self._include_variable_cp = fs.include_variable_cp
self._rsopt = self._rates_sensitivity_option_dict[fs.rates_sensitivity_type]
self._stopt = self._sensitivity_transform_option_dict[fs.sensitivity_transform_type]
self._variable_scales = np.ones(self._n_dof)
self._variable_scales[::self._n_equations] = 1.e3
self._solution_times = []
self._linear_inverse_operator = None
self._maj_coeff_griffon = np.zeros(self._n_dof)
self._sub_coeff_griffon = np.zeros(self._n_dof)
self._sup_coeff_griffon = np.zeros(self._n_dof)
self._mcoeff_griffon = np.zeros(self._nz_interior)
self._ncoeff_griffon = np.zeros(self._nz_interior)
self._griffon.flamelet_stencils(self._dz, self._nz_interior, self._x, 1. / self._lewis_numbers,
self._maj_coeff_griffon, self._sub_coeff_griffon, self._sup_coeff_griffon,
self._mcoeff_griffon, self._ncoeff_griffon)
self._jac_nelements_griffon = int(
self._n_equations * (self._nz_interior * self._n_equations + 2 * (self._nz_interior - 1)))
row_indices = np.zeros(self._jac_nelements_griffon, dtype=np.int32)
col_indices = np.zeros(self._jac_nelements_griffon, dtype=np.int32)
self._griffon.flamelet_jac_indices(self._nz_interior, row_indices, col_indices)
self._jac_indices_griffon = (row_indices, col_indices)
self._block_thomas_l_values = np.zeros(self._n_equations * self._n_equations * self._nz_interior)
self._block_thomas_d_pivots = np.zeros(self._jac_nelements_griffon, dtype=np.int32)
self._iteration_count = None
# ------------------------------------------------------------------------------------------------------------------
# adiabatic methods
# ------------------------------------------------------------------------------------------------------------------
def _adiabatic_rhs(self, t, state_interior):
rhs = np.zeros(self._n_dof)
null = np.zeros(1)
self._griffon.flamelet_rhs(state_interior, self._pressure,
self._state_oxy, self._state_fuel,
True, null, null, null, null,
self._nz_interior,
self._maj_coeff_griffon,
self._sub_coeff_griffon,
self._sup_coeff_griffon,
self._mcoeff_griffon,
self._ncoeff_griffon,
self._x,
self._include_enthalpy_flux,
self._include_variable_cp,
self._scale_heat_loss_by_temp_range,
rhs)
return rhs
def _adiabatic_jac(self, state_interior):
values = np.zeros(self._jac_nelements_griffon)
null = np.zeros(1)
self._griffon.flamelet_jacobian(state_interior,
self._pressure,
self._state_oxy, self._state_fuel,
True, null, null, null, null,
self._nz_interior,
self._maj_coeff_griffon,
self._sub_coeff_griffon,
self._sup_coeff_griffon,
self._mcoeff_griffon,
self._ncoeff_griffon,
self._x,
False,
0.,
False,
0.,
self._rsopt,
self._stopt,
self._include_enthalpy_flux,
self._include_variable_cp,
False,
null,
values)
return values
def _adiabatic_jac_offset_scaled(self, state_interior, prefactor):
values = np.zeros(self._jac_nelements_griffon)
null = np.zeros(1)
self._griffon.flamelet_jacobian(state_interior,
self._pressure,
self._state_oxy, self._state_fuel,
True, null, null, null, null,
self._nz_interior,
self._maj_coeff_griffon,
self._sub_coeff_griffon,
self._sup_coeff_griffon,
self._mcoeff_griffon,
self._ncoeff_griffon,
self._x,
False,
0.,
True,
prefactor,
self._rsopt,
self._stopt,
self._include_enthalpy_flux,
self._include_variable_cp,
False,
null,
values)
return values
def _adiabatic_jac_and_eig(self, state_interior, diffterm):
values = np.zeros(self._jac_nelements_griffon)
expeig = np.zeros(self._n_dof)
null = np.zeros(1)
self._griffon.flamelet_jacobian(state_interior,
self._pressure,
self._state_oxy, self._state_fuel,
True, null, null, null, null,
self._nz_interior,
self._maj_coeff_griffon,
self._sub_coeff_griffon,
self._sup_coeff_griffon,
self._mcoeff_griffon,
self._ncoeff_griffon,
self._x,
True,
diffterm,
False,
0.,
self._rsopt,
self._stopt,
self._include_enthalpy_flux,
self._include_variable_cp,
False,
expeig,
values)
return values, expeig
def _adiabatic_jac_csc(self, state_interior):
return csc_matrix((self._adiabatic_jac(state_interior), self._jac_indices_griffon))
def _adiabatic_jac_and_eig_csc(self, state_interior, diffterm):
values, expeig = self._adiabatic_jac_and_eig(state_interior, diffterm)
return csc_matrix((values, self._jac_indices_griffon)), expeig
def _adiabatic_setup_superlu(self, t, state_interior, prefactor):
jac = csc_matrix((self._adiabatic_jac_offset_scaled(state_interior, prefactor),
self._jac_indices_griffon))
jac.eliminate_zeros()
self._linear_inverse_operator = superlu_factor(jac)
def _adiabatic_setup_block_thomas(self, t, state_interior, prefactor):
self._jacobian_values = self._adiabatic_jac_offset_scaled(state_interior, prefactor)
py_btddod_full_factorize(self._jacobian_values,
self._nz_interior,
self._n_equations,
self._block_thomas_l_values,
self._block_thomas_d_pivots)
# ------------------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------
# nonadiabatic methods
# ------------------------------------------------------------------------------------------------------------------
def _nonadiabatic_rhs(self, t, state_interior):
rhs = np.zeros(self._n_dof)
self._griffon.flamelet_rhs(state_interior, self._pressure,
self._state_oxy, self._state_fuel,
False, self._T_conv, self._T_rad, self._h_conv, self._h_rad,
self._nz_interior,
self._maj_coeff_griffon,
self._sub_coeff_griffon,
self._sup_coeff_griffon,
self._mcoeff_griffon,
self._ncoeff_griffon,
self._x,
self._include_enthalpy_flux,
self._include_variable_cp,
self._scale_heat_loss_by_temp_range,
rhs)
return rhs
def _nonadiabatic_jac(self, state_interior):
values = np.zeros(self._jac_nelements_griffon)
null = np.zeros(1)
self._griffon.flamelet_jacobian(state_interior,
self._pressure,
self._state_oxy, self._state_fuel,
False, self._T_conv, self._T_rad, self._h_conv, self._h_rad,
self._nz_interior,
self._maj_coeff_griffon,
self._sub_coeff_griffon,
self._sup_coeff_griffon,
self._mcoeff_griffon,
self._ncoeff_griffon,
self._x,
False,
0.,
False,
0.,
self._rsopt,
self._stopt,
self._include_enthalpy_flux,
self._include_variable_cp,
self._scale_heat_loss_by_temp_range,
null,
values)
return values
def _nonadiabatic_jac_offset_scaled(self, state_interior, prefactor):
values = np.zeros(self._jac_nelements_griffon)
null = np.zeros(1)
self._griffon.flamelet_jacobian(state_interior,
self._pressure,
self._state_oxy, self._state_fuel,
False, self._T_conv, self._T_rad, self._h_conv, self._h_rad,
self._nz_interior,
self._maj_coeff_griffon,
self._sub_coeff_griffon,
self._sup_coeff_griffon,
self._mcoeff_griffon,
self._ncoeff_griffon,
self._x,
False,
0.,
True,
prefactor,
self._rsopt,
self._stopt,
self._include_enthalpy_flux,
self._include_variable_cp,
self._scale_heat_loss_by_temp_range,
null,
values)
return values
def _nonadiabatic_jac_and_eig(self, state_interior, diffterm):
values = np.zeros(self._jac_nelements_griffon)
expeig = np.zeros(self._n_dof)
self._griffon.flamelet_jacobian(state_interior,
self._pressure,
self._state_oxy, self._state_fuel,
False, self._T_conv, self._T_rad, self._h_conv, self._h_rad,
self._nz_interior,
self._maj_coeff_griffon,
self._sub_coeff_griffon,
self._sup_coeff_griffon,
self._mcoeff_griffon,
self._ncoeff_griffon,
self._x,
True,
diffterm,
False,
0.,
self._rsopt,
self._stopt,
self._include_enthalpy_flux,
self._include_variable_cp,
self._scale_heat_loss_by_temp_range,
expeig,
values)
return values, expeig
def _nonadiabatic_jac_csc(self, state_interior):
return csc_matrix((self._nonadiabatic_jac(state_interior), self._jac_indices_griffon))
def _nonadiabatic_jac_and_eig_csc(self, state_interior, diffterm):
values, expeig = self._nonadiabatic_jac_and_eig(state_interior, diffterm)
return csc_matrix((values, self._jac_indices_griffon)), expeig
def _nonadiabatic_setup_superlu(self, t, state_interior, prefactor):
jac = csc_matrix((self._nonadiabatic_jac_offset_scaled(state_interior, prefactor),
self._jac_indices_griffon))
jac.eliminate_zeros()
self._linear_inverse_operator = superlu_factor(jac)
def _nonadiabatic_setup_block_thomas(self, t, state_interior, prefactor):
self._jacobian_values = self._nonadiabatic_jac_offset_scaled(state_interior, prefactor)
py_btddod_full_factorize(self._jacobian_values,
self._nz_interior,
self._n_equations,
self._block_thomas_l_values,
self._block_thomas_d_pivots)
# ------------------------------------------------------------------------------------------------------------------
def rhs(self, t, state_interior):
return getattr(self, '_' + self._heat_transfer + '_rhs')(t, state_interior)
def jac(self, state_interior):
return getattr(self, '_' + self._heat_transfer + '_jac')(state_interior)
def jac_csc(self, state_interior):
return getattr(self, '_' + self._heat_transfer + '_jac_csc')(state_interior)
def jac_and_eig(self, state_interior):
return getattr(self, '_' + self._heat_transfer + '_jac_and_eig')(state_interior)
# ------------------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------
# linear solve methods
# ------------------------------------------------------------------------------------------------------------------
def _solve_superlu(self, residual):
return self._linear_inverse_operator.solve(residual), 1, True
def _solve_block_thomas(self, residual):
solution = np.zeros(self._n_dof)
py_btddod_full_solve(self._jacobian_values, self._block_thomas_l_values, self._block_thomas_d_pivots,
residual, self._nz_interior, self._n_equations, solution)
return solution, 1, True
# ------------------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------
# getter methods
# ------------------------------------------------------------------------------------------------------------------
def _get_mass_fraction_with_bcs(self, key, state):
if isinstance(key, str):
key = self._mechanism.species_index(key)
if key == self._n_species - 1:
yn = np.ones(self._nz_interior + 2)
for i in range(1, self._n_equations):
yn -= state[i::self._n_equations]
return yn
else:
i = key + 1
return state[i::self._n_equations]
def _state_2d_with_bcs(self, state):
nzi = state.size // self._n_equations
return np.vstack((self._oxy_state,
state.reshape((nzi, self._n_equations)),
self._fuel_state)).ravel()
@property
def mechanism(self):
"""Obtain the flamelet's ChemicalMechanismSpec object"""
return self._mechanism
@property
def dissipation_rate(self):
"""Obtain the np.ndarray of scalar dissipation rate values"""
return self._x
@property
def mixfrac_grid(self):
"""Obtain the np.ndarray of mixture fraction grid points"""
return self._z
@property
def oxy_stream(self):
"""Obtain the stream associated with the oxidizer"""
return self._oxy_stream
@property
def fuel_stream(self):
"""Obtain the stream associated with the fuel"""
return self._fuel_stream
@property
def pressure(self):
"""Obtain the thermodynamic pressure"""
return self._pressure
@property
def linear_temperature(self):
"""Obtain the np.ndarray of linear temperature values"""
To = self._oxy_stream.T
Tf = self._fuel_stream.T
return To + (Tf - To) * self._z
@property
def initial_interior_state(self):
"""Obtain the initial interior (no boundary states) state vector of the flamelet, useful for initializing another flamelet object"""
return self._initial_state
@property
def initial_state(self):
"""Obtain the initial full (interior + boundaries) state vector of the flamelet"""
return self._state_2d_with_bcs(self._initial_state)
@property
def initial_temperature(self):
"""Obtain the np.ndarray of values of the temperature before solving the steady/unsteady flamelet"""
return np.hstack((self._state_oxy[0], self._initial_state[::self._n_equations], self._state_fuel[0]))
def initial_mass_fraction(self, key):
"""Obtain the np.ndarray of values of a particular mass fraction before solving the steady/unsteady flamelet"""
return self._get_mass_fraction_with_bcs(key, self._state_2d_with_bcs(self._initial_state))
@property
def current_interior_state(self):
"""Obtain the current interior (no boundary states) state vector of the flamelet, useful for initializing another flamelet object"""
return self._current_state
@property
def current_state(self):
"""Obtain the initial full (interior + boundaries) state vector of the flamelet"""
return self._state_2d_with_bcs(self._current_state)
@property
def current_temperature(self):
"""Obtain the np.ndarray of values of the temperature after solving the steady/unsteady flamelet"""
return np.hstack((self._state_oxy[0], self._current_state[::self._n_equations], self._state_fuel[0]))
def current_mass_fraction(self, key):
"""Obtain the np.ndarray of values of a particular mass fraction after solving the steady/unsteady flamelet"""
return self._get_mass_fraction_with_bcs(key, self._state_2d_with_bcs(self._current_state))
@property
def solution_times(self):
"""Obtain this reactor's integration times"""
return array(self._solution_times)
@property
def iteration_count(self):
"""Obtain the number of iterations needed to solve the steady flamelet (after solving...)"""
return self._iteration_count
@property
def _oxy_state(self):
return self._state_oxy
@property
def _fuel_state(self):
return self._state_fuel
def offset_time(self, delta):
self._initial_time += delta
self._current_time += delta
def _check_ignition_delay(self, state, delta_temperature_ignition):
ne = self._n_equations
has_ignited = np.max(state[::ne] - self._initial_state[::ne]) > delta_temperature_ignition
return has_ignited
# ------------------------------------------------------------------------------------------------------------------
# time integration, nonlinear solvers, etc.
# ------------------------------------------------------------------------------------------------------------------
def integrate(self,
stop_at_time=None,
stop_at_steady=None,
stop_criteria=None,
first_time_step=1.e-6,
max_time_step=1.e-3,
minimum_time_step_count=40,
transient_tolerance=1.e-10,
write_log=False,
log_rate=100,
maximum_steps_per_jacobian=10,
nonlinear_solve_tolerance=1.e-12,
linear_solver='block thomas',
stepper_type=KennedyCarpenterS6P4Q3,
nlsolver_type=SimpleNewtonSolver,
stepcontrol_type=PIController,
extra_integrator_args=dict(),
extra_stepper_args=dict(),
extra_nlsolver_args=dict(),
extra_stepcontrol_args=dict(),
save_first_and_last_only=False,
print_exception_on_failure=False):
"""Base method for flamelet integration
Parameters
----------
stop_at_time : float
The final time to stop the simulation at
stop_at_steady : float
The tolerance at which a steady state is decided upon and stopped at
stop_criteria : callable (t, state, residual, n_steps)
Any callable that returns True when the simulation should stop
first_time_step : float
The time step size initially used by the time integrator
max_time_step : float
The maximum time step allowed by the integrator
minimum_time_step_count : int
The minimum number of time steps to run, (default: 40) (helpful for slowly evolving simulations, for instance those with low starting temperatures)
transient_tolerance : float
the target temporal error for transient integration
write_log : bool
whether or not to print integration statistics and status during the simulation
log_rate : int
how often to print log information
maximum_steps_per_jacobian : int
maximum number of steps Spitfire allows before the Jacobian must be re-evaluated - keep low for robustness, try to increase for performance on large mechanisms
nonlinear_solve_tolerance : float
tolerance for the nonlinear solver
linear_solver : str
which linear solver to use - only 'block thomas' (default, heavily recommended) or 'superlu' are supported
stepper_type : spitfire.time.TimeStepper
which (single step) stepper method to use (optional, default: ESDIRK64)
nlsolver_type : spitfire.time.NonlinearSolver
which nonlinear solver method to use (optional, default: SimpleNewtonSolver)
stepcontrol_type : spitfire.time.StepControl
which time step adaptation method to use (optional, default: PIController)
extra_integrator_args : dict
any extra arguments to specify to the time integrator - arguments passed to the odesolve method
extra_stepper_args : dict
extra arguments to specify on the spitfire.time.TimeStepper object
extra_nlsolver_args : dict
extra arguments to specify on the spitfire.time.NonlinearSolver object
extra_stepcontrol_args : dict
extra arguments to specify on the spitfire.time.StepControl object
save_first_and_last_only : bool
whether or not to retain all data (False, default) or only the first and last solutions
print_exception_on_failure : bool
whether or not to print an exception message on integrator/model failure (default: False)
Returns
-------
a library containing temperature, mass fractions, and pressure over time and mixture fraction, respectively
"""
def post_step_callback(t, state, *args):
state[state < 0.] = 0.
return state
integrator_args = {'stop_criteria': stop_criteria}
if stop_at_time is not None:
integrator_args.update({'stop_at_time': stop_at_time})
if stop_at_steady is not None:
integrator_args.update({'stop_at_steady': stop_at_steady})
integrator_args.update(extra_integrator_args)
# build the step controller and set attributes
step_control_args = {'first_step': first_time_step,
'max_step': max_time_step,
'target_error': transient_tolerance}
step_control_args.update(extra_stepcontrol_args)
step_controller = stepcontrol_type(**step_control_args)
# build the nonlinear solver and set attributes
nonlinear_solver_args = {'evaluate_jacobian_every_iter': False,
'norm_weighting': 1. / self._variable_scales,
'tolerance': nonlinear_solve_tolerance}
nonlinear_solver_args.update(extra_nlsolver_args)
newton_solver = nlsolver_type(**nonlinear_solver_args)
# build the stepper method and set attributes
stepper_args = {'nonlinear_solver': newton_solver, 'norm_weighting': 1. / self._variable_scales}
stepper_args.update(extra_stepper_args)
stepper = stepper_type(**stepper_args)
# build the rhs and projector methods and do the integration
rhs_method = getattr(self, '_' + self._heat_transfer + '_rhs')
if linear_solver.lower() == 'superlu':
setup_method = getattr(self, '_' + self._heat_transfer + '_setup_superlu')
solve_method = self._solve_superlu
elif linear_solver.lower() == 'block thomas':
setup_method = getattr(self, '_' + self._heat_transfer + '_setup_block_thomas')
solve_method = self._solve_block_thomas
else:
raise ValueError('linear solver ' + linear_solver + ' is invalid, must be ''superlu'' or ''block thomas''')
output = odesolve(right_hand_side=rhs_method,
initial_state=self._current_state,
initial_time=self._current_time,
step_size=step_controller,
method=stepper,
linear_setup=setup_method,
linear_solve=solve_method,
minimum_time_step_count=minimum_time_step_count,
linear_setup_rate=maximum_steps_per_jacobian,
verbose=write_log,
log_rate=log_rate,
norm_weighting=1. / self._variable_scales,
post_step_callback=post_step_callback,
save_each_step=not save_first_and_last_only,
print_exception_on_failure=print_exception_on_failure,
**integrator_args)
if save_first_and_last_only:
current_state, current_time, time_step_size = output
self._current_state = np.copy(current_state)
self._current_time = np.copy(current_time)
states = np.zeros((1, current_state.size))
states[0, :] = current_state
t = np.zeros(1)
t[0] = current_time
else:
t, states = output
self._current_state = np.copy(states[-1, :])
self._current_time = np.copy(t[-1])
time_dimension = Dimension('time', t)
mixfrac_dimension = Dimension('mixture_fraction', self._z)
output_library = Library(time_dimension, mixfrac_dimension)
output_library.extra_attributes['mech_spec'] = self._mechanism
output_library['temperature'] = output_library.get_empty_dataset()
output_library['temperature'][:, 0] = self.oxy_stream.T
output_library['temperature'][:, 1:-1] = states[:, ::self._n_equations]
output_library['temperature'][:, -1] = self.fuel_stream.T
output_library['pressure'] = np.zeros_like(output_library['temperature']) + self._pressure
species_names = self._mechanism.species_names
output_library['mass fraction ' + species_names[-1]] = np.ones_like(output_library['temperature'])
for i, s in enumerate(species_names[:-1]):
output_library['mass fraction ' + s] = output_library.get_empty_dataset()
output_library['mass fraction ' + s][:, 0] = self.oxy_stream.Y[i]
output_library['mass fraction ' + s][:, 1:-1] = states[:, 1 + i::self._n_equations]
output_library['mass fraction ' + s][:, -1] = self.fuel_stream.Y[i]
output_library['mass fraction ' + species_names[-1]] -= output_library['mass fraction ' + s]
return output_library
def integrate_to_steady(self, steady_tolerance=1.e-4, **kwargs):
"""Integrate a flamelet until steady state is reached
Parameters
----------
steady_tolerance : float
residual tolerance below which steady state is defined
**kwargs
Arbitrary keyword arguments - see the integrate() method documentation
"""
return self.integrate(stop_at_steady=steady_tolerance, **kwargs)
def integrate_to_time(self, final_time, **kwargs):
"""Integrate a flamelet until it reaches a specified simulation time
Parameters
----------
final_time : float
time at which integration stops
**kwargs
Arbitrary keyword arguments - see the integrate() method documentation
"""
return self.integrate(stop_at_time=final_time, **kwargs)
def integrate_to_steady_after_ignition(self,
steady_tolerance=1.e-4,
delta_temperature_ignition=400.,
**kwargs):
"""Integrate a flamelet until steady state is reached after ignition (based on temperature) has occurred.
This is helpful in slowly-evolving systems whose initial residual may be lower than the prescribed tolerance.
Parameters
----------
steady_tolerance : float
residual tolerance below which steady state is defined
delta_temperature_ignition : float
how much the temperature of the reactor must have increased for ignition to have occurred, default is 400 K
**kwargs
Arbitrary keyword arguments - see the integrate() method documentation
"""
def stop_at_steady_after_ignition(t, state, residual, *args, **kwargs):
has_ignited = self._check_ignition_delay(state, delta_temperature_ignition)
is_steady = residual < steady_tolerance
return has_ignited and is_steady
return self.integrate(stop_criteria=stop_at_steady_after_ignition, **kwargs)
def integrate_for_heat_loss(self, temperature_tolerance=0.05, steady_tolerance=1.e-4, **kwargs):
"""Integrate a flamelet until the temperature profile is sufficiently linear.
This is used to generate the heat loss dimension for flamelet libraries.
Note that this will terminate the integration if a steady state is identified,
which may simply indicate that the heat transfer settings were insufficient to
drive the temperature to a linear enough profile.
Parameters
----------
temperature_tolerance : float
tolerance for termination, where max(T) <= (1 + tolerance) max(T_oxy, T_fuel)
steady_tolerance : float
residual tolerance below which steady state is defined
**kwargs
Arbitrary keyword arguments - see the integrate() method documentation
"""
def stop_at_linear_temperature_or_steady(t, state, residual, *args, **kwargs):
T_bc_max = max([self._oxy_stream.T, self._fuel_stream.T])
is_linear_enough = np.max(state) < (1. + temperature_tolerance) * T_bc_max
is_steady = residual < steady_tolerance
return is_linear_enough or is_steady
return self.integrate(stop_criteria=stop_at_linear_temperature_or_steady, **kwargs)
def compute_ignition_delay(self,
delta_temperature_ignition=400.,
minimum_allowable_residual=1.e-12,
return_solution=False,
**kwargs):
"""Integrate in time until ignition (exceeding a specified threshold of the increase in temperature)
Parameters
----------
delta_temperature_ignition : float
how much the temperature of the reactor must have increased for ignition to have occurred, default is 400 K
minimum_allowable_residual : float
how small the residual can be before the reactor is deemed to 'never' ignite, default is 1.e-12
return_solution : bool
whether or not to return the solution trajectory in addition to the ignition delay, as a tuple, (t, library)
**kwargs
Arbitrary keyword arguments - see the integrate() method documentation
"""
def stop_at_ignition(t, state, residual, *args, **kwargs):
has_ignited = self._check_ignition_delay(state, delta_temperature_ignition)
is_not_steady = residual > minimum_allowable_residual
if is_not_steady:
return has_ignited
else:
error_msg = f'From compute_ignition_delay(): '
f'residual < minimum allowable value ({minimum_allowable_residual}),'
f' suggesting that the reactor will not ignite.'
f'\nNote that you can set this value with the "minimum_allowable_residual" argument.'
f'\nIt is advised that you also pass write_log=True to observe progress of the simulation '
f'in case it is running perpetually.'
raise ValueError(error_msg)
output_library = self.integrate(stop_criteria=stop_at_ignition,
save_first_and_last_only=not return_solution,
**kwargs)
tau_ignition = output_library.time_values[-1]
if return_solution:
return tau_ignition, output_library
else:
return tau_ignition
def make_library_from_interior_state(self, state_in):
mixfrac_dimension = Dimension('mixture_fraction', self._z)
output_library = Library(mixfrac_dimension)
output_library.extra_attributes['mech_spec'] = self._mechanism
output_library['temperature'] = output_library.get_empty_dataset()
output_library['temperature'][0] = self.oxy_stream.T
output_library['temperature'][1:-1] = state_in[::self._n_equations]
output_library['temperature'][-1] = self.fuel_stream.T
output_library['pressure'] = np.zeros_like(output_library['temperature']) + self._pressure
species_names = self._mechanism.species_names
output_library['mass fraction ' + species_names[-1]] = np.ones_like(output_library['temperature'])
for i, s in enumerate(species_names[:-1]):
output_library['mass fraction ' + s] = output_library.get_empty_dataset()
output_library['mass fraction ' + s][0] = self.oxy_stream.Y[i]
output_library['mass fraction ' + s][1:-1] = state_in[1 + i::self._n_equations]
output_library['mass fraction ' + s][-1] = self.fuel_stream.Y[i]
output_library['mass fraction ' + species_names[-1]] -= output_library['mass fraction ' + s]
return output_library
def steady_solve_newton(self,
initial_guess=None,
tolerance=1.e-6,
max_iterations=10,
max_factor_line_search=1.5,
max_allowed_residual=1.e6,
min_allowable_state_var=-1.e-6,
norm_order=np.Inf,
log_rate=100000,
verbose=True):
"""Use Newton's method to solve for the steady state of this flamelet.
Note that Newton's method is unlikely to converge unless an accurate initial guess is given.
Parameters
----------
initial_guess : np.ndarray
the initial guess - obtain this from a Flamelet
tolerance : float
residual tolerance below which the solution has converged
max_iterations : int
maximum number of iterations before failure is detected
max_factor_line_search : float
the maximum factor by which the residual is allowed to increase in the line search algorithm
max_allowed_residual : float
the maximum allowable value of the residual
min_allowable_state_var : float
the lowest value (negative or zero) that a state variable can take during the solution process
norm_order : int or np.Inf
the order of the norm used in measuring the residual
log_rate : int
how often a message about the solution status is written
verbose : bool
whether to write out the solver status (log messages) or write out failure descriptions
Returns
-------
a tuple of a library containing temperature, mass fractions, and pressure over mixture fraction,
and the required iteration count, and whether or not the system converged,
although if convergence is not obtained, then the library and iteration count output will both be None
"""
def verbose_print(message):
if verbose:
print(message)
if initial_guess is None:
state = np.copy(self._initial_state)
else:
state = np.copy(initial_guess)
inv_dofscales = 1. / self._variable_scales
rhs_method = getattr(self, '_' + self._heat_transfer + '_rhs')
jac_method = getattr(self, '_' + self._heat_transfer + '_jac')
iteration_count = 0
out_count = 0
res = tolerance + 1.
rhs = rhs_method(0., state)
nzi = self._nz_interior
neq = self._n_equations
evaluate_jacobian = True
while res > tolerance and iteration_count < max_iterations:
iteration_count += 1
out_count += 1
if evaluate_jacobian:
J = -jac_method(state)
py_btddod_full_factorize(J, nzi, neq,
self._block_thomas_l_values,
self._block_thomas_d_pivots)
evaluate_jacobian = False
dstate = np.zeros(self._n_dof)
py_btddod_full_solve(J,
self._block_thomas_l_values,
self._block_thomas_d_pivots,
rhs, nzi, neq, dstate)
if any(logical_or(isinf(dstate), isnan(dstate))):
verbose_print('nan/inf detected in state update!')
return None, None, False
norm_rhs_old = norm(rhs * inv_dofscales, ord=norm_order)
alpha = 1.
rhs = rhs_method(0., state + dstate)
if any(logical_or(isinf(rhs), isnan(rhs))):
verbose_print('nan/inf detected in state update!')
return None, None, False
while norm(rhs * inv_dofscales, ord=norm_order) > max_factor_line_search * norm_rhs_old and alpha > 0.001:
alpha *= 0.5
dstate *= alpha
rhs = rhs_method(0., state + dstate)
verbose_print(f' line search reducing step size to {alpha:.3f}')
evaluate_jacobian = True
state += dstate
res = norm(rhs * inv_dofscales, ord=norm_order)
if res > max_allowed_residual:
message = 'Convergence failure! Residual of {:.2e} detected, ' \
'exceeds the maximum allowable value of {:.2e}.'.format(res, max_allowed_residual)
verbose_print(message)
return None, None, False
if np.min(state) < min_allowable_state_var:
message = 'Convergence failure! ' \
'Mass fraction or temperature < ' \
'min_allowable_state_var detected.'.format(res, max_allowed_residual)
verbose_print(message)
return None, None, False
if out_count == log_rate and verbose:
out_count = 0
maxT = np.max(state)
print(' - iter {:4}, |residual| = {:7.2e}, max(T) = {:6.1f}'.format(iteration_count, res, maxT))
state[state < 0] = 0.
output_library = self.make_library_from_interior_state(state)
if iteration_count > max_iterations or res > tolerance:
message = 'Convergence failure! ' \
'Too many iterations required, more than allowable {:}.'.format(max_iterations)
verbose_print(message)
return None, None, False
else:
self._current_state = np.copy(state)
return output_library, iteration_count, True
def steady_solve_psitc(self,
initial_guess=None,
tolerance=1.e-6,
max_iterations=400,
min_allowable_state_var=-1.e-6,
ds_init=1.,
ds_init_decrease=4.,
adaptive_restart=True,
diffusion_factor=4.,
global_ds=False,
ds_safety=0.1,
ds_ramp=1.1,
ds_max=1.e4,
max_factor_line_search=1.5,
max_allowed_residual=1.e6,
log_rate=100000,
norm_order=np.Inf,
_recursion_depth=0,
max_recursion_depth=20,
verbose=True):
"""Use an adaptive pseudotransient continuation method to compute the steady state of this flamelet
Parameters
----------
initial_guess : np.ndarray
the initial guess - obtain this from a Flamelet
tolerance : float
residual tolerance below which the solution has converged
max_iterations : int
maximum number of iterations before failure is detected
max_factor_line_search : float
the maximum factor by which the residual is allowed to increase in the line search algorithm
max_allowed_residual : float
the maximum allowable value of the residual
min_allowable_state_var : float
the lowest value (negative or zero) that a state variable can take during the solution process
ds_init : float
the initial pseudo time step (default: 1.), decrease to 1e-1 or 1e-2 for more robustness
ds_init_decrease : float
how the initial dual time step is decreased upon failure if adaptive_restart is used (default: 4)
adaptive_restart : bool
whether or not the solver restarts with decreased ds_init upon failure (default: True)
diffusion_factor : float
how strongly diffusion is weighted in the pseudo time step adaptation (default: 4) (expert parameter)
global_ds : bool
whether or not to use a global pseudo time step (default: False) (setting to True not recommended)
ds_safety : float
the 'safety factor' in the pseudo time step adaptation (default: 0.1), increase for speed, decrease for robustness
ds_ramp : float
how quickly the pseudo time step is allowed to increase (default: 1.1), increase for speed, decrease for robustness
ds_max : flaot
maximum allowable value of the pseudo time step (default: 1.e4)
max_recursion_depth : int
how many adaptive restarts may be attempted
norm_order : int or np.Inf
the order of the norm used in measuring the residual
log_rate : int
how often a message about the solution status is written
verbose : bool
whether to write out the solver status (log messages) or write out failure descriptions
Returns
-------
a tuple of a library containing temperature, mass fractions, and pressure over mixture fraction,
and the required iteration count, whether or not the system converged, and the final minimum dual time step value,
although if convergence is not obtained, then the library and iteration count output will both be None
"""
original_args = locals()
del original_args['self']
def verbose_print(message):
if verbose:
print(message)
if initial_guess is None:
state = np.copy(self._initial_state)
else:
state = np.copy(initial_guess)
dofscales = self._variable_scales
inv_dofscales = 1. / dofscales
rhs_method = getattr(self, '_' + self._heat_transfer + '_rhs')
jac_method = getattr(self, '_' + self._heat_transfer + '_jac_and_eig')
diffterm = diffusion_factor * self._max_dissipation_rate
ds = np.zeros(self._n_dof)
ds[:] = ds_init
one = np.ones(self._n_dof)
iteration_count = 0
out_count = 0
jac_age = 0
jac_refresh_age = 8
res = tolerance + 1.
rhs = rhs_method(0., state)
nzi = self._nz_interior
neq = self._n_equations
evaluate_jacobian = True
while res > tolerance and iteration_count < max_iterations:
iteration_count += 1
out_count += 1
if evaluate_jacobian:
J, expeig = jac_method(state, diffterm)
ds = np.min(np.vstack([ds_safety / (expeig + 1.e-16),
ds_ramp * ds,
ds_max * one]), axis=0)
if global_ds or iteration_count == 1:
ds[:] = np.min(ds)
one_over_ds = 1. / ds
py_btddod_scale_and_add_diagonal(J, -1., one_over_ds, 1., nzi, neq)
py_btddod_full_factorize(J, nzi, neq,
self._block_thomas_l_values,
self._block_thomas_d_pivots)
jac_age = 0
evaluate_jacobian = False
else:
jac_age += 1
evaluate_jacobian = (jac_age == jac_refresh_age) or res > 1.e-2
dstate = np.zeros(self._n_dof)
py_btddod_full_solve(J,
self._block_thomas_l_values,
self._block_thomas_d_pivots,
rhs, nzi, neq, dstate)
if any(logical_or(isinf(dstate), isnan(dstate))):
if _recursion_depth > max_recursion_depth or not adaptive_restart:
verbose_print('nan/inf detected in state update and solver has already restarted more than'
' max_recursion_depth number of times!')
return None, None, False, np.min(ds)
else:
if adaptive_restart:
verbose_print('NaN/Inf detected in steady_state_solve_psitc! Restarting...')
original_args['ds_init'] /= ds_init_decrease
original_args['_recursion_depth'] += 1
return self.steady_solve_psitc(**original_args)
norm_rhs_old = norm(rhs * inv_dofscales, ord=norm_order)
alpha = 1.
rhs = rhs_method(0., state + dstate)
if any(logical_or(isinf(rhs), isnan(rhs))):
if _recursion_depth > max_recursion_depth or not adaptive_restart:
if verbose:
print('nan/inf detected in state update and solver has already restarted more than'
' max_recursion_depth number of times!')
return None, None, False, np.min(ds)
else:
if adaptive_restart:
verbose_print('NaN/Inf detected in steady_state_solve_psitc! Restarting...')
original_args['ds_init'] /= ds_init_decrease
original_args['_recursion_depth'] += 1
return self.steady_solve_psitc(**original_args)
while norm(rhs * inv_dofscales, ord=norm_order) > max_factor_line_search * norm_rhs_old and alpha > 0.001:
alpha *= 0.5
dstate *= alpha
rhs = rhs_method(0., state + dstate)
verbose_print(f' line search reducing step size to {alpha:.3f}')
evaluate_jacobian = True
state += dstate
res = norm(rhs * inv_dofscales, ord=norm_order)
if res > max_allowed_residual:
message = 'Convergence failure in steady_solve! Residual of {:.2e} detected, ' \
'exceeds the maximum allowable value of {:.2e}.'.format(res, max_allowed_residual)
if _recursion_depth > max_recursion_depth or not adaptive_restart:
verbose_print(message + ' Solver has already restarted more than' \
' max_recursion_depth number of times!')
return None, None, False, np.min(ds)
else:
if adaptive_restart:
verbose_print(message + ' Restarting...')
original_args['ds_init'] /= ds_init_decrease
original_args['_recursion_depth'] += 1
return self.steady_solve_psitc(**original_args)
if np.min(state) < min_allowable_state_var:
message = 'Convergence failure in steady_solve! ' \
'Mass fraction or temperature < ' \
'min_allowable_state_var detected.'.format(res, max_allowed_residual)
if _recursion_depth > max_recursion_depth or not adaptive_restart:
verbose_print(message + ' Solver has already restarted more than' \
' max_recursion_depth number of times!')
return None, None, False, np.min(ds)
else:
if adaptive_restart:
verbose_print(message + ' Restarting...')
original_args['ds_init'] /= ds_init_decrease
original_args['_recursion_depth'] += 1
return self.steady_solve_psitc(**original_args)
if out_count == log_rate and verbose:
out_count = 0
print(' - iter {:4}, max L_exp = {:7.2e}, min(ds) = {:7.2e}, '
'|residual| = {:7.2e}, max(T) = {:6.1f}'.format(iteration_count, np.max(expeig), np.min(ds),
res, np.max(state)))
state[state < 0] = 0.
output_library = self.make_library_from_interior_state(state)
if iteration_count > max_iterations or res > tolerance:
return None, None, False, np.min(ds)
else:
self._iteration_count = iteration_count
self._current_state = np.copy(state)
return output_library, iteration_count, True, np.min(ds)
def compute_steady_state(self, tolerance=1.e-6, verbose=False,
use_psitc=True, newton_args=None, psitc_args=None, transient_args=None):
"""Solve for the steady state of this flamelet, using a number of numerical algorithms
This will first try Newton's method, which is fast if it manages to converge.
If Newton's method fails, the pseudo-transient continuation (psitc) method is used.
The psitc solver will attempt several restarts with increasingly conservative solver settings.
Finally, if both Newton's method and psitc fail, ESDIRK64 time integration with adaptive stepping is attempted.
This is meant to be a convenient interface for common usage.
If it fails, try utilizing each of the steady solvers on their own with special parameters specified.
For exceptionally large mechanisms, say, > 150 species, the psitc solver can be slow,
and setting use_psitc=False will bypass it when Newton's method fails in favor of the ESDIRK solver.
This is only recommended for large mechanisms.
Parameters
----------
tolerance : float
residual tolerance below which the solution has converged
verbose : bool
whether or not to write out status and failure messages
use_psitc : bool
whether or not to use the psitc method when Newton's method fails (if False, tries ESDIRK time stepping next)
newton_args : dict
extra arguments such as max_iterations to pass to the Newton solver
psitc_args : dict
extra arguments such as max_iterations to pass to the PsiTC solver
transient_args : dict
extra arguments such as max_iterations to pass to the ESDI RK solver
Returns
-------
a library containing temperature, mass fractions, and pressure over mixture fraction
"""
the_newton_args = {'tolerance': tolerance, 'log_rate': 1, 'verbose': verbose, 'max_iterations': 38}
if newton_args is not None:
the_newton_args.update(newton_args)
output_library, iteration_count, conv = self.steady_solve_newton(**the_newton_args)
if conv:
return output_library
else:
conv = False
mds = 1.e-6
the_psitc_args = {'tolerance': tolerance, 'log_rate': 1, 'verbose': verbose, 'max_iterations': 400}
if psitc_args is not None:
the_psitc_args.update(psitc_args)
if use_psitc:
output_library, iteration_count, conv, mds = self.steady_solve_psitc(**the_psitc_args)
if conv:
return output_library
else:
the_esdirk_args = {'steady_tolerance': tolerance,
'transient_tolerance': 1.e-8,
'max_time_step': 1e4,
'write_log': verbose,
'log_rate': 1,
'first_time_step': 1e-2 * mds,
'maximum_steps_per_jacobian': 10,
'save_first_and_last_only': True}
if transient_args is not None:
the_esdirk_args.update(transient_args)
transient_library = self.integrate_to_steady(**the_esdirk_args)
steady_library = Library(transient_library.dim('mixture_fraction'))
steady_library.extra_attributes['mech_spec'] = self._mechanism
for p in transient_library.props:
steady_library[p] = transient_library[p][-1, :].ravel()
return steady_library
<file_sep>"""
This module contains the HomogeneousReactor class that provides a high-level interface for a variety of 0-D reactors
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
from spitfire.time.integrator import odesolve
from spitfire.time.methods import KennedyCarpenterS6P4Q3
from spitfire.time.nonlinear import SimpleNewtonSolver
from spitfire.time.stepcontrol import PIController
from spitfire.chemistry.library import Dimension, Library
import numpy as np
from numpy import zeros, hstack, sqrt, sum
from scipy.linalg.lapack import dgetrf as lapack_lu_factor
from scipy.linalg.lapack import dgetrs as lapack_lu_solve
from scipy.sparse.linalg import splu as superlu_factor
from scipy.sparse import csc_matrix as sparse_csc_matrix
import matplotlib.pyplot as plt
class HomogeneousReactor(object):
"""A class for solving zero-dimensional reactors
**Constructor**: specify a mechanism, initial mixture, and reactor specifications
Parameters
----------
mech_spec : spitfire.chemistry.mechanism.ChemicalMechanismSpec instance
the mechanism
initial_mixture : Cantera.Quantity (a Spitfire stream) or Cantera.Solution object
the initial mixture of the reactor
configuration : str
whether the reactor is constant-volume (isochoric) or constant-pressure (isobaric)
heat_transfer : str
whether the reactor is adiabatic, isothermal, or diathermal (finite-rate heat transfer by convection and/or radiation)
mass_transfer : str
whether the reactor is closed or open
convection_temperature : float or callable
the temperature of external fluid in a diathermal reactor, either a constant or a function of time, f(t)
radiation_temperature : float or callable
the temperature of external radiation body of a diathermal reactor, either a constant or a function of time, f(t)
convection_coefficient : float or callable
the convection coefficient, either a constant or a function of time, f(t)
radiative_emissivity : float or callable
the radiative emissivity, either a constant or a function of time, f(t)
shape_dimension_dict : float or callable
The shape and dimension of a diathermal reactor. The shape is one of 'cube', 'sphere', 'capsule', 'tetrahedron', 'octahedron', or 'icosahedron'
(see `wikipedia <https://en.wikipedia.org/wiki/Surface-area-to-volume_ratio#Mathematical_examples>`_).
The dimension is either the characteristic length ('char. length') in meters or volume ('volume') in cubic meters.
mixing_tau : float or callable
The mixing time of an open reactor, either a constant or a function of time, f(t)
feed_temperature : float or callable
the temperature of the feed stream of an open reactor, either a constant or a function of time, f(t)
feed_mass_fractions : np.array or callable
the mass fractions of the feed stream of an open reactor, either a constant or a function of time, f(t)
feed_density : float or callable
the density of the feed stream of an open reactor, either a constant or a function of time, f(t)
rates_sensitivity_type : str
how the chemical source term Jacobian is formed, either 'dense' or 'sparse' for exact formulations
or 'no-TBAF' which ignores third-body and falloff sensitivities. The default is 'dense'.
For large mechanisms (over 100 species) the 'sparse' formulation is far faster than 'dense',
especially for mechanisms of more than 300 species.
sensitivity_transform_type : str
how the Jacobian is transformed for isobaric systems, currently only 'exact' is supported
initial_time : float
the starting time point (in seconds) of the reactor, default to 0.0
"""
_configurations = ['constant pressure', 'constant volume', 'isobaric', 'isochoric']
_configuration_dict = {'constant pressure': 'isobaric',
'isobaric': 'isobaric',
'constant volume': 'isochoric',
'isochoric': 'isochoric'}
_heat_transfers = ['adiabatic', 'isothermal', 'diathermal']
_mass_transfers = ['closed', 'open']
_shape_dict = {'cube': {'l->sov': lambda a: 6. / a,
'v->sov': lambda v: 6. / (np.power(v, 1. / 3.))},
'sphere': {'l->sov': lambda a: 3. / a,
'v->sov': lambda v: 3. / (np.power(3. * v / (4. * np.pi), 1. / 3.))},
'capsule': {'l->sov': lambda a: 12. / (5. * a),
'v->sov': lambda v: 12. / (5. * np.power(3. * v / (10. * np.pi), 1. / 3.))},
'tetrahedron': {'l->sov': lambda a: 6. * sqrt(6.) / a,
'v->sov': lambda v: 6. * sqrt(6.) / np.power(12. * v / np.sqrt(2.), 1. / 3.)},
'octahedron': {'l->sov': lambda a: 3. * sqrt(6.) / a,
'v->sov': lambda v: 3. * sqrt(6.) / np.power(3. * v / np.sqrt(2.), 1. / 3.)},
'icosahedron': {'l->sov': lambda a: 12. * sqrt(3.) / ((3. + sqrt(5.)) * a),
'v->sov': lambda v: 12. * sqrt(3.) / (
(3. + sqrt(5.)) * np.power(12. * v / 5. / (3. + sqrt(5.)), 1. / 3.))}}
_shapes = list(_shape_dict.keys())
@classmethod
def _check_constructor_argument(cls, argument, description, acceptable_values):
if argument.lower() in acceptable_values:
return True
else:
raise ValueError(
"""
Error in reactor construction:
Bad {:} argument detected.
Argument given: {:}
Acceptable values: {:}
""".format(description, argument, acceptable_values))
@classmethod
def _warn_unused_argument(cls, argument_should_be_none, unused_argument, reason):
if argument_should_be_none is not None:
print(
"""
Warning in reactor construction:
The {:} argument is unused.
Reason: {:}
""".format(unused_argument, reason))
@classmethod
def _check_necessary_argument(cls, argument_should_be_not_none, unspecified_argument, reason):
if argument_should_be_not_none is None:
raise ValueError(
"""
Error in reactor construction:
The {:} argument is needed but was unspecified.
Reason: {:}
""".format(unspecified_argument, reason))
else:
return True
def __init__(self,
mech_spec,
initial_mixture,
configuration,
heat_transfer,
mass_transfer,
convection_temperature=None,
radiation_temperature=None,
convection_coefficient=None,
radiative_emissivity=None,
shape_dimension_dict=None,
mixing_tau=None,
feed_temperature=None,
feed_mass_fractions=None,
feed_density=None,
rates_sensitivity_type='dense',
sensitivity_transform_type='exact',
initial_time=0.):
# check configuration (isobaric/isochoric), heat transfer, and mass transfer
if self._check_constructor_argument(configuration, 'configuration', self._configurations):
self._configuration = self._configuration_dict[configuration.lower()]
if self._check_constructor_argument(heat_transfer, 'heat transfer', self._heat_transfers):
self._heat_transfer = heat_transfer.lower()
if self._check_constructor_argument(mass_transfer, 'mass transfer', self._mass_transfers):
self._mass_transfer = mass_transfer.lower()
# save heat transfer parameters, check validity, and warn for unused parameters
if self._heat_transfer == 'adiabatic' or self._heat_transfer == 'isothermal':
self._convection_temperature = 0.
self._radiation_temperature = 0.
self._convection_coefficient = 0.
self._radiative_emissivity = 0.
self._surface_area_to_volume = 0.
message = 'heat transfer is not set to diathermal'
self._warn_unused_argument(convection_temperature, 'convection_temperature', message)
self._warn_unused_argument(radiation_temperature, 'radiation_temperature', message)
self._warn_unused_argument(convection_coefficient, 'convection_coefficient', message)
self._warn_unused_argument(radiative_emissivity, 'radiative_emissivity', message)
self._warn_unused_argument(shape_dimension_dict, 'shape_dimension_dict', message)
else:
message = 'heat transfer is set to diathermal'
if self._check_necessary_argument(convection_temperature, 'convection_temperature', message):
self._convection_temperature = convection_temperature
if self._check_necessary_argument(radiation_temperature, 'radiation_temperature', message):
self._radiation_temperature = radiation_temperature
if self._check_necessary_argument(convection_coefficient, 'convection_coefficient', message):
self._convection_coefficient = convection_coefficient
if self._check_necessary_argument(radiative_emissivity, 'radiative_emissivity', message):
self._radiative_emissivity = radiative_emissivity
if self._check_necessary_argument(shape_dimension_dict, 'shape_dimension_dict', message):
if 'shape' not in shape_dimension_dict:
raise ValueError(
"""
Error in reactor construction:
The shape_dimension_dict argument did not have the required ''shape'' key
""")
else:
self._check_constructor_argument(shape_dimension_dict['shape'], 'shape', self._shapes)
if 'char. length' not in shape_dimension_dict and 'volume' not in shape_dimension_dict:
raise ValueError(
"""
Error in reactor construction:
The shape_dimension_dict argument did not have one of the required ''char. length'' or ''volume'' keys
""")
elif 'char. length' in shape_dimension_dict and 'volume' in shape_dimension_dict:
raise ValueError(
"""
Error in reactor construction:
The shape_dimension_dict argument had both of the ''char. length'' or ''volume'' keys. Only one is allowed.
""")
if 'char. length' in shape_dimension_dict:
method = self._shape_dict[shape_dimension_dict['shape']]['l->sov']
self._surface_area_to_volume = method(shape_dimension_dict['char. length'])
elif 'volume' in shape_dimension_dict:
method = self._shape_dict[shape_dimension_dict['shape']]['v->sov']
self._surface_area_to_volume = method(shape_dimension_dict['volume'])
# save mass transfer specifics and check validity
if self._mass_transfer == 'closed':
self._mixing_tau = 0.
self._feed_temperature = 0.
self._feed_mass_fractions = np.ndarray(1)
self._feed_density = 0.
message = 'mass transfer is not set to open'
self._warn_unused_argument(mixing_tau, 'mixing_tau', message)
self._warn_unused_argument(feed_temperature, 'feed_temperature', message)
self._warn_unused_argument(feed_mass_fractions, 'feed_mass_fractions', message)
self._warn_unused_argument(feed_density, 'feed_density', message)
else:
message = 'mass transfer is set to open'
if self._check_necessary_argument(mixing_tau, 'mixing_tau', message):
self._mixing_tau = np.Inf if mixing_tau is None else mixing_tau
if self._check_necessary_argument(feed_temperature, 'feed_temperature', message):
self._feed_temperature = feed_temperature
if self._check_necessary_argument(feed_mass_fractions, 'feed_mass_fractions', message):
self._feed_mass_fractions = feed_mass_fractions
if self._configuration == 'isobaric':
self._warn_unused_argument(feed_density, 'feed_density',
message + ' but the reactor is isobaric, so feed_density is not needed')
self._feed_density = feed_density
else:
if self._check_necessary_argument(feed_density, 'feed_density', message):
self._feed_density = feed_density
# look for parameters that are functions of time
self._parameter_time_functions = set()
for attribute in ['_convection_temperature',
'_radiation_temperature',
'_convection_coefficient',
'_radiative_emissivity',
'_mixing_tau',
'_feed_temperature',
'_feed_mass_fractions',
'_feed_density']:
if callable(getattr(self, attribute)):
self._parameter_time_functions.add(attribute)
self._tc_is_timevar = '_convection_temperature' in self._parameter_time_functions
self._tr_is_timevar = '_radiation_temperature' in self._parameter_time_functions
self._cc_is_timevar = '_convection_coefficient' in self._parameter_time_functions
self._re_is_timevar = '_radiative_emissivity' in self._parameter_time_functions
self._tau_is_timevar = '_mixing_tau' in self._parameter_time_functions
self._tf_is_timevar = '_feed_temperature' in self._parameter_time_functions
self._yf_is_timevar = '_feed_mass_fractions' in self._parameter_time_functions
self._rf_is_timevar = '_feed_density' in self._parameter_time_functions
self._tc_value = self._convection_temperature(0.) if self._tc_is_timevar else self._convection_temperature
self._cc_value = self._convection_coefficient(0.) if self._cc_is_timevar else self._convection_coefficient
self._tr_value = self._radiation_temperature(0.) if self._tr_is_timevar else self._radiation_temperature
self._re_value = self._radiative_emissivity(0.) if self._re_is_timevar else self._radiative_emissivity
self._tau_value = self._mixing_tau(0.) if self._tau_is_timevar else self._mixing_tau
self._tf_value = self._feed_temperature(0.) if self._tf_is_timevar else self._feed_temperature
self._yf_value = self._feed_mass_fractions(0.) if self._yf_is_timevar else self._feed_mass_fractions
self._rf_value = self._feed_density(0.) if self._rf_is_timevar else self._feed_density
self._rates_sensitivity_option = {'dense': 0, 'no-TBAF': 1, 'sparse': 2}[rates_sensitivity_type]
self._sensitivity_transform_option = {'exact': 0}[sensitivity_transform_type]
self._is_open = self._mass_transfer == 'open'
self._heat_transfer_option = {'adiabatic': 0, 'isothermal': 1, 'diathermal': 2}[self._heat_transfer]
self._mechanism = mech_spec
self._griffon = self._mechanism.griffon
self._initial_pressure = initial_mixture.P
self._current_pressure = np.copy(self._initial_pressure)
self._initial_temperature = initial_mixture.T
self._current_temperature = np.copy(self._initial_temperature)
self._initial_mass_fractions = initial_mixture.Y
self._current_mass_fractions = np.copy(self._initial_mass_fractions)
self._initial_time = np.copy(initial_time)
self._current_time = np.copy(self._initial_time)
self._n_species = self._mechanism.n_species
self._n_reactions = self._mechanism.n_reactions
self._n_equations = self._n_species if self._configuration == 'isobaric' else self._n_species + 1
self._initial_state = zeros(self._n_equations)
if self._configuration == 'isobaric':
self._temperature_index = 0
self._initial_state[0] = np.copy(initial_mixture.T)
self._initial_state[1:] = np.copy(initial_mixture.Y[:-1])
elif self._configuration == 'isochoric':
self._temperature_index = 1
self._initial_state[0] = np.copy(initial_mixture.density)
self._initial_state[1] = np.copy(initial_mixture.T)
self._initial_state[2:] = np.copy(initial_mixture.Y[:-1])
self._current_state = np.copy(self._initial_state)
self._variable_scales = np.ones(self._n_equations)
self._variable_scales[self._temperature_index] = 1.e3
self._left_hand_side_inverse_operator = None
self._diag_indices = np.diag_indices(self._n_equations)
self._extra_logger_title_line1 = f'{"":<10} | {"":<10}|'
self._extra_logger_title_line2 = f' {"T (K)":<8} | {"T-T_0 (K)":<10}|'
def _update_heat_transfer_parameters(self, t):
self._tc_value = self._convection_temperature(t) if self._tc_is_timevar else self._tc_value
self._cc_value = self._convection_coefficient(t) if self._cc_is_timevar else self._cc_value
self._tr_value = self._radiation_temperature(t) if self._tr_is_timevar else self._tr_value
self._re_value = self._radiative_emissivity(t) if self._re_is_timevar else self._re_value
def _update_mass_transfer_parameters(self, t):
self._tau_value = self._mixing_tau(t) if self._tau_is_timevar else self._tau_value
self._tf_value = self._feed_temperature(t) if self._tf_is_timevar else self._tf_value
self._yf_value = self._feed_mass_fractions(t) if self._yf_is_timevar else self._yf_value
def _lapack_setup_wrapper(self, jacobian_method, state, prefactor):
j = jacobian_method(state) * prefactor
j[self._diag_indices] -= 1.
self._left_hand_side_inverse_operator = lapack_lu_factor(j)[:2]
def _superlu_setup_wrapper(self, jacobian_method, state, prefactor):
j = jacobian_method(state)
j *= prefactor
j[self._diag_indices] -= 1.
j = sparse_csc_matrix(j)
j.eliminate_zeros()
self._left_hand_side_inverse_operator = superlu_factor(j)
def _lapack_solve(self, residual):
return lapack_lu_solve(self._left_hand_side_inverse_operator[0],
self._left_hand_side_inverse_operator[1],
residual)[0], 1, True
def _superlu_solve(self, residual):
return self._left_hand_side_inverse_operator.solve(residual), 1, True
def _extra_logger_log(self, state, *args, **kwargs):
T = state[self._temperature_index]
T0 = self.initial_temperature
return f'{T:>10.2f} | {T - T0:>10.2f}|'
@property
def initial_state(self):
"""Obtain this reactor's initial state vector"""
return self._initial_state
@property
def current_state(self):
"""Obtain this reactor's final state vector"""
return self._current_state
@property
def initial_temperature(self):
"""Obtain this reactor's initial temperature"""
return self._initial_temperature
@property
def current_temperature(self):
"""Obtain this reactor's current temperature"""
return self._current_temperature
@property
def initial_pressure(self):
"""Obtain this reactor's initial pressure"""
return self._initial_pressure
@property
def current_pressure(self):
"""Obtain this reactor's current pressure"""
return self._current_pressure
@property
def initial_mass_fractions(self):
"""Obtain this reactor's initial mass fractions"""
return self._initial_mass_fractions
@property
def current_mass_fractions(self):
"""Obtain this reactor's current mass fractions"""
return self._current_mass_fractions
@property
def initial_time(self):
"""Obtain this reactor's initial mass fractions"""
return self._initial_time
@property
def current_time(self):
"""Obtain this reactor's current mass fractions"""
return self._current_time
@property
def n_species(self):
return self._n_species
@property
def n_reactions(self):
return self._n_reactions
@classmethod
def get_supported_reactor_shapes(self):
"""Obtain a list of supported reactor geometries"""
return HomogeneousReactor._shape_dict.keys()
def integrate(self,
stop_at_time=None,
stop_at_steady=None,
stop_criteria=None,
first_time_step=1.e-6,
max_time_step=1.e6,
minimum_time_step_count=40,
transient_tolerance=1.e-10,
write_log=False,
log_rate=100,
maximum_steps_per_jacobian=1,
nonlinear_solve_tolerance=1.e-12,
linear_solver='lapack',
plot=None,
stepper_type=KennedyCarpenterS6P4Q3,
nlsolver_type=SimpleNewtonSolver,
stepcontrol_type=PIController,
extra_integrator_args=dict(),
extra_stepper_args=dict(),
extra_nlsolver_args=dict(),
extra_stepcontrol_args=dict(),
save_first_and_last_only=False):
"""Base method for reactor integration
Parameters
----------
stop_at_time : float
The final time to stop the simulation at
stop_at_steady : float
The tolerance at which a steady state is decided upon and stopped at
stop_criteria : callable (t, state, residual, n_steps)
Any callable that returns True when the simulation should stop
first_time_step : float
The time step size initially used by the time integrator
max_time_step : float
The largest time step the time stepper is allowed to take
minimum_time_step_count : int
The minimum number of time steps to run (helpful for slowly evolving simulations, for instance those with low starting temperatures)
transient_tolerance : float
the target temporal error for transient integration
write_log : bool
whether or not to print integration statistics and status during the simulation
log_rate : int
how often to print log information
maximum_steps_per_jacobian : int
maximum number of steps Spitfire allows before the Jacobian must be re-evaluated - keep low for robustness, try to increase for performance on large mechanisms
nonlinear_solve_tolerance : float
tolerance for the nonlinear solver used in implicit time stepping (optional, default: 1e-12)
linear_solver : str
which linear solver to use, at the moment either 'lapack' (dense, direct) or 'superlu' (sparse, direct) are available
plot : list
List of variables (temperature and/or specific species names) to be plotted after the time integration completes.
No plot is shown if a list is not provided.
Temperature is plotted in the first subplot if any list of variables is provided for plotting (even if temperature is not specified in the list of variables).
Species mass fractions will be plotted in a second subplot if any species names are provided in the list of variables.
stepper_type : spitfire.time.TimeStepper
which (single step) stepper method to use (optional, default: ESDIRK64)
nlsolver_type : spitfire.time.NonlinearSolver
which nonlinear solver method to use (optional, default: SimpleNewtonSolver)
stepcontrol_type : spitfire.time.StepControl
which time step adaptation method to use (optional, default: PIController)
extra_integrator_args : dict
any extra arguments to specify to the time integrator - arguments passed to the odesolve method
extra_stepper_args : dict
extra arguments to specify on the spitfire.time.TimeStepper object
extra_nlsolver_args : dict
extra arguments to specify on the spitfire.time.NonlinearSolver object
extra_stepcontrol_args : dict
extra arguments to specify on the spitfire.time.StepControl object
save_first_and_last_only : bool
whether or not to retain all data (False, default) or only the first and last solutions
Returns
-------
a library containing temperature, mass fractions, and density (isochoric) or pressure (isobaric) over time
"""
def post_step_callback(t, state, *args):
state[state < 0.] = 0.
return state
integrator_args = {'stop_criteria': stop_criteria}
if stop_at_time is not None:
integrator_args.update({'stop_at_time': stop_at_time})
if stop_at_steady is not None:
integrator_args.update({'stop_at_steady': stop_at_steady})
integrator_args.update(extra_integrator_args)
# build the step controller and set attributes
step_control_args = {'first_step': first_time_step,
'max_step': max_time_step,
'target_error': transient_tolerance}
step_control_args.update(extra_stepcontrol_args)
step_controller = stepcontrol_type(**step_control_args)
# build the nonlinear solver and set attributes
nonlinear_solver_args = {'evaluate_jacobian_every_iter': False,
'norm_weighting': 1. / self._variable_scales,
'tolerance': nonlinear_solve_tolerance}
nonlinear_solver_args.update(extra_nlsolver_args)
newton_solver = nlsolver_type(**nonlinear_solver_args)
# build the stepper method and set attributes
stepper_args = {'nonlinear_solver': newton_solver, 'norm_weighting': 1. / self._variable_scales}
stepper_args.update(extra_stepper_args)
stepper = stepper_type(**stepper_args)
# build the rhs and projector methods and do the integration
if self._configuration == 'isobaric':
def rhs_method(time, state):
k = np.zeros(self._n_equations)
self._update_mass_transfer_parameters(time)
self._update_heat_transfer_parameters(time)
self._griffon.reactor_rhs_isobaric(state, self._initial_pressure,
self._tf_value, self._yf_value, self._tau_value,
self._tc_value, self._tr_value,
self._cc_value, self._re_value,
self._surface_area_to_volume,
self._heat_transfer_option, self._is_open, k)
return k
def jac_method(state):
k = np.zeros(self._n_equations)
j = np.zeros(self._n_equations * self._n_equations)
self._griffon.reactor_jac_isobaric(state, self._initial_pressure,
self._tf_value, self._yf_value, self._tau_value,
self._tc_value, self._tr_value,
self._cc_value, self._re_value,
self._surface_area_to_volume,
self._heat_transfer_option, self._is_open,
self._rates_sensitivity_option, self._sensitivity_transform_option,
k, j)
return j.reshape((self._n_equations, self._n_equations), order='F')
elif self._configuration == 'isochoric':
def rhs_method(time, state):
k = np.zeros(self._n_equations)
self._update_mass_transfer_parameters(time)
self._update_heat_transfer_parameters(time)
self._griffon.reactor_rhs_isochoric(state,
self._rf_value, self._tf_value, self._yf_value, self._tau_value,
self._tc_value, self._tr_value,
self._cc_value, self._re_value,
self._surface_area_to_volume,
self._heat_transfer_option, self._is_open, k)
return k
def jac_method(state):
k = np.zeros(self._n_equations)
j = np.zeros(self._n_equations * self._n_equations)
self._griffon.reactor_jac_isochoric(state,
self._rf_value, self._tf_value, self._yf_value, self._tau_value,
self._tc_value, self._tr_value,
self._cc_value, self._re_value,
self._surface_area_to_volume,
self._heat_transfer_option, self._is_open,
self._rates_sensitivity_option, k, j)
return j.reshape((self._n_equations, self._n_equations), order='F')
setup_wrapper = getattr(self, '_' + linear_solver + '_setup_wrapper')
setup_method = lambda t, state, prefactor: setup_wrapper(jac_method, state, prefactor)
solve_method = self._lapack_solve if linear_solver == 'lapack' else self._superlu_solve
output = odesolve(right_hand_side=rhs_method,
initial_state=self._current_state,
initial_time=self._current_time,
step_size=step_controller,
method=stepper,
linear_setup=setup_method,
linear_solve=solve_method,
minimum_time_step_count=minimum_time_step_count,
linear_setup_rate=maximum_steps_per_jacobian,
verbose=write_log,
log_rate=log_rate,
extra_logger_log=self._extra_logger_log,
extra_logger_title_line1=self._extra_logger_title_line1,
extra_logger_title_line2=self._extra_logger_title_line2,
norm_weighting=1. / self._variable_scales,
post_step_callback=post_step_callback,
save_each_step=not save_first_and_last_only,
**integrator_args)
if save_first_and_last_only:
current_state, current_time, time_step_size = output
self._current_state = np.copy(current_state)
self._current_time = np.copy(current_time)
states = np.zeros((1, current_state.size))
states[0, :] = current_state
t = np.zeros(1)
t[0] = current_time
else:
t, states = output
self._current_state = np.copy(states[-1, :])
self._current_time = np.copy(t[-1])
time_dimension = Dimension('time', t)
output_library = Library(time_dimension)
if self._configuration == 'isobaric':
self._current_pressure = self._initial_pressure
self._current_temperature = self._current_state[0]
ynm1 = self._current_state[1:]
self._current_mass_fractions = hstack((ynm1, 1. - sum(ynm1)))
output_library['temperature'] = states[:, 0]
output_library['pressure'] = self.current_pressure + np.zeros_like(output_library['temperature'])
elif self._configuration == 'isochoric':
ynm1 = self._current_state[2:]
self._current_mass_fractions = hstack((ynm1, 1. - sum(ynm1)))
self._current_pressure = self._current_state[0] * self._current_state[1] / sum(
[yi / Mi for (yi, Mi) in zip(self._current_mass_fractions.tolist(),
self._mechanism.molecular_weights.tolist())])
self._current_temperature = self._current_state[1]
output_library['density'] = states[:, 0]
output_library['temperature'] = states[:, 1]
species_names = self._mechanism.species_names
output_library['mass fraction ' + species_names[-1]] = np.ones_like(output_library['temperature'])
for i, s in enumerate(species_names[:-1]):
output_library['mass fraction ' + s] = states[:, self._temperature_index + 1 + i]
output_library['mass fraction ' + species_names[-1]] -= output_library['mass fraction ' + s]
if plot is not None:
t = output_library.time_values * 1.e3
T = output_library['temperature']
if plot == ['temperature']: # only plot temperature if it is the only requested variable
plt.semilogx(t, T)
plt.xlabel('time (ms)')
plt.ylabel('Temperature (K)')
plt.grid()
plt.show()
else: # if variables other than temperature are included in the list, plot those in a separate subplot
f, (axT, axY) = plt.subplots(2, sharex=True, sharey=False)
axT.semilogx(t, T) # always plot T
axT.set_ylabel('Temperature (K)')
axT.grid()
for species_vars in plot:
if species_vars != 'temperature': # separate subplot for species mass fractions
Y = output_library['mass fraction ' + species_vars]
axY.loglog(t, Y, label=species_vars)
axY.set_xlabel('time (ms)')
axY.set_ylabel('Mass Fractions')
axY.set_ylim([1.e-12, 1.e0])
axY.grid()
axY.legend()
plt.show()
return output_library
def integrate_to_steady(self, steady_tolerance=1.e-6, **kwargs):
"""Integrate a reactor until steady state is reached
Parameters
----------
steady_tolerance : float
residual tolerance below which steady state is defined
**kwargs
Arbitrary keyword arguments - see the integrate() method documentation
Returns
-------
a library containing temperature, mass fractions, and density (isochoric) or pressure (isobaric) over time
"""
return self.integrate(stop_at_steady=steady_tolerance, **kwargs)
def integrate_to_time(self, final_time, **kwargs):
"""Integrate a reactor until it reaches a specified simulation time
Parameters
----------
final_time : float
time at which integration ceases
**kwargs
Arbitrary keyword arguments - see the integrate() method documentation
Returns
-------
a library containing temperature, mass fractions, and density (isochoric) or pressure (isobaric) over time
"""
return self.integrate(stop_at_time=final_time, **kwargs)
def integrate_to_steady_after_ignition(self,
steady_tolerance=1.e-4,
delta_temperature_ignition=400.,
**kwargs):
"""Integrate a reactor until steady state is reached after ignition (based on temperature) has occurred.
This is helpful in slowly-evolving systems whose initial residual may be lower than the prescribed tolerance.
Parameters
----------
steady_tolerance : float
residual tolerance below which steady state is defined
delta_temperature_ignition : float
how much the temperature of the reactor must have increased for ignition to have occurred, default is 400 K
**kwargs
Arbitrary keyword arguments - see the integrate() method documentation
Returns
-------
a library containing temperature, mass fractions, and density (isochoric) or pressure (isobaric) over time
"""
if self._heat_transfer == 'isothermal':
raise ValueError(
'integrate_to_steady_after_ignition() called on an isothermal reactor! This is not currently supported!')
else:
T0 = self._initial_temperature
Tidx = self._temperature_index
def stop_at_steady_after_ignition(t, state, residual, *args, **kwargs):
has_ignited = state[Tidx] > (T0 + delta_temperature_ignition)
is_steady = residual < steady_tolerance
return has_ignited and is_steady
return self.integrate(stop_criteria=stop_at_steady_after_ignition, **kwargs)
def compute_ignition_delay(self,
delta_temperature_ignition=400.,
minimum_allowable_residual=1.e-12,
return_solution=False,
**kwargs):
"""Integrate in time until ignition (exceeding a specified threshold of the increase in temperature)
Parameters
----------
delta_temperature_ignition : float
how much the temperature of the reactor must have increased for ignition to have occurred, default is 400 K
minimum_allowable_residual : float
how small the residual can be before the reactor is deemed to 'never' ignite, default is 1.e-12
return_solution : bool
whether or not to return the solution trajectory in addition to the ignition delay, as a tuple, (t, library)
**kwargs
Arbitrary keyword arguments - see the integrate() method documentation
Returns
-------
the ignition delay of the reactor, in seconds, and optionally a library containing temperature, mass fractions, and density (isochoric) or pressure (isobaric) over time
"""
if self._heat_transfer == 'isothermal':
raise ValueError(
'compute_ignition_delay() called on an isothermal reactor! This is not currently supported!')
else:
T0 = self._initial_temperature
Tidx = self._temperature_index
def stop_at_ignition(t, state, residual, *args, **kwargs):
has_ignited = state[Tidx] > (T0 + delta_temperature_ignition)
if residual > minimum_allowable_residual:
return has_ignited
else:
error_msg = f'From compute_ignition_delay(): '
f'residual < minimum allowable value ({minimum_allowable_residual}),'
f' suggesting that the reactor will not ignite.'
f'\nNote that you can set this value with the "minimum_allowable_residual" argument.'
f'\nIt is advised that you also pass write_log=True to observe progress of the simulation '
f'in case it is running perpetually.'
raise ValueError(error_msg)
output_library = self.integrate(stop_criteria=stop_at_ignition,
save_first_and_last_only=not return_solution,
**kwargs)
tau_ignition = output_library.time_values[-1]
if return_solution:
return tau_ignition, output_library
else:
return tau_ignition
<file_sep>Explosive Mode Analysis of Isothermal vs Adiabatic Reactors
===========================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - Simulating the ignition of a hypothetical isothermal
reactor - How to compute quantities relevant to explosive mode analysis
- Comparing isothermal (chemical feedback) vs adiabatic (thermal *and*
chemical feedback) ignition
Introduction
------------
In this demonstration, we’ll take a brief look at chemical explosive
mode analsis (CEMA) of simple hydrogen-air reactors. One reactor is a
typical isobaric, adiabatic system, while the other is a hypothetical
isothermal reactor - heat release is instantaneously dissipated and the
mixture is kept at its initial temperature. The isothermal reactor will
still “ignite” in the sense that self-catalyzing chain reactions will
occur as a pool of radical species is built up. While this chemical
feedback loop will remain, the thermal feedback, wherein heat release
further accelerates combustion, is removed.
.. code:: ipython3
from spitfire import ChemicalMechanismSpec, HomogeneousReactor
import matplotlib.pyplot as plt
import numpy as np
mech = ChemicalMechanismSpec('h2-burke.xml', 'h2-burke')
air = mech.stream(stp_air=True)
fuel = mech.stream('X', 'H2:1')
mix = mech.mix_for_equivalence_ratio(1.0, fuel, air)
mix.TP = 1000., 101325.
Now simply set up the two reactors and integrate them a bit in time.
.. code:: ipython3
isothermal_reactor = HomogeneousReactor(mech, mix, 'isobaric', 'isothermal', 'closed')
adiabatic_reactor = HomogeneousReactor(mech, mix, 'isobaric', 'adiabatic', 'closed')
iso = isothermal_reactor.integrate_to_time(1.e-3)
adi = adiabatic_reactor.integrate_to_time(1.e-3)
Chemical Explosive Mode Analysis
--------------------------------
CEMA is a technique of assessing chemical behavior through
eigenvalue/eigenvector analysis of the chemical source Jacobian matrix.
Feedback cycles such as chemical and thermal runaway in ignition show up
as eigenvalues with positive real part. CEMA is fundamentally limited to
locally linear analysis, which complicates multidimensional problems
where molecular mixing couples nontrivially with explosive chemical
modes. However, for homogeneous reactor models, CEMA is ideal.
Spitfire makes it easy to compute some CEMA-related quantities. Simply
import the ``explosive_mode_analysis`` method and provide it with a
mechanism and a ``Library`` object from a reactor, flamelet, tabulated
chemistry builder, or your own creation.
The fundamental quantity in CEMA is the “explosive eigenvalue,” which is
the largest real part of nonzero eigenvalues. Determining what counts as
a nonzero value is an unresolved issue. Zero eigenvalues exist due to
elemental conservation, and mass/energy conservation for closed
reactors, and a problem is certainty of the eigenvalues (number of valid
digits) because the matrix is singular. Numerical eigensolvers will not
yield many signficiant digits. Spitfire simply calls any eigenvalue of
magnitude less than :math:`10^{-4}` a zero. A more precise definition
would be great for CEMA research but seems unlikely.
In addition to the explosive eigenvalue, you can also request “explosion
indices,” which are normalized components of species and temperature on
the eigenvector corresponding to the explosive mode. Further,
“participation indices” are those components mapped back through
stoichiometry to elementary chemical reactions.
A final note: certain fuels such as DME and biodiesel, discussed in
another reactor demonstration, yield two explosive eigenvalues when
low-temperature ignition pathways are active. Spitfire can easily
incorporate this secondary mode and its explosion/participation indices
- just set a few extra arguments. Hydrogen does not admit a significant
secondary explosive mode, so we turn it off here (it is off by default).
.. code:: ipython3
iso = explosive_mode_analysis(mech, iso, 'isobaric', 'isothermal',
compute_explosion_indices=True,
compute_participation_indices=True,
include_secondary_mode=False)
adi = explosive_mode_analysis(mech, adi, 'isobaric', 'adiabatic',
compute_explosion_indices=True,
compute_participation_indices=True,
include_secondary_mode=False)
.. code:: ipython3
plt.semilogx(iso.time_values * 1.e6, iso['temperature'], '--', label=f'{s} (iso)')
plt.semilogx(adi.time_values * 1.e6, adi['temperature'], '-', label=f'{s} (adi)')
plt.ylabel('T (K)')
plt.xlabel('t (us)')
plt.legend()
plt.grid()
plt.show()
for s, c in [('H', 'b'), ('H2', 'g'), ('OH', 'c'), ('H2O', 'm')]:
plt.loglog(iso.time_values * 1.e6, iso[f'mass fraction {s}'], c + '--', label=f'{s} (iso)')
plt.loglog(adi.time_values * 1.e6, adi[f'mass fraction {s}'], c + '-', label=f'{s} (adi)')
plt.ylabel('mass fraction')
plt.xlabel('t (us)')
plt.legend()
plt.grid()
plt.ylim([1e-5, 1e0])
plt.show()
plt.semilogx(iso.time_values * 1.e6, iso['cema-lexp1'], '--', label='isothermal')
plt.semilogx(adi.time_values * 1.e6, adi['cema-lexp1'], '-', label='adiabatic')
plt.semilogx(iso.time_values * 1.e6, np.zeros_like(iso.time_values), 'k:')
plt.ylabel('$\\lambda_{\\rm exp}$ (Hz)')
plt.xlabel('t (us)')
plt.yscale('symlog', linthreshy=1e2)
plt.legend()
plt.grid()
plt.show()
plt.semilogy(iso.time_values * 1.e6, iso['cema-lexp1'], '--', label='isothermal')
plt.semilogy(adi.time_values * 1.e6, adi['cema-lexp1'], '-', label='adiabatic')
plt.semilogy(iso.time_values * 1.e6, np.zeros_like(iso.time_values), 'k:')
plt.ylabel('$\\lambda_{\\rm exp}$ (Hz)')
plt.xlabel('t (us)')
plt.yscale('symlog', linthreshy=1e2)
plt.xlim([2e2, 3e2])
plt.legend()
plt.grid()
plt.show()
.. image:: isothermal_reactors_with_mode_analysis_files/isothermal_reactors_with_mode_analysis_7_0.png
.. image:: isothermal_reactors_with_mode_analysis_files/isothermal_reactors_with_mode_analysis_7_1.png
.. image:: isothermal_reactors_with_mode_analysis_files/isothermal_reactors_with_mode_analysis_7_2.png
.. image:: isothermal_reactors_with_mode_analysis_files/isothermal_reactors_with_mode_analysis_7_3.png
These preliminary results show a surprising degree of similarity between
the adiabatic and isothermal reactors. The reason is fairly clear though
- the induction phase of the adiabatic reactor is entirely isothermal!
This isn’t always the case - larger fuel breakdown during induction is
endothermic - but for hydrogen the only real difference shows up when
the temperature starts to rise. The final figure above shows the
explosive eigenvalue of the adiabatic reactor rapidly rising to a peak
while the isothermal eigenvalue dies out. Both see the eigenvalue
transition to a negative value, indicating the approach to a stable
equilibrium state, although the adiabatic reactor, due to its much
higher temperature, equilibrates much faster.
Next we look at the explosion and participation indices.
.. code:: ipython3
for name in ['T'] + mech.species_names[:-1]:
ei = iso['cema-ei1 ' + name]
if np.max(ei) > 0.1:
plt.semilogx(iso.time_values * 1.e6, ei, label=name)
plt.ylabel('Explosion index')
plt.xlabel('t (us)')
plt.legend()
plt.grid()
plt.title('Isothermal explosion indices')
plt.show()
for name in ['T'] + mech.species_names[:-1]:
ei = adi['cema-ei1 ' + name]
if np.max(ei) > 0.1:
plt.semilogx(adi.time_values * 1.e6, ei, label=name)
plt.ylabel('Explosion index')
plt.xlabel('t (us)')
plt.legend()
plt.grid()
plt.title('Adiabatic explosion indices')
plt.show()
for i in range(mech.n_reactions):
pi = iso['cema-pi1 ' + str(i)]
if np.max(pi) > 0.2:
plt.semilogx(iso.time_values * 1.e6, pi,
label=mech.gas.reaction_equation(i))
plt.ylabel('Participation index')
plt.xlabel('t (us)')
plt.legend()
plt.grid()
plt.title('Isothermal reaction participation indices')
plt.show()
for i in range(mech.n_reactions):
pi = adi['cema-pi1 ' + str(i)]
if np.max(pi) > 0.2:
plt.semilogx(adi.time_values * 1.e6, pi,
label=mech.gas.reaction_equation(i))
plt.ylabel('Participation index')
plt.xlabel('t (us)')
plt.legend()
plt.grid()
plt.title('Adiabatic reaction participation indices')
plt.show()
.. image:: isothermal_reactors_with_mode_analysis_files/isothermal_reactors_with_mode_analysis_9_0.png
.. image:: isothermal_reactors_with_mode_analysis_files/isothermal_reactors_with_mode_analysis_9_1.png
.. image:: isothermal_reactors_with_mode_analysis_files/isothermal_reactors_with_mode_analysis_9_2.png
.. image:: isothermal_reactors_with_mode_analysis_files/isothermal_reactors_with_mode_analysis_9_3.png
The index analysis shows the relevant species and the importance of
temperature in the explosive mode. Both reactors see the hydrogen
radical playing the largest role during induction, due to its role as
the leading chain carrier in chemical runaway. When ignition peaks,
thermal runaway is indicated by the role of temperature in the adiabatic
reactor’s explosive mode. If you have interest in chain reaction
mechanisms, CK Law’s book *Combustion Physics* has an excellent
description of hydrogen ignition that would go nicely with this
demonstration. You might wonder why the results appear to contain
“noise” as if experiments - as suggested above, eigen-analysis of a
singular matrix is not numerically precise and jumps as seen above where
the eigenvalue transitions are expected.
Conclusions
-----------
This notebook shows how Spitfire enables chemical explosive mode
analysis, and showed some interesting comparisons between adiabatic and
isothermal reactor models.
<file_sep>from spitfire.chemistry.flamelet2d import _Flamelet2D
from spitfire.chemistry.flamelet import Flamelet
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.time.integrator import Governor, NumberOfTimeSteps, FinalTime, Steady, SaveAllDataToList
from spitfire.time.methods import AdaptiveERK54CashKarp, ESDIRK64, BackwardEulerWithError
from spitfire.time.nonlinear import SimpleNewtonSolver
from spitfire.time.stepcontrol import PIController
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
m = ChemicalMechanismSpec(cantera_xml='coh2-hawkes.xml', group_name='coh2-hawkes')
print(m.n_species, m.n_reactions)
pressure = 101325.
air = m.stream(stp_air=True)
air.TP = 300., pressure
synthesis_gas = m.stream('X', 'H2:1, CO:1')
exhaust_gas = m.stream('X', 'CO2:1, H2O:1, CO:0.5, H2:0.001')
fuel1 = m.copy_stream(synthesis_gas)
fuel1.TP = 1000., pressure
fuel2 = m.copy_stream(exhaust_gas)
fuel2.TP = 400., pressure
fuel1_name = 'SG'
fuel2_name = 'EG'
x_cp = m.stoich_mixture_fraction(fuel2, air)
y_cp = m.stoich_mixture_fraction(fuel1, air)
x_cp = x_cp if x_cp < 0.5 else 1. - x_cp
y_cp = y_cp if y_cp < 0.5 else 1. - y_cp
x_cc = 6.
y_cc = 6.
def make_clustered_grid(nx, ny, x_cp, y_cp, x_cc, y_cc):
x_half1 = Flamelet._clustered_grid(nx // 2, x_cp * 2., x_cc)[0] * 0.5
y_half1 = Flamelet._clustered_grid(nx // 2, y_cp * 2., y_cc)[0] * 0.5
x_half2 = (0.5 - x_half1)[::-1]
y_half2 = (0.5 - y_half1)[::-1]
x_range = np.hstack((x_half1, 0.5 + x_half2))
y_range = np.hstack((y_half1, 0.5 + y_half2))
dx_mid = x_range[nx // 2 - 1] - x_range[nx // 2 - 2]
x_range[nx // 2 - 1] -= dx_mid / 3.
x_range[nx // 2 + 0] += dx_mid / 3.
dy_mid = y_range[ny // 2 - 1] - y_range[ny // 2 - 2]
y_range[ny // 2 - 1] -= dy_mid / 3.
y_range[ny // 2 + 0] += dy_mid / 3.
return x_range, y_range
nx = 32
ny = nx
x_range, y_range = make_clustered_grid(nx, ny, x_cp, y_cp, x_cc, y_cc)
x_grid, y_grid = np.meshgrid(x_range, y_range)
chi11_max = 1.
chi22_max = 1.
f = _Flamelet2D(m, 'unreacted', pressure, air, fuel1, fuel2, chi11_max, chi22_max, grid_1=x_range, grid_2=y_range)
nq = f._n_equations
phi0 = np.copy(f._initial_state)
def plot_contours(phi, variable, i):
fig = plt.figure()
iq = 0 if variable == 'T' else m.species_index(variable) + 1
phi2d = phi[iq::nq].reshape((ny, nx), order='F')
phi02d = phi0[iq::nq].reshape((ny, nx), order='F')
ax = plt.subplot2grid((3, 4), (2, 1), rowspan=1, colspan=2)
ax.cla()
ax.plot(x_range, phi02d[0, :], 'b--', label='EQ')
ax.plot(x_range, phi2d[0, :], 'g-', label='SLFM')
Tmin = 200.
Tmax = int(np.max(phi) // 100 + 1) * 100
if variable == 'T':
ax.set_ylim([Tmin, Tmax])
ax.yaxis.tick_right()
ax.set_xlabel('$Z_1$')
ax.set_xlim([0, 1])
ax.grid(True)
# ax.legend(loc='best')
ax.legend(loc='center left', bbox_to_anchor=(-0.4, 0.5), ncol=1, borderaxespad=0, frameon=False)
ax = plt.subplot2grid((3, 4), (0, 0), rowspan=2, colspan=1)
ax.cla()
ax.plot(phi02d[:, 0], y_range, 'b--', label='EQ')
ax.plot(phi2d[:, 0], y_range, 'g-', label='SLFM')
if variable == 'T':
ax.set_xlim([Tmin, Tmax])
ax.set_ylabel('$Z_2$')
ax.set_ylim([0, 1])
ax.grid(True)
# ax.legend(loc='best')
ax = plt.subplot2grid((3, 4), (0, 1), rowspan=2, colspan=2)
cax = plt.subplot2grid((3, 4), (0, 3), rowspan=2, colspan=1)
ax.cla()
if variable == 'T':
contour = ax.contourf(x_grid, y_grid, phi2d, cmap=plt.get_cmap('magma'),
norm=Normalize(Tmin, Tmax), levels=np.linspace(Tmin, Tmax, 20))
else:
contour = ax.contourf(x_grid, y_grid, phi2d, cmap=plt.get_cmap('magma'),
levels=np.linspace(np.min(phi2d), np.max(phi2d), 20))
plt.colorbar(contour, cax=cax)
ax.plot([0, 0, 1, 0], [0, 1, 0, 0], 'k-', linewidth=0.5, zorder=4)
# ax.contour(x_grid, y_grid, phi2d, cmap=plt.get_cmap('rainbow'),
# norm=Normalize(Tmin, Tmax), levels=np.linspace(Tmin, Tmax, 20))
t1 = plt.Polygon(np.array([[1, 0], [1, 1], [0, 1]]), color='w', zorder=3)
ax.add_patch(t1)
ax.text(-0.1, 1.04, fuel1_name, fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=10)
ax.text(0.95, -0.05, fuel2_name, fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=11)
ax.text(-0.08, -0.05, 'air', fontdict={'fontweight': 'bold'},
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.7), zorder=12)
# ax.set_xlabel('$Z_1$')
# ax.set_ylabel('$Z_2$', rotation=0)
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.grid(True)
cax.set_title('SLFM T' if variable == 'T' else 'SLFM ' + variable)
plt.tight_layout()
plt.savefig(f'img_{variable}_{i}.png')
g = Governor()
g.log_rate = 10
g.clip_to_positive = True
g.norm_weighting = 1. / f._variable_scales
g.projector_setup_rate = 20
g.time_step_increase_factor_to_force_jacobian = 1.1
g.time_step_decrease_factor_to_force_jacobian = 0.8
data = SaveAllDataToList(initial_solution=phi0,
save_frequency=100,
file_prefix='ip',
file_first_and_last_only=True,
save_first_and_last_only=True)
g.custom_post_process_step = data.save_data
newton = SimpleNewtonSolver(evaluate_jacobian_every_iter=False,
norm_weighting=g.norm_weighting,
tolerance=1.e-12,
max_nonlinear_iter=8)
esdirk = ESDIRK64(norm_weighting=g.norm_weighting, nonlinear_solver=newton)
pi = PIController(first_step=1.e-8, target_error=1.e-10, max_step=1.e0)
viz_dt = 1.e-3
viz_nt = 100
plot_contours(phi0, 'T', 'ic')
phi = np.copy(phi0)
dt = 1.e-8
for i in range(viz_nt):
g.termination_criteria = FinalTime((i + 1) * viz_dt)
pi._first_step = dt
_, phi, _, dt = g.integrate(right_hand_side=f.rhs,
linear_setup=f.block_Jacobi_setup,
linear_solve=f.block_Jacobi_solve,
initial_condition=phi,
method=esdirk,
controller=pi,
initial_time=i * viz_dt)
plot_contours(phi, 'T', i)
<file_sep>Transient Flamelet Example: Ignition and Advanced Time Integration
==================================================================
*This demo is part of Spitfire, with*\ `licensing and copyright info
here. <https://github.com/sandialabs/Spitfire/blob/master/license.md>`__
*Highlights* - Computing a transient ignition trajectory - Advanced time
integration parameters
Introduction
------------
In this demonstration we repeatedly compute the ignition trajectory of a
hydrogen flamelet, using different time steppers, target errors for
adaptive time step selection, and more.
.. code:: ipython3
from spitfire import ChemicalMechanismSpec, FlameletSpec, Flamelet
import cantera as ct
import matplotlib.pyplot as plt
import numpy as np
from time import perf_counter
Just as a reminder, here we build the chemical mechanism instace from a
Cantera solution instead of simply providing the XML file and group name
directly. Either works, but sometimes you might already have a Cantera
solution available.
Following that, we build a preheated air stream and a fuel mixture of
Nitrogen and Hydrogen that gives a chosen stoichiometric mixture
fraction. These are sent to a ``FlameletSpec`` object for later.
.. code:: ipython3
sol = ct.Solution('h2-burke.xml', 'h2-burke')
mech = ChemicalMechanismSpec.from_solution(sol)
Tair = 1200.
pressure = 101325.
zstoich = 0.1
air = mech.stream(stp_air=True)
air.TP = Tair, pressure
fuel = mech.mix_fuels_for_stoich_mixture_fraction(mech.stream('X', 'H2:1'), mech.stream('X', 'N2:1'), zstoich, air)
fuel.TP = 300., pressure
flamelet_specs = FlameletSpec(mech_spec=mech,
initial_condition='unreacted',
oxy_stream=air,
fuel_stream=fuel,
grid_points=34,
max_dissipation_rate=1.e3)
Baseline Ignition Trajectory
----------------------------
First, we’ll simply call ``integrate_to_steady`` without any parameters
to compute a flamelet ignition trajectory with the default time
integration settings.
.. code:: ipython3
ft = Flamelet(flamelet_specs)
output = ft.integrate_to_steady()
.. code:: ipython3
for i in range(0, output.time_values.size, 20):
plt.plot(output.mixture_fraction_values, output['temperature'][i, :], color='gray', alpha=0.2)
plt.plot(output.mixture_fraction_values, output['temperature'][0, :], '--', label='unreacted')
plt.plot(output.mixture_fraction_values, output['temperature'][-1, :], label='steady')
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('temperature (K)')
plt.legend()
plt.show()
for i in range(0, output.time_values.size, 20):
plt.plot(output.mixture_fraction_values, output['mass fraction H2'][i, :], color='gray', alpha=0.2)
plt.plot(output.mixture_fraction_values, output['mass fraction O2'][i, :], color='gray', alpha=0.2)
plt.plot(output.mixture_fraction_values, output['mass fraction H2O'][i, :], color='gray', alpha=0.2)
plt.plot(output.mixture_fraction_values, output['mass fraction H2'][0, :], '--', label='unreacted H2')
plt.plot(output.mixture_fraction_values, output['mass fraction H2'][-1, :], label='steady H2')
plt.plot(output.mixture_fraction_values, output['mass fraction O2'][0, :], '--',label='unreacted O2')
plt.plot(output.mixture_fraction_values, output['mass fraction O2'][-1, :], label='steady O2')
plt.plot(output.mixture_fraction_values, output['mass fraction H2O'][0, :],'--', label='unreacted H2O')
plt.plot(output.mixture_fraction_values, output['mass fraction H2O'][-1, :], label='steady H2O')
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('mass fraction')
plt.legend()
plt.show()
for i in range(0, output.time_values.size, 20):
plt.plot(output.mixture_fraction_values, output['mass fraction OH'][i, :], color='gray', alpha=0.2)
plt.plot(output.mixture_fraction_values, output['mass fraction OH'][0, :], '--', label='unreacted OH')
plt.plot(output.mixture_fraction_values, output['mass fraction OH'][-1, :], label='steady OH')
plt.grid()
plt.xlabel('mixture fraction')
plt.ylabel('mass fraction')
plt.legend()
plt.show()
.. image:: transient_ignition_stepper_details_files/transient_ignition_stepper_details_6_0.png
.. image:: transient_ignition_stepper_details_files/transient_ignition_stepper_details_6_1.png
.. image:: transient_ignition_stepper_details_files/transient_ignition_stepper_details_6_2.png
Time Steppers and Target Error
------------------------------
Now we import some of Spitfire’s built-in time stepping methods. These
include BDF-1 (Backward Euler) and some implicit Runge-Kutta methods of
orders 3-5. The ``SimpleNewtonSolver`` is needed as the nonlinear solver
for the implicit time methods.
.. code:: ipython3
from spitfire import (SimpleNewtonSolver,
BackwardEulerS1P1Q1,
KennedyCarpenterS6P4Q3,
KvaernoS4P3Q2,
KennedyCarpenterS4P3Q2,
KennedyCarpenterS8P5Q4)
To run with a custom stepper, provide the ``stepper_type`` argument. A
related parameter in these adaptive steppers is the
``transient_tolerance``, which should be decreased to improve accuracy
through smaller time steps. This parameter relates to efficiency through
the order of the integration technique - for first-order (P1) Backward
Euler the relationship is linear and a ten times reduction in the
tolerance should roughly correspond to a ten times increase in run time.
For the P3, P4, and P5 methods, however, a factor of ten increase in run
time can enable a tolerance 1000, 10000, and 100000 times smaller,
respectively. This gives high-order methods a dramatic advantage in
solving to extreme accuracy, and in practice their better stability also
makes them faster at computing flamelet solutions without concern of
error.
Below we iterate over some combinations of methods and tolerances,
followed by some results and discussion.
.. code:: ipython3
output_dict = dict()
for name, method, tol in [('BDF1', BackwardEulerS1P1Q1, 1e-7),
('Kv-P3', KvaernoS4P3Q2, 1e-7),
('KC-P3', KennedyCarpenterS4P3Q2, 1e-7),
('KC-P4', KennedyCarpenterS6P4Q3, 1e-7),
('KC-P5', KennedyCarpenterS8P5Q4, 1e-7),
('BDF1', BackwardEulerS1P1Q1, 1e-8),
('Kv-P3', KvaernoS4P3Q2, 1e-10),
('KC-P3', KennedyCarpenterS4P3Q2, 1e-10),
('KC-P4', KennedyCarpenterS6P4Q3, 1e-11),
('KC-P5', KennedyCarpenterS8P5Q4, 1e-12)]:
print(f'Running w/{name:5}, tolerance {tol:5.1e} ... ', end='')
tic = perf_counter()
ft = Flamelet(flamelet_specs)
the_output = ft.integrate_to_steady(stepper_type=method, transient_tolerance=tol)
dcput = perf_counter() - tic
nsteps = the_output.time_values.size
output_dict[(name, tol)] = (the_output, nsteps, dcput)
print(f'done in {nsteps:5} time steps in {dcput:4.1f} s, mean cput/step of {dcput*1e3/nsteps:3.1f} ms')
.. parsed-literal::
Running w/BDF1 , tolerance 1.0e-07 ... done in 5199 time steps in 5.8 s, mean cput/step of 1.1 ms
Running w/Kv-P3, tolerance 1.0e-07 ... done in 872 time steps in 2.3 s, mean cput/step of 2.7 ms
Running w/KC-P3, tolerance 1.0e-07 ... done in 396 time steps in 2.0 s, mean cput/step of 5.0 ms
Running w/KC-P4, tolerance 1.0e-07 ... done in 153 time steps in 1.1 s, mean cput/step of 7.2 ms
Running w/KC-P5, tolerance 1.0e-07 ... done in 112 time steps in 1.1 s, mean cput/step of 9.5 ms
Running w/BDF1 , tolerance 1.0e-08 ... done in 16227 time steps in 20.4 s, mean cput/step of 1.3 ms
Running w/Kv-P3, tolerance 1.0e-10 ... done in 8580 time steps in 12.9 s, mean cput/step of 1.5 ms
Running w/KC-P3, tolerance 1.0e-10 ... done in 3677 time steps in 7.3 s, mean cput/step of 2.0 ms
Running w/KC-P4, tolerance 1.0e-11 ... done in 1169 time steps in 4.4 s, mean cput/step of 3.7 ms
Running w/KC-P5, tolerance 1.0e-12 ... done in 774 time steps in 4.2 s, mean cput/step of 5.5 ms
From the plot of maximum flamelet temperature, we can see that the
ignition delay time seems similar across all of the methods and target
errors. This is a typical observation in transient flamelet models - a
solution that stays stable will usually be sufficiently accurate (in
terms of time integration error - other errors are still relevant).
Some interesting observations can be made from the efficiency numbers.
1. Higher-order methods are the fastest for a given tolerance, both for
high, stability-limited values and lower values meant for accurate
simulations.
2. Higher-order methods require more CPU time per step but take fewer
steps.
3. Higher-order methods are significantly faster at computing solutions
with lower tolerances
4. Decreasing the tolerance decreases the CPU time per step
The first three conclusions are not surprising, but the fourth one is
confusing at first. The reason the CPU time per step decreases with
tolerance is that Spitfire, similarly to other advanced ODE solvers, not
only adaptively changes the time step size but also adaptively
evaluates/factorizes the Jacobian matrix. Expensive calculations with
the Jacobian are kept to a minimum, and can be minimized further when
the error tolerance is lower. This is because smaller time steps fail
less frequently and give smoother behavior when nonlinear transients
appear suddenly. Jacobian reuse is why KC-P4 (Spitfire’s default
stepper) is nearly twice as fast per time step at the lower tolerance
(:math:`10^{-11}`) than the higher one - however, the increase in time
step count does still increase the runtime.
The second plot below shows the time step size history for each solver.
Observe especially how BDF-1 with tolerance of :math:`10^{-8}` requires
the smallest step size, compared to the higher-order methods with much
lower tolerances. The fifth-order method (KC-P5) is always taking a time
step at least an order of magnitude larger, even at a tolerance of
:math:`10^{-12}`.
.. code:: ipython3
for name, transient_tol in output_dict:
output, nsteps, dcput = output_dict[(name, transient_tol)]
plt.semilogx(output.time_values * 1.e3, np.max(output['temperature'], axis=1), label=f'{name}|{transient_tol}|{dcput:.1f} s')
plt.grid()
plt.xlabel('time (ms)')
plt.ylabel('max flamelet temperature (K)')
plt.legend()
plt.show()
for name, transient_tol in output_dict:
output, nsteps, dcput = output_dict[(name, transient_tol)]
t = output.time_values
dt = t[1:] - t[:-1]
plt.loglog(t[:-1] * 1.e3, dt * 1.e6, label=f'{name}/{transient_tol:.1e} | {dcput:.1f} s')
plt.grid()
plt.xlabel('time (ms)')
plt.ylabel('time step size (us)')
plt.show()
.. image:: transient_ignition_stepper_details_files/transient_ignition_stepper_details_12_0.png
.. image:: transient_ignition_stepper_details_files/transient_ignition_stepper_details_12_1.png
Jacobian/Preconditioner Reuse
-----------------------------
We can roughly control the degree of Jacobian/preconditioner reuse with
the ``maximum_steps_per_jacobian`` argument to ``integrate_to_steady``,
which maps to the ``linear_setup_rate`` argument in Spitfire’s
``odesolve`` method. Setting this argument to 1 means we always
re-evaluate the Jacobian on every time step. Setting it to 20, for
instance, simply means that a maximum of 20 steps can occur between
re-evaluation/factorization. The default setting in
``integrate_to_steady`` is 10, and while it is tempting to increase it
further, this can negatively impact stability and force smaller time
steps during nonlinear transients.
Other parameters such as ``time_step_increase_factor_to_force_jacobian``
and ``time_step_decrease_factor_to_force_jacobian`` to ``odesolve`` can
be used to control Jacobian/preconditioner reuse.
Also we can build the nonlinear solver differently. The
``SimpleNewtonSolver`` class can be built with the
``evaluate_jacobian_every_iter`` argument set to True. This can be
provided through ``integrate_to_steady`` with the
``extra_nlsolver_args`` argument (takes a dictionary of keyword
arguments to be passed to the nonlinear solver construction). This goes
a step further than ``maximum_steps_per_jacobian=1``, never reusing the
Jacobian matrix even between nonlinear solver iterations. This improves
stability quite a bit, and reduces nonlinear iteration count, but for
larger mechanisms (more species) this is extremely costly. For hydrogen,
however, it’s still pretty cheap and works out well in the end.
Below we run the fifth-order method with different values of
``maximum_steps_per_jacobian`` and then with the Jacobian re-evaluated
at every Newton iteration. This enables us to get past the
:math:`10^{-7}` tolerance limit imposed by stability on the lagged
Jacobian runs, leading to very fast solutions. I’ll repeat it though -
this option is much slower (take a look at the CPU time per step) and is
impractical for larger mechanisms where the Jacobian
evaluation/factorization is the dominant cost.
.. code:: ipython3
for name, method, tol, mspj, nlsa in [('KC-P5-1Jac', KennedyCarpenterS8P5Q4, 1e-12, 1, dict()),
('KC-P5-2Jac', KennedyCarpenterS8P5Q4, 1e-12, 2, dict()),
('KC-P5-5Jac', KennedyCarpenterS8P5Q4, 1e-12, 5, dict()),
('KC-P5-20Jac', KennedyCarpenterS8P5Q4, 1e-12, 20, dict()),
('KC-P5-100Jac', KennedyCarpenterS8P5Q4, 1e-12, 100, dict()),
('KC-P5-fullJac', KennedyCarpenterS8P5Q4, 1e-12, 1, {'evaluate_jacobian_every_iter': True}),]:
print(f'Running w/{name:15}, tolerance {tol:5.1e} ... ', end='')
tic = perf_counter()
ft = Flamelet(flamelet_specs)
the_output = ft.integrate_to_steady(stepper_type=method,
transient_tolerance=tol,
maximum_steps_per_jacobian=mspj,
extra_nlsolver_args=nlsa)
dcput = perf_counter() - tic
nsteps = the_output.time_values.size
output_dict[(name, tol)] = (the_output, nsteps, dcput)
print(f'done in {nsteps:5} time steps in {dcput:4.1f} s, mean cput/step of {dcput*1e3/nsteps:3.1f} ms')
.. parsed-literal::
Running w/KC-P5-1Jac , tolerance 1.0e-12 ... done in 776 time steps in 3.5 s, mean cput/step of 4.5 ms
Running w/KC-P5-2Jac , tolerance 1.0e-12 ... done in 774 time steps in 3.5 s, mean cput/step of 4.6 ms
Running w/KC-P5-5Jac , tolerance 1.0e-12 ... done in 769 time steps in 3.8 s, mean cput/step of 5.0 ms
Running w/KC-P5-20Jac , tolerance 1.0e-12 ... done in 778 time steps in 4.7 s, mean cput/step of 6.1 ms
Running w/KC-P5-100Jac , tolerance 1.0e-12 ... done in 780 time steps in 5.6 s, mean cput/step of 7.2 ms
Running w/KC-P5-fullJac , tolerance 1.0e-12 ... done in 773 time steps in 8.5 s, mean cput/step of 11.0 ms
.. code:: ipython3
for name, method, tol, mspj, nlsa in [('KC-P5-fullJac', KennedyCarpenterS8P5Q4, 1e-4, 1, {'evaluate_jacobian_every_iter': True}),
('KC-P5-fullJac', KennedyCarpenterS8P5Q4, 1e-7, 1, {'evaluate_jacobian_every_iter': True})]:
print(f'Running w/{name:15}, tolerance {tol:5.1e} ... ', end='')
tic = perf_counter()
ft = Flamelet(flamelet_specs)
the_output = ft.integrate_to_steady(stepper_type=method,
transient_tolerance=tol,
maximum_steps_per_jacobian=mspj,
extra_nlsolver_args=nlsa)
dcput = perf_counter() - tic
nsteps = the_output.time_values.size
output_dict[(name, tol)] = (the_output, nsteps, dcput)
print(f'done in {nsteps:5} time steps in {dcput:4.1f} s, mean cput/step of {dcput*1e3/nsteps:3.1f} ms')
.. parsed-literal::
Running w/KC-P5-fullJac , tolerance 1.0e-04 ... done in 72 time steps in 1.4 s, mean cput/step of 19.2 ms
Running w/KC-P5-fullJac , tolerance 1.0e-07 ... done in 106 time steps in 1.8 s, mean cput/step of 17.4 ms
.. code:: ipython3
for name, transient_tol in output_dict:
if 'KC-P5' in name and 'Jac' in name:
output, nsteps, dcput = output_dict[(name, transient_tol)]
plt.semilogx(output.time_values * 1.e3, np.max(output['temperature'], axis=1), label=f'{name}|{transient_tol}|{dcput:.1f} s')
plt.grid()
plt.xlabel('time (ms)')
plt.ylabel('max flamelet temperature (K)')
plt.legend()
plt.show()
for name, transient_tol in output_dict:
if 'KC-P5' in name and 'Jac' in name:
output, nsteps, dcput = output_dict[(name, transient_tol)]
t = output.time_values
dt = t[1:] - t[:-1]
plt.loglog(t[:-1] * 1.e3, dt * 1.e6, label=f'{name}/{transient_tol:.1e} | {dcput:.1f} s')
plt.grid()
plt.xlabel('time (ms)')
plt.ylabel('time step size (us)')
plt.show()
.. image:: transient_ignition_stepper_details_files/transient_ignition_stepper_details_16_0.png
.. image:: transient_ignition_stepper_details_files/transient_ignition_stepper_details_16_1.png
Conclusions
-----------
In this notebook we’ve solved a transient flamelet ignition problem with
a number of different time integration settings. There’s more that can
be modified but these are the major options. We’ve shown the merit of
high-order methods provided by Spitfire and shown some results regarding
Jacobian/preconditioner reuse.
<file_sep>import pickle
def run():
from spitfire.time.integrator import odesolve
from spitfire.time.stepcontrol import PIController
from spitfire.time.methods import CashKarpS6P5Q4
import numpy as np
def right_hand_side(q, fluid_density, drag_coeff, gravity, surface_area, mass):
vel_x = q[0]
vel_y = q[1]
f = fluid_density * surface_area * drag_coeff / mass
return np.array([-f * vel_x * vel_x,
-f * vel_y * vel_y - gravity,
vel_x,
vel_y])
q0 = np.array([1., 10., 0., 0.]) # initial condition
rf = 1.23 # fluid density, kg/m3
ro = 7.86e3 # object (cannonball) density, kg/m3
g = 9.8 # gravitational constant, m/s2
r = 4. * 2.54 / 100. # object radius, m
sa = 4. * np.pi * r * r
m = ro * np.pi * r * r * r * 4. / 3.
drag_coeff_dict = {'no drag': 0.0,
'weak drag': 4.0,
'strong drag': 40.0}
def object_has_landed(t, state, *args, **kwargs):
vel_y = state[1]
pos_y = state[3]
return pos_y < 0.5 * r and vel_y < 0
solution_data = dict()
for key in drag_coeff_dict:
cd = drag_coeff_dict[key]
solution_data[key] = odesolve(lambda t, y: right_hand_side(y, rf, cd, g, sa, m),
q0,
step_size=PIController(first_step=1e-6, target_error=1e-10, max_step=1e-3),
method=CashKarpS6P5Q4(),
save_each_step=10,
stop_criteria=object_has_landed)
return solution_data
if __name__ == '__main__':
output = run()
with open('gold.pkl', 'wb') as file_output:
pickle.dump(output, file_output)
<file_sep>"""
This module contains Spitfire's core functionality for chemistry problems.
"""
<file_sep>Chemical Reaction Models
------------------------
.. toctree::
:maxdepth: 1
:caption: Demonstrations:
demo/reactors/thermochemistry_Cantera_Spitfire_griffon
demo/reactors/one_step_heptane_ignition
demo/reactors/ignition_delay_NTC_DME
demo/reactors/oscillating_ignition_extinction
demo/reactors/isothermal_reactors_with_mode_analysis
demo/reactors/ignition_extinction_heptane
demo/flamelet/introduction_to_flamelets
demo/flamelet/high_level_tabulation_api_adiabatic
demo/flamelet/example_nonadiabatic_flamelets
demo/flamelet/tabulation_api_presumed_pdf
demo/flamelet/custom_pdf_logmean_chi
demo/flamelet/methane_shear_layer_tabulation
demo/flamelet/transient_ignition_stepper_details
demo/flamelet/example_transient_flamelet_rate_sensitivity
demo/flamelet/example_coal_combustion_model
The following sections detail some of the math behind Spitfire's reaction modeling capabilities.
We present the governing equations for non-premixed flamelets and homogeneous reactors,
and supported reaction rate laws and thermodynamic property models.
Governing Equations for Non-premixed Flamelets
++++++++++++++++++++++++++++++++++++++++++++++
Spitfire's flamelet and tabulation capabilities support generalized flamelet models for RANS/LES of hydrocarbon pool fires in the non-premixed combustion regime.
While direct support is provided for sooting hydrocarbon fires,
Spitfire leverages a modular, extensible stack from thermochemistry evaluator, numerical methods, solvers, and tabulation techniques.
In this section we detail the governing equations solved by Spitfire for equilibrium, strained steady/transient, adiabatic/nonadiabatic flamelets.
All of these equations are defined with the mixture fraction coordinate, which is a conserved scalar that describes inert mixing between fuel and air in a fire.
These equations can be derived in a variety of ways, either through local coordinate transformations along the isosurfaces of the mixture fraction
or by transforming species transport equations to follow a general Lagrangian coordinate frame.
In both cases, time and length scale separation arguments lead to one-dimensional equilibrium/strained/nonadiabatic flamelet models of flows with two inlets.
The thermochemical state is described with the mass fractions :math:`Y_i` and temperature :math:`T`.
These are described by the mixture fraction :math:`\mathcal{Z}` and other parameters, and in transient flamelets we consider
evolution in a Lagrangian time :math:`t`.
Equations :eq:`adiabatic_flamelet_Yi_eqn` and :eq:`adiabatic_flamelet_T_eqn` describe adiabatic flamelets,
which balance molecular mixing (with strength proportional the scalar dissipation rate :math:`\chi`) with species production/consumption and heat release through chemical reactions.
These equations include variable heat capacity effects and the full form of the heat flux including the diffusive enthalpy temrs.
They do not account for differential diffusion and are based on a unity Lewis number and mass fraction form of the species diffusive fluxes.
Generalizations of the diffusive flux models have been derived and are planned for a future version of Spitfire.
The variable heat capacity term and enthalpy flux terms are optional in Spitfire, but are included by default as they are very important for modeling nonadiabatic flows with strong coupling to radiative losses.
The steady version of this equation set is derived by simply removing the time derivative term.
.. math::
\frac{\partial Y_i}{\partial t} = \frac{\chi}{2}\frac{\partial^2 Y_i}{\partial \mathcal{Z}^2} + \frac{\omega_i}{\rho},
:label: adiabatic_flamelet_Yi_eqn
.. math::
\frac{\partial T}{\partial t} = \frac{\chi}{2}\left(\frac{\partial^2 T}{\partial \mathcal{Z}^2} + \frac{\partial T}{\partial \mathcal{Z}}\sum_{i=1}^{n}\frac{c_{p,i}}{c_p}\frac{\partial Y_i}{\partial \mathcal{Z}} + \frac{1}{c_p}\frac{\partial c_p}{\partial \mathcal{Z}}\frac{\partial T}{\partial \mathcal{Z}}\right) - \frac{1}{\rho c_p}\sum_{i=1}^{n}\omega_i h_i.
:label: adiabatic_flamelet_T_eqn
These equations are supplemented by Dirichlet boundary conditions defined by the oxidizer and fuel states,
.. math::
T(t, 0) &= T_{\mathrm{oxy}}, \\
Y_i(t, 0) &= Y_{i,\mathrm{oxy}}, \\
T(t, 1) &= T_{\mathrm{fuel}}, \\
Y_i(t, 1) &= Y_{i,\mathrm{fuel}}.
The dissipation rate :math:`\chi` can be a constant or depend on the mixture fraction.
Spitfire provides the common form due to Peters:
.. math::
\chi(\mathcal{Z}) = \chi_{\mathrm{max}} \exp\left( -2\left[\mathrm{erfinv}(2\mathcal{Z}-1)\right]^2 \right).
Spitfire also supports nonadiabatic flamelet models, which modifies only the temperature equation,
.. math::
\frac{\partial T}{\partial t} = \left.\frac{\partial T}{\partial t}\right|_{\mathrm{adiabatic}} + \frac{1}{\rho c_p}\left(h(T_\infty - T) + \varepsilon\sigma(T_\mathrm{surf}^4 - T^4)\right).
:label: nonadiabatic_flamelet_T_eqn
The convection and radiation coefficients and reference temperatures are allowed to vary over the mixture fraction.
Further, the heat loss terms can be scaled to facilitate simulation of strong radiative quenching in large sooting fires,
.. math::
\frac{\partial T}{\partial t} = \left.\frac{\partial T}{\partial t}\right|_{\mathrm{adiabatic}} + \frac{1}{\rho c_p}\frac{\chi_{\mathrm{max}}}{\mathcal{Z}_{\mathrm{st}}(1 - \mathcal{Z}_{\mathrm{st}})}\left(h\frac{T_\infty - T}{T_{\mathrm{max}} - T_\infty} + \varepsilon\sigma\frac{T_\mathrm{surf}^4 - T^4}{T_{\mathrm{max}}^4 - T_\mathrm{surf}^4}\right).
:label: scaled_nonadiabatic_flamelet_T_eqn
where :math:`\mathcal{Z}_{\mathrm{st}}` is the stoichiometric mixture fraction.
The preferred model supported in Spitfire for hydrocarbon pool fires is to use a convective/linear form of the heat loss with :math:`h'` to :math:`10^6-10^7`,
which rapidly drives hydrocarbon flamelets to extinction, covering a wide range of the heat loss space broadly throughout the mixture fraction.
Governing Equations for Homogeneous Reactors
++++++++++++++++++++++++++++++++++++++++++++
Homogeneous, or 'zero-dimensional,' reactor models represent well-mixed combustion systems wherein there are no spatial gradients in any quantity describing the chemical mixture.
In such a system the temperature :math:`T`, pressure :math:`p`, and composition, expressed by the mass fractions :math:`\{Y_i\}`, are all homogeneous and a reactor may be modeled as a point in space whose properties vary only in time, :math:`t`.
Zero-dimensional systems are idealizations of very complex systems but have their place in the modeling of combustion processes.
In a lab setting this idealization can be approached with *jet-stirred reactors* (JSR, also commonly referred to as a continuous stirred tank reactor (CSTR), perfectly stirred reactor (PSR), and Longwell reactor) and *rapid compression machines* (RCM).
A JSR is a continuous stirred tank reactor to which reactants are fed and mixed rapidly through several opposed jets.
A JSR unit coupled with downstream gas chromatography and mass spectrometry can be used to quantify the composition of the chemical mixture as reaction proceeds.
Detailed models of combustion kinetics are developed through comparison with experimental data from such systems.
The rapid computational solution of kinetic models for simple, zero-dimensional reactors is of great fundamental importance to combustion modeling.
In Spitfire we model mixtures of ideal gases in twelve types of reactors distinguished by their *configuration*, *heat transfer*, and *mass transfer*.
We use *configuration* to distinguish isochoric, or constant-volume, reactors from isobaric, or constant-pressure, ones.
*Mass transfer* refers to a closed, or batch, reactor or an open reactor with mass flow at specified mean residence time.
Three types of *heat transfer* are available:
- adiabatic: a reactor with insulated walls that allow no heat transfer with the surroundings
- isothermal: a reactor whose temperature is held exactly constant for all time
- diathermal: a reactor whose walls allow a finite rate of heat transfer by radiative heat transfer to a nearby surface and convective heat transfer to a fluid flowing around the reactor
Below we detail the equations governing isochoric and isobaric reactors with any pair of models for mass and transfer.
In all cases, the gas is modeled as a mixture of thermally perfect gases.
The ideal gas law applies to each species and the bulk mixture.
.. math::
p = \rho R_\mathrm{mix} T,
:label: ideal_gas_law
where the mixture specific gas constant, :math:`R_\mathrm{mix}`, is the universal molar gas constant divided by the mixture molar mass,
.. math::
M_\mathrm{mix} = \left(\sum_{i=1}^{n}\frac{Y_i}{M_i}\right)^{-1},
:label: mixture_molar_mass
where :math:`M_i` is the molar mass of species :math:`i` in a mixture with :math:`n` distinct species.
Additionally, the mass fractions, of which only :math:`n-1` are independent (and only :math:`n-1` are solved for in Spitfire), are related by
.. math::
Y_n = 1 - \sum_{i=1}^{n-1}Y_i.
:label: Y_n_eqn
Isochoric Reactors
__________________
Figure :numref:`figure_isochoric_reactor_diagram` diagrams an open, constant-volume reactor with diathermal walls.
The reactor has volume :math:`V` and surface area :math:`A`.
Convective heat transfer is described by a fluid temperature :math:`T_\infty` and convective heat transfer coefficient :math:`h`.
Radiative heat transfer is determined by the temperature of the surface, :math:`T_\mathrm{surf}`, and effective emissivity, :math:`\varepsilon`.
Finally, for an isochoric reactor, mass transfer is specified by the residence time :math:`\tau`, based on volumetric flow rate, and inflowing state
with temperature :math:`T_\mathrm{in}`, density :math:`\rho_\mathrm{in}`, and mass fractions :math:`\{Y_{i,\mathrm{in}}\}`.
.. _figure_isochoric_reactor_diagram:
.. figure:: images/isochoric-reactor-diagram.png
:width: 660px
:align: center
:figclass: align-center
Isochoric reactor with mass transfer and convective and radiative heat transfer
Isochoric reactors are governed by the following equations for the reactor density, temperature, and first :math:`n-1` mass fractions.
:math:`\omega_i` is the net mass production rate of species :math:`i` due to chemical reactions,
:math:`c_v` is the specific, isochoric heat capacity of the mixture,
and :math:`e_i` and :math:`e_{i,\mathrm{in}}` are the specific internal energy of species :math:`i` in the feed and reactor.
:math:`\sigma` is the Stefan-Boltzmann constant.
We solve these equations in Spitfire to maximize sparsity and minimize calculation cost of Jacobian matrices.
Recent work [MJ2018]_ has shown that the conservation error that results from solving a temperature equation instead of an energy equation is negligible when high-order time integration methods such as those in Spitfire are used.
Closed reactors are obtained by setting :math:`\tau\to\infty`.
Adiabatic reactors are obtained by setting :math:`h,\varepsilon\to0`.
Isothermal reactors are obtained by setting the entire right-hand side of the temperature equation to zero.
.. math::
\frac{\partial \rho}{\partial t} = \frac{\rho_\mathrm{in} - \rho}{\tau},
:label: isochoric_rho_eqn
.. math::
\frac{\partial Y_i}{\partial t} = \frac{\rho_\mathrm{in}}{\rho}\frac{Y_{i,\mathrm{in}} - Y_i}{\tau} + \frac{\omega_i}{\rho}, \quad i=1,\ldots,n-1
:label: isochoric_Yi_eqn
.. math::
\frac{\partial T}{\partial t} = \frac{\rho_\mathrm{in}}{\rho \tau c_v}\sum_{i=1}^{n}Y_{i,\mathrm{in}}(e_{i,\mathrm{in}} - e_i) - \frac{1}{\rho c_v}\sum_{i=1}^{n}\omega_i e_i + \frac{1}{\rho c_v}\frac{A}{V}\left(h(T_\infty - T) + \varepsilon\sigma(T_\mathrm{surf}^4 - T^4)\right),
:label: isochoric_T_eqn
.. [MJ2018] <NAME>, <NAME>,
On the consistency of state vectors and Jacobian matrices,
Combustion and Flame,
Volume 193,
2018,
Pages 257-271,
Isobaric Reactors
_________________
Figure :numref:`figure_isobaric_reactor_diagram` diagrams an open, constant-pressure reactor with diathermal walls.
The pressure, :math:`p`, of this reactor is held constant by the motion of a weightless, frictionless piston.
The expansion work done by this process is an important difference between isobaric and isochoric reactors.
We solve the following equations governing isobaric reactors.
:math:`c_p` is the specific, isobaric heat capacity of the mixture,
and :math:`h_i` and :math:`h_{i,\mathrm{in}}` are the specific internal enthalpy of species :math:`i` in the feed and reactor.
.. math::
\frac{\partial Y_i}{\partial t} = \frac{Y_{i,\mathrm{in}} - Y_i}{\tau} + \frac{\omega_i}{\rho}, \quad i=1,\ldots,n-1
:label: isobaric_Yi_eqn
.. math::
\frac{\partial T}{\partial t} = \frac{1}{\tau c_p}\sum_{i=1}^{n}Y_{i,\mathrm{in}}(h_{i,\mathrm{in}} - h_i) - \frac{1}{\rho c_p}\sum_{i=1}^{n}\omega_i h_i + \frac{1}{\rho c_p}\frac{A}{V}\left(h(T_\infty - T) + \varepsilon\sigma(T_\mathrm{surf}^4 - T^4)\right),
:label: isobaric_T_eqn
.. _figure_isobaric_reactor_diagram:
.. figure:: images/isobaric-reactor-diagram.png
:width: 660px
:align: center
:figclass: align-center
Isobaric reactor with expansion work, mass transfer, and convective and radiative heat transfer
Chemical Kinetic Models
+++++++++++++++++++++++
Spitfire currently supports various forms of reaction rate expressions for homogeneous gas-phase systems.
Let :math:`n_r` be the number of elementary reactions.
The net mass production rate of species :math:`i` is then
.. math::
\omega_i = M_i \sum_{j=1}^{n_r}\nu_{i,j}q_j,
where :math:`\nu_{i,j}` is the net molar stoichiometric coefficient of species :math:`i` in reaction :math:`j` and :math:`q_j` is the rate of progress of reaction :math:`j`.
The rate of progress is decomposed into two parts: first, the mass action component :math:`\mathcal{R}_j`, and second, the TBAF component :math:`\mathcal{C}_j` which contains third-body enhancement and falloff effects.
.. math::
q_j = \overset{\text{mass action}}{\mathcal{R}_j}\cdot\overset{\text{3-body + falloff}}{\mathcal{C}_j}.
The mass action component consists of forward and reverse rate constants :math:`k_{f,j}` and :math:`k_{r,j}` along with products of species concentrations :math:`\left\langle c_k\right\rangle`,
.. math::
\mathcal{R}_j = k_{f,j}\prod_{k=1}^{N}\left\langle c_k\right\rangle^{\nu^f_{k,j}} - k_{r,j}\prod_{k=1}^{N}\left\langle c_k\right\rangle^{\nu^r_{k,j}},
in which :math:`\nu^f_{i,j}` and :math:`\nu^r_{i,j}` are the forward and reverse stoichiometric coefficients of species :math:`i` in reaction :math:`j`, respectively.
The forward rate constant is found with a modified Arrhenius expression,
.. math::
k_{f,j} = A_j T^{b_j} \exp\left(-\frac{E_{a,j}}{R_u T}\right) = A_j T^{b_j} \exp\left(-\frac{T_{a,j}}{T}\right),
where :math:`A_j`, :math:`b_j`, and :math:`E_{a,j}` are the pre-exponential factor, temperature exponent, and activation energy of reaction :math:`j`, respectively.
We define :math:`T_{a,j}=E_{a,j}/R_u` as the activation temperature.
The reverse rate constant of an irreversible reaction is zero.
:math:`k_{r,j}` for a reversible reaction is found with the equilibrium constant :math:`K_{c,j}`, via :math:`k_{r,j} = k_{f,j}/K_{c,j}`.
The equilibrium constant is
.. math::
K_{c,j} = \left(\frac{p_\text{atm}}{R_u}\right)^{\Xi_j}\exp\left(\sum_{k=1}^{N}\nu_{k,j}B_k\right),
where :math:`\Xi_j=\sum_{k=1}^{N}\nu_{k,j}` and :math:`B_k` is
.. math::
B_k = -\ln(T) + \frac{M_k}{R_u}\left(s_k - \frac{h_k}{T}\right).
For the TBAF component :math:`\mathcal{C}_j` there are two nontrivial cases: (1) a three-body reaction and, (2) a unimolecular/recombination falloff reaction.
If a reaction is not of a three-body or falloff type, then :math:`\mathcal{C}_j = 1`.
For three-body reactions, it is
.. math::
\mathcal{C}_j = \left\langle c_{TB,j}\right\rangle = \sum_{i=1}^{N}\alpha_{i,j}\left\langle c_i\right\rangle,
where :math:`\alpha_{i,j}` is the third-body enhancement factor of species :math:`i` in reaction :math:`j`, and :math:`\left\langle c_{TB,j}\right\rangle` is the third-body-enhanced concentration of reaction :math:`j`.
The quantity :math:`\alpha_{i,j}` defaults to one if not specified.
For falloff reactions, the TBAF component is
.. math::
\mathcal{C}_j = \frac{p_{fr,j}}{1 + p_{fr,j}}\mathcal{F}_j,
in which :math:`p_{fr,j}` and :math:`\mathcal{F}_j` are the falloff reduced pressure and falloff blending factor, respectively.
The falloff reduced pressure is
.. math::
p_{fr,j} = \frac{k_{0,j}}{k_{f,j}}\mathcal{T}_{F,j},
where :math:`k_{0,j}` is the low-pressure limit rate constant evaluated with low-pressure Arrhenius parameters :math:`A_{0,j}`, :math:`b_{0,j}`, :math:`E_{a,0,j}`, and :math:`\mathcal{T}_{F,j}` is the concentration of the mixture
which is either that of a single species if specified or the third-body-enhanced concentration if not.
The falloff blending factor :math:`\mathcal{F}_j` depends upon the specified falloff form.
For the Lindemann approach, :math:`\mathcal{F}_j = 1`.
In the Troe form,
.. math::
\mathcal{F}_j &= \mathcal{F}_{\text{cent}}^{1/(1+(A/B)^2)}, \\
\mathcal{F}_{\text{cent}} &= (1-a_{\text{Troe}})\exp\left(-\frac{T}{T^{***}}\right) + a_{\text{Troe}}\exp\left(-\frac{T}{T^{*}}\right) + \exp\left(-\frac{T^{**}}{T}\right), \\
A &= \log_{10}p_{FR,j} - 0.67\log_{10}\mathcal{F}_{\text{cent}} - 0.4, \\
B &= 0.806 - 1.1762\log_{10}\mathcal{F}_{\text{cent}} - 0.14\log_{10}p_{FR,j},
where :math:`a_{\text{Troe}}`, :math:`T^{*}`, :math:`T^{**}`, and :math:`T^{***}` are specified parameters of the Troe form.
If :math:`T^{***}` is unspecified in the mechanism file then its term is ignored.
todo: add description of new non-elementary reaction rates
Species Thermodynamics
++++++++++++++++++++++
Spitfire supports ideal mixtures of thermally perfect species, and species heat capacity may be modeled as a constant or through a NASA-7 or NASA-9 polynomial.
NASA-7 polynomials must be used with two temperature regions, while any number of regions may be used with a NASA-9 polynomial.
<file_sep>"""
This module contains classes and methods for building tabulated chemistry libraries
"""
# Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License
# along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
#
# Questions? Contact <NAME> (<EMAIL>)
import numpy as np
from scipy.interpolate import interp1d
from scipy.interpolate import InterpolatedUnivariateSpline
from multiprocessing import Pool, Manager
from time import perf_counter
from spitfire.chemistry.flamelet import Flamelet, FlameletSpec
from spitfire.chemistry.library import Dimension, Library
import spitfire.chemistry.analysis as sca
import copy
from functools import partial
import itertools
"""these names are specific to tabulated chemistry libraries for combustion"""
_mixture_fraction_name = 'mixture_fraction'
_dissipation_rate_name = 'dissipation_rate'
_enthalpy_defect_name = 'enthalpy_defect'
_enthalpy_offset_name = 'enthalpy_offset'
_scaled_scalar_variance_name = 'scaled_scalar_variance_mean'
_stoich_suffix = '_stoich'
_mean_suffix = '_mean'
def _write_library_header(lib_type, mech, fuel, oxy, verbose):
if verbose:
print('-' * 82)
print(f'building {lib_type} library')
print('-' * 82)
print(f'- mechanism: {mech.mech_file_path}')
print(f'- {mech.n_species} species, {mech.n_reactions} reactions')
print(f'- stoichiometric mixture fraction: {mech.stoich_mixture_fraction(fuel, oxy):.3f}')
print('-' * 82)
return perf_counter()
def _write_library_footer(cput0, verbose):
if verbose:
print('----------------------------------------------------------------------------------')
print(f'library built in {perf_counter() - cput0:6.2f} s')
print('----------------------------------------------------------------------------------', flush=True)
def build_unreacted_library(flamelet_specs, verbose=True):
"""Build a flamelet library for a nonreacting flow, with linear enthalpy and mass fraction profiles.
Parameters
----------
flamelet_specs : FlameletSpec or dictionary of arguments for a FlameletSpec
flamelet specifications
Returns
-------
library : spitfire.chemistry.library.Library instance
a chemistry library with only the "mixture_fraction" dimension
"""
fs = FlameletSpec(**flamelet_specs) if isinstance(flamelet_specs, dict) else copy.copy(flamelet_specs)
fs.initial_condition = 'unreacted'
flamelet = Flamelet(fs)
return flamelet.make_library_from_interior_state(flamelet.initial_interior_state)
def build_adiabatic_eq_library(flamelet_specs, verbose=True):
"""Build a flamelet library with the equilibrium (infinitely fast) chemistry assumption,
equivalently with Gibbs free energy minimization.
Parameters
----------
flamelet_specs : FlameletSpec or dictionary of arguments for a FlameletSpec
flamelet specifications
Returns
-------
library : spitfire.chemistry.library.Library instance
a chemistry library with only the "mixture_fraction" dimension
"""
fs = FlameletSpec(**flamelet_specs) if isinstance(flamelet_specs, dict) else copy.copy(flamelet_specs)
fs.initial_condition = 'equilibrium'
flamelet = Flamelet(fs)
return flamelet.make_library_from_interior_state(flamelet.initial_interior_state)
def build_adiabatic_bs_library(flamelet_specs, verbose=True):
"""Build a flamelet library with the Burke-Schumann (idealized, one-step combustion) assumptions
Parameters
----------
flamelet_specs : FlameletSpec or dictionary of arguments for a FlameletSpec
flamelet specifications
Returns
-------
library : spitfire.chemistry.library.Library instance
a chemistry library with only the "mixture_fraction" dimension
"""
fs = FlameletSpec(**flamelet_specs) if isinstance(flamelet_specs, dict) else copy.copy(flamelet_specs)
fs.initial_condition = 'Burke-Schumann'
flamelet = Flamelet(fs)
return flamelet.make_library_from_interior_state(flamelet.initial_interior_state)
def _build_nonadiabatic_defect_unstrained_library(initialization, flamelet_specs, n_defect_st=16, verbose=True):
flamelet_specs = FlameletSpec(**flamelet_specs) if isinstance(flamelet_specs, dict) else copy.copy(flamelet_specs)
m = flamelet_specs.mech_spec
fuel = flamelet_specs.fuel_stream
oxy = flamelet_specs.oxy_stream
z_st = m.stoich_mixture_fraction(fuel, oxy)
flamelet_specs.initial_condition = initialization
flamelet = Flamelet(flamelet_specs)
# compute the extreme enthalpy defect
state_ad = flamelet.initial_interior_state
adiabatic_lib = flamelet.make_library_from_interior_state(state_ad)
enthalpy_ad = sca.compute_specific_enthalpy(m, adiabatic_lib)['enthalpy']
z_interior = flamelet.mixfrac_grid[1:-1]
state_cooled_eq = state_ad.copy()
state_cooled_eq[::m.n_species] = z_interior * fuel.T + (1 - z_interior) * oxy.T
cooled_lib = flamelet.make_library_from_interior_state(state_cooled_eq)
enthalpy_cooled_eq = sca.compute_specific_enthalpy(m, cooled_lib)['enthalpy']
z = flamelet.mixfrac_grid
h_ad_st = interp1d(z, enthalpy_ad)(z_st)
h_ce_st = interp1d(z, enthalpy_cooled_eq)(z_st)
defect_ext = h_ad_st - h_ce_st
# build the library with equilibrium solutions at with enthalpies offset by the triangular defect form
defect_range = np.linspace(-defect_ext, 0, n_defect_st)[::-1]
z_dim = Dimension(_mixture_fraction_name, flamelet.mixfrac_grid)
g_dim = Dimension(_enthalpy_defect_name + _stoich_suffix, defect_range)
output_library = Library(z_dim, g_dim)
output_library.extra_attributes['mech_spec'] = m
for p in adiabatic_lib.props:
output_library[p] = output_library.get_empty_dataset()
output_library['enthalpy_defect'] = output_library.get_empty_dataset()
output_library['enthalpy_cons'] = output_library.get_empty_dataset()
output_library['enthalpy'] = output_library.get_empty_dataset()
output_library[_mixture_fraction_name] = output_library.get_empty_dataset()
fz = z.copy()
fz[z <= z_st] = z[z <= z_st] / z_st
fz[z > z_st] = (1 - z[z > z_st]) / (1 - z_st)
ns = m.n_species
g_library = flamelet.make_library_from_interior_state(flamelet.initial_interior_state)
for ig in range(n_defect_st):
defected_enthalpy = enthalpy_ad + defect_range[ig] * fz
for iz in range(1, z.size - 1):
y = np.zeros(ns)
for ispec in range(ns):
y[ispec] = g_library['mass fraction ' + m.species_names[ispec]][iz]
m.gas.HPY = defected_enthalpy[iz], flamelet.pressure, y
if initialization == 'equilibrium':
m.gas.equilibrate('HP')
g_library['temperature'][iz] = m.gas.T
for ispec in range(ns):
g_library['mass fraction ' + m.species_names[ispec]][iz] = m.gas.Y[ispec]
for p in g_library.props:
if p != 'defected_enthapy':
output_library[p][:, ig] = g_library[p].ravel()
output_library['enthalpy_defect'][:, ig] = defected_enthalpy - enthalpy_ad
output_library['enthalpy_cons'][:, ig] = enthalpy_ad
output_library['enthalpy'][:, ig] = defected_enthalpy
output_library[_mixture_fraction_name][:, ig] = flamelet.mixfrac_grid.ravel()
return output_library
def build_nonadiabatic_defect_eq_library(flamelet_specs, n_defect_st=16, verbose=True):
"""Build a flamelet library with the equilibrium (infinitely fast) chemistry assumption
and heat loss effects captured through a presumed triangular form of the enthalpy defect.
Parameters
----------
flamelet_specs : FlameletSpec or dictionary of arguments for a FlameletSpec
flamelet specifications
n_defect_st : Int
the number of stoichiometric enthalpy defect values to include in the table (default: 16)
Returns
-------
library : spitfire.chemistry.library.Library instance
a chemistry library with the "mixture_fraction" and "enthalpy_defect_stoich" dimensions
"""
return _build_nonadiabatic_defect_unstrained_library('equilibrium', flamelet_specs, n_defect_st, verbose)
def build_nonadiabatic_defect_bs_library(flamelet_specs, n_defect_st=16, verbose=True):
"""Build a flamelet library with the Burke-Schumann chemistry assumption
and heat loss effects captured through a presumed triangular form of the enthalpy defect.
Parameters
----------
flamelet_specs : FlameletSpec or dictionary of arguments for a FlameletSpec
flamelet specifications
n_defect_st : Int
the number of stoichiometric enthalpy defect values to include in the table (default: 16)
Returns
-------
library : spitfire.chemistry.library.Library instance
a chemistry library with the "mixture_fraction" and "enthalpy_defect_stoich" dimensions
"""
return _build_nonadiabatic_defect_unstrained_library('Burke-Schumann', flamelet_specs, n_defect_st, verbose)
def build_adiabatic_slfm_library(flamelet_specs,
diss_rate_values=np.logspace(-3, 2, 16),
diss_rate_ref='stoichiometric',
verbose=True,
solver_verbose=False,
_return_intermediates=False,
include_extinguished=False,
diss_rate_log_scaled=True):
"""Build a flamelet library with an adiabatic strained laminar flamelet model
Parameters
----------
flamelet_specs : dictionary or FlameletSpec instance
data for the mechanism, streams, mixture fraction grid, etc.
diss_rate_values : np.array
reference dissipation rate values in the table (note that if the flamelet extinguishes at any point,
the extinguished flamelet and larger dissipation rates are not included in the library unless the
include_extinguished argument is set to True)
diss_rate_ref : str
the reference point of the specified dissipation rate values, either 'stoichiometric' or 'maximum'
verbose : bool
whether or not to show progress of the library construction
include_extinguished : bool
whether or not to include extinguished states in the output table, if encountered in the provided range of
dissipation rates, off by default
diss_rate_log_scaled : bool
whether or not the range of dissipation rates is logarithmically scaled
Returns
-------
library : spitfire.chemistry.library.Library instance
the structured chemistry library
"""
if isinstance(flamelet_specs, dict):
flamelet_specs = FlameletSpec(**flamelet_specs)
m = flamelet_specs.mech_spec
fuel = flamelet_specs.fuel_stream
oxy = flamelet_specs.oxy_stream
flamelet_specs.initial_condition = 'equilibrium'
if diss_rate_ref == 'maximum':
flamelet_specs.max_dissipation_rate = 0.
else:
flamelet_specs.stoich_dissipation_rate = 0.
cput00 = _write_library_header('adiabatic SLFM', m, fuel, oxy, verbose)
f = Flamelet(flamelet_specs)
table_dict = dict()
nchi = diss_rate_values.size
suffix = _stoich_suffix if diss_rate_ref == 'stoichiometric' else '_max'
x_values = list()
for idx, chival in enumerate(diss_rate_values):
if diss_rate_ref == 'maximum':
flamelet_specs.max_dissipation_rate = chival
else:
flamelet_specs.stoich_dissipation_rate = chival
flamelet = Flamelet(flamelet_specs)
if verbose:
print(f'{idx + 1:4}/{nchi:4} (chi{suffix} = {chival:8.1e} 1/s) ', end='', flush=True)
cput0 = perf_counter()
x_library = flamelet.compute_steady_state(tolerance=1.e-6, verbose=solver_verbose, use_psitc=True)
dcput = perf_counter() - cput0
if np.max(flamelet.current_temperature - flamelet.linear_temperature) < 10. and not include_extinguished:
if verbose:
print(' extinction detected, stopping. The extinguished state will not be included in the table.')
break
else:
if verbose:
print(f' converged in {dcput:6.2f} s, T_max = {np.max(flamelet.current_temperature):6.1f}')
z_st = flamelet.mechanism.stoich_mixture_fraction(flamelet.fuel_stream, flamelet.oxy_stream)
chi_st = flamelet._compute_dissipation_rate(np.array([z_st]),
flamelet._max_dissipation_rate,
flamelet._dissipation_rate_form)[0]
x_values.append(chi_st)
table_dict[chi_st] = dict()
for k in x_library.props:
table_dict[chi_st][k] = x_library[k].ravel()
flamelet_specs.initial_condition = flamelet.current_interior_state
if _return_intermediates:
table_dict[chi_st]['adiabatic_state'] = np.copy(flamelet.current_interior_state)
if _return_intermediates:
_write_library_footer(cput00, verbose)
return table_dict, f.mixfrac_grid, np.array(x_values)
else:
z_dim = Dimension(_mixture_fraction_name, f.mixfrac_grid)
x_dim = Dimension(_dissipation_rate_name + _stoich_suffix, np.array(x_values), diss_rate_log_scaled)
output_library = Library(z_dim, x_dim)
output_library.extra_attributes['mech_spec'] = m
for quantity in table_dict[chi_st]:
output_library[quantity] = output_library.get_empty_dataset()
for ix, x in enumerate(x_values):
output_library[quantity][:, ix] = table_dict[x][quantity]
_write_library_footer(cput00, verbose)
return output_library
def _expand_enthalpy_defect_dimension_transient(chi_st, managed_dict, flamelet_specs, table_dict,
h_stoich_spacing, verbose, input_integration_args, solver_verbose):
flamelet_specs.initial_condition = table_dict[chi_st]['adiabatic_state']
flamelet_specs.stoich_dissipation_rate = chi_st
flamelet_specs.heat_transfer = 'nonadiabatic'
flamelet_specs.scale_heat_loss_by_temp_range = True
flamelet_specs.scale_convection_by_dissipation = True
flamelet_specs.use_linear_ref_temp_profile = True
flamelet_specs.convection_coefficient = flamelet_specs.convection_coefficient if flamelet_specs.convection_coefficient is not None else 1.e7
flamelet_specs.radiative_emissivity = 0.
integration_args = dict(
{'first_time_step': 1.e-9,
'max_time_step': 1.e-1,
'write_log': solver_verbose,
'log_rate': 100,
'print_exception_on_failure': False})
if input_integration_args is not None:
integration_args.update(input_integration_args)
if 'transient_tolerance' not in integration_args:
integration_args['transient_tolerance'] = 1.e-8
cput0000 = perf_counter()
running = True
while running and integration_args['transient_tolerance'] > 1.e-15:
try:
fnonad = Flamelet(flamelet_specs)
transient_lib = fnonad.integrate_for_heat_loss(**integration_args)
running = False
except Exception as e:
if solver_verbose:
print(
f'Transient heat loss calculation failed with tolerance of {integration_args["transient_tolerance"]:.1e}, retrying with 100x lower...')
integration_args.update(dict({'transient_tolerance': integration_args['transient_tolerance'] * 1.e-2}))
indices = [0]
z = fnonad.mixfrac_grid
z_st = fnonad.mechanism.stoich_mixture_fraction(fnonad.fuel_stream, fnonad.oxy_stream)
h_tz = sca.compute_specific_enthalpy(flamelet_specs.mech_spec, transient_lib)['enthalpy']
h_ad = h_tz[0, :]
nt, nz = h_tz.shape
last_hst = interp1d(z, h_ad)(z_st)
for i in range(nt):
this_hst = interp1d(z, h_tz[i, :])(z_st)
if last_hst - this_hst > h_stoich_spacing:
indices.append(i)
last_hst = this_hst
if nt - 1 not in indices:
indices.append(-1)
for i in indices:
defect = h_tz[i, :] - h_ad
gst = float(interp1d(z, defect)(z_st))
this_data = dict()
this_data['enthalpy_defect'] = np.copy(defect)
this_data['enthalpy_cons'] = np.copy(h_ad)
this_data['enthalpy'] = np.copy(h_tz[i, :])
this_data[_mixture_fraction_name] = fnonad.mixfrac_grid
for q in transient_lib.props:
this_data[q] = transient_lib[q][i, :]
managed_dict[(chi_st, gst)] = this_data
dcput = perf_counter() - cput0000
if verbose:
print('chi_st = {:8.1e} 1/s converged in {:6.2f} s'.format(chi_st, dcput), flush=True)
def _expand_enthalpy_defect_dimension_steady(chi_st, managed_dict, flamelet_specs, table_dict,
h_stoich_spacing, verbose, input_integration_args, solver_verbose):
flamelet_specs.initial_condition = table_dict[chi_st]['adiabatic_state']
flamelet_specs.stoich_dissipation_rate = chi_st
flamelet_specs.heat_transfer = 'nonadiabatic'
flamelet_specs.scale_heat_loss_by_temp_range = False
flamelet_specs.scale_convection_by_dissipation = False
flamelet_specs.use_linear_ref_temp_profile = True
flamelet_specs.radiative_emissivity = 0.
flamelet_specs.convection_coefficient = 0.
flamelet = Flamelet(flamelet_specs)
first = True
refine_before_extinction = False
extinguished = False
extinguished_first = False
maxT = -1
state_old = np.copy(flamelet.current_interior_state)
hval = 0.
dh = 1.e-1
diff_target = 1e-1
diff_norm = 1e-1
hval_max = 1.e10
solutions = []
hvalues = []
hvalues.append(hval)
solutions.append(dict())
for p in table_dict[chi_st]:
if p != 'adiabatic_state':
solutions[-1][p] = table_dict[chi_st][p]
current_state = table_dict[chi_st]['adiabatic_state']
cput0000 = perf_counter()
while first or (not extinguished and hval < hval_max):
hval += dh
if first:
first = False
flamelet_specs.convection_coefficient = hval
flamelet_specs.initial_condition = current_state
flamelet = Flamelet(flamelet_specs)
g_library = flamelet.compute_steady_state(verbose=solver_verbose)
current_state = flamelet.current_interior_state
maxT = np.max(current_state)
diff_norm = np.max(np.abs(current_state - state_old) / (np.abs(current_state) + 1.e-4))
extinguished = maxT < (np.max([flamelet.oxy_stream.T, flamelet.fuel_stream.T]) + 10.)
if (extinguished and (not extinguished_first)) and refine_before_extinction:
extinguished_first = True
extinguished = False
hval -= dh
dh *= 0.1
diff_target *= 0.1
current_state = state_old.copy()
continue
state_old = np.copy(current_state)
dh *= np.min([np.max([np.sqrt(diff_target / diff_norm), 0.1]), 2.])
hvalues.append(hval)
solutions.append(dict())
for p in g_library.props:
solutions[-1][p] = g_library[p].ravel()
z_dim = Dimension(_mixture_fraction_name, flamelet.mixfrac_grid)
h_dim = Dimension(_enthalpy_defect_name + _stoich_suffix, np.array(hvalues))
steady_lib = Library(z_dim, h_dim)
steady_lib.extra_attributes['mech_spec'] = flamelet_specs.mech_spec
for p in table_dict[chi_st]:
if p != 'adiabatic_state':
steady_lib[p] = steady_lib.get_empty_dataset()
for ig, sol in enumerate(solutions):
for p in sol:
steady_lib[p][:, ig] = sol[p].ravel()
indices = [0]
z = flamelet.mixfrac_grid
z_st = flamelet.mechanism.stoich_mixture_fraction(flamelet.fuel_stream, flamelet.oxy_stream)
h_tz = sca.compute_specific_enthalpy(flamelet_specs.mech_spec, steady_lib)['enthalpy']
h_ad = h_tz[:, 0]
nz, nt = h_tz.shape
last_hst = interp1d(z, h_ad)(z_st)
for i in range(nt - 1):
this_hst = interp1d(z, h_tz[:, i])(z_st)
if last_hst - this_hst > h_stoich_spacing:
indices.append(i)
last_hst = this_hst
for i in indices:
defect = h_tz[:, i] - h_ad
gst = float(interp1d(z, defect)(z_st))
this_data = dict()
this_data['enthalpy_defect'] = np.copy(defect)
this_data['enthalpy_cons'] = np.copy(h_ad)
this_data['enthalpy'] = np.copy(h_tz[:, i])
this_data[_mixture_fraction_name] = flamelet.mixfrac_grid
for q in steady_lib.props:
this_data[q] = steady_lib[q][:, i]
managed_dict[(chi_st, gst)] = this_data
dcput = perf_counter() - cput0000
if verbose:
print('chi_st = {:8.1e} 1/s converged in {:6.2f} s'.format(chi_st, dcput), flush=True)
def _build_unstructured_nonadiabatic_defect_slfm_library(flamelet_specs,
heat_loss_expansion='transient',
diss_rate_values=np.logspace(-3, 2, 16),
diss_rate_ref='stoichiometric',
verbose=True,
solver_verbose=False,
h_stoich_spacing=10.e3,
num_procs=1,
integration_args=None):
table_dict, z_values, x_values = build_adiabatic_slfm_library(flamelet_specs,
diss_rate_values, diss_rate_ref,
verbose, solver_verbose,
_return_intermediates=True)
if heat_loss_expansion == 'transient':
enthalpy_expansion_fxn = _expand_enthalpy_defect_dimension_transient
else:
enthalpy_expansion_fxn = _expand_enthalpy_defect_dimension_steady
if verbose:
print(f'expanding ({heat_loss_expansion}) enthalpy defect dimension ...', flush=True)
if num_procs > 1:
pool = Pool(num_procs)
manager = Manager()
nonad_table_dict = manager.dict()
cput000 = perf_counter()
pool.starmap(enthalpy_expansion_fxn,
((chi_st,
nonad_table_dict,
flamelet_specs,
table_dict,
h_stoich_spacing,
verbose,
integration_args,
solver_verbose) for chi_st in table_dict.keys()))
if verbose:
print('----------------------------------------------------------------------------------')
print('enthalpy defect dimension expanded in {:6.2f} s'.format(perf_counter() - cput000), flush=True)
print('collecting parallel data ... '.format(perf_counter() - cput000), end='', flush=True)
cput0000 = perf_counter()
serial_dict = dict()
for cg in nonad_table_dict.keys():
serial_dict[cg] = nonad_table_dict[cg]
pool.close()
pool.join()
if verbose:
print('done in {:6.2f} s'.format(perf_counter() - cput0000))
print('----------------------------------------------------------------------------------', flush=True)
return serial_dict
else:
serial_dict = dict()
cput000 = perf_counter()
for chi_st in table_dict.keys():
enthalpy_expansion_fxn(chi_st,
serial_dict,
flamelet_specs,
table_dict,
h_stoich_spacing,
verbose,
integration_args,
solver_verbose)
if verbose:
print('----------------------------------------------------------------------------------')
print('enthalpy defect dimension expanded in {:6.2f} s'.format(perf_counter() - cput000))
print('----------------------------------------------------------------------------------', flush=True)
return serial_dict
def _interpolate_to_structured_defect_dimension(unstructured_table, n_defect_stoich, verbose=False, extend=False):
cput00 = perf_counter()
min_g_st = 1.e305
max_g_st = -1.e305
chi_st_space = set()
chi_to_g_list_dict = dict()
progress_note = 10.
progress = 10.
if verbose:
print('Structuring enthalpy defect dimension ... \nInitializing ...', end='', flush=True)
for (chi_st, g_stoich) in unstructured_table.keys():
min_g_st = np.min([min_g_st, g_stoich])
max_g_st = np.max([max_g_st, g_stoich])
chi_st_space.add(chi_st)
if chi_st not in chi_to_g_list_dict:
chi_to_g_list_dict[chi_st] = set({g_stoich})
else:
chi_to_g_list_dict[chi_st].add(g_stoich)
if verbose:
print(' Done.\nInterpolating onto structured grid ... \nProgress: 0%', end='', flush=True)
defect_st_space = np.linspace(min_g_st, max_g_st, n_defect_stoich)
if extend:
defect_spacing = np.abs(defect_st_space[1] - defect_st_space[0])
times_spacing = 2
defect_st_space = np.linspace(min_g_st - times_spacing * defect_spacing, max_g_st,
n_defect_stoich + times_spacing)
for chi_st in chi_st_space:
chi_to_g_list_dict[chi_st] = list(chi_to_g_list_dict[chi_st])
chi_st_space = list(chi_st_space)
structured_table = dict()
for chi_idx, chi_st in enumerate(chi_st_space):
unstruc_g_st_space = chi_to_g_list_dict[chi_st]
unstruc_g_st_space_sorted = np.sort(unstruc_g_st_space)
table_g0 = unstructured_table[(chi_st, unstruc_g_st_space[0])]
nz = table_g0[list(table_g0.keys())[0]].size
for g_st in defect_st_space:
structured_table[(chi_st, g_st)] = dict()
for q in table_g0:
structured_table[(chi_st, g_st)][q] = np.zeros(nz)
for q in table_g0.keys():
for iz in range(nz):
unstruc_y = np.zeros_like(unstruc_g_st_space)
for i in range(len(unstruc_g_st_space)):
unstruc_y[i] = unstructured_table[(chi_st, unstruc_g_st_space_sorted[i])][q][iz]
if extend and (q == 'enthalpy' or q == 'enthalpy_defect'):
yginterp = interp1d(unstruc_g_st_space_sorted, unstruc_y, kind='linear', fill_value='extrapolate')
else:
yginterp = InterpolatedUnivariateSpline(unstruc_g_st_space_sorted, unstruc_y, k=1, ext='const')
for g_st_struc in defect_st_space:
structured_table[(chi_st, g_st_struc)][q][iz] = yginterp(g_st_struc)
if q == 'density' and structured_table[(chi_st, g_st_struc)][q][iz] < 1.e-14:
raise ValueError('density < 1.e-14 detected!')
if q == 'temperature' and structured_table[(chi_st, g_st_struc)][q][iz] < 1.e-14:
raise ValueError('temperature < 1.e-14 detected!')
if float((chi_idx + 1) / len(chi_st_space)) * 100. > progress:
if verbose:
print('--{:.0f}%'.format(progress), end='', flush=True)
progress += progress_note
if verbose:
print('--{:.0f}%'.format(100))
if verbose:
print('Structured enthalpy defect dimension built in {:6.2f} s'.format(perf_counter() - cput00), flush=True)
return structured_table, np.array(sorted(chi_st_space)), defect_st_space[::-1]
def _build_nonadiabatic_defect_slfm_library(flamelet_specs,
heat_loss_expansion='transient',
diss_rate_values=np.logspace(-3, 2, 16),
diss_rate_ref='stoichiometric',
verbose=True,
solver_verbose=False,
h_stoich_spacing=10.e3,
num_procs=1,
integration_args=None,
n_defect_st=32,
extend_defect_dim=False,
diss_rate_log_scaled=True):
if isinstance(flamelet_specs, dict):
flamelet_specs = FlameletSpec(**flamelet_specs)
m = flamelet_specs.mech_spec
fuel = flamelet_specs.fuel_stream
oxy = flamelet_specs.oxy_stream
cput00 = _write_library_header('nonadiabatic (defect) SLFM', m, fuel, oxy, verbose)
ugt = _build_unstructured_nonadiabatic_defect_slfm_library(flamelet_specs,
heat_loss_expansion,
diss_rate_values,
diss_rate_ref,
verbose,
solver_verbose,
h_stoich_spacing,
num_procs,
integration_args)
structured_defect_table, x_values, g_values = _interpolate_to_structured_defect_dimension(ugt,
n_defect_st,
verbose=verbose,
extend=extend_defect_dim)
key0 = list(structured_defect_table.keys())[0]
z_values = structured_defect_table[key0][_mixture_fraction_name]
z_dim = Dimension(_mixture_fraction_name, z_values)
x_dim = Dimension(_dissipation_rate_name + _stoich_suffix, x_values, diss_rate_log_scaled)
g_dim = Dimension(_enthalpy_defect_name + _stoich_suffix, g_values)
output_library = Library(z_dim, x_dim, g_dim)
output_library.extra_attributes['mech_spec'] = m
for quantity in structured_defect_table[key0]:
values = output_library.get_empty_dataset()
for ix, x in enumerate(x_values):
for ig, g in enumerate(g_values):
values[:, ix, ig] = structured_defect_table[(x, g)][quantity]
output_library[quantity] = values
_write_library_footer(cput00, verbose)
return output_library
def build_nonadiabatic_defect_transient_slfm_library(flamelet_specs,
diss_rate_values=np.logspace(-3, 2, 16),
diss_rate_ref='stoichiometric',
verbose=True,
solver_verbose=False,
h_stoich_spacing=10.e3,
num_procs=1,
integration_args=None,
n_defect_st=32,
extend_defect_dim=False,
diss_rate_log_scaled=True):
"""Build a flamelet library with the strained laminar flamelet model including heat loss effects through the enthalpy defect,
where heat loss profiles are generated through rapid, transient extinction (as opposed to quasisteady heat loss)
Parameters
----------
flamelet_specs : dictionary or FlameletSpec instance
data for the mechanism, streams, mixture fraction grid, etc.
diss_rate_values : np.array
reference dissipation rate values in the table (note that if the flamelet extinguishes at any point,
the extinguished flamelet and larger dissipation rates are not included in the library)
diss_rate_ref : str
the reference point of the specified dissipation rate values, either 'stoichiometric' or 'maximum'
verbose : bool
whether or not to show progress of the library construction
solver_verbose : bool
whether or not to show detailed progress of sub-solvers in generating the library
h_stoich_spacing : float
the stoichiometric enthalpy spacing used in subsampling the transient solution history of each extinction solve
n_defect_st : Int
the number of stoichiometric enthalpy defect values to include in the library
integration_args : kwargs
extra arguments to be passed to the heat loss integration call (see Flamelet.integrate)
num_procs : Int
how many processors over which to distribute the parallel extinction solves
extend_defect_dim : bool
whether or not to add a buffer layer to the enthalpy defect field to aid in library lookups
Returns
-------
library : spitfire.chemistry.library.Library instance
the structured chemistry library
"""
return _build_nonadiabatic_defect_slfm_library(flamelet_specs,
'transient',
diss_rate_values,
diss_rate_ref,
verbose,
solver_verbose,
h_stoich_spacing,
num_procs,
integration_args,
n_defect_st,
extend_defect_dim,
diss_rate_log_scaled=diss_rate_log_scaled)
def build_nonadiabatic_defect_steady_slfm_library(flamelet_specs,
diss_rate_values=np.logspace(-3, 2, 16),
diss_rate_ref='stoichiometric',
verbose=True,
solver_verbose=False,
h_stoich_spacing=10.e3,
num_procs=1,
integration_args=None,
n_defect_st=32,
extend_defect_dim=False,
diss_rate_log_scaled=True):
"""Build a flamelet library with the strained laminar flamelet model including heat loss effects through the enthalpy defect,
where heat loss profiles are generated through quasisteady extinction
Parameters
----------
flamelet_specs : dictionary or FlameletSpec instance
data for the mechanism, streams, mixture fraction grid, etc.
diss_rate_values : np.array
reference dissipation rate values in the table (note that if the flamelet extinguishes at any point,
the extinguished flamelet and larger dissipation rates are not included in the library)
diss_rate_ref : str
the reference point of the specified dissipation rate values, either 'stoichiometric' or 'maximum'
verbose : bool
whether or not to show progress of the library construction
solver_verbose : bool
whether or not to show detailed progress of sub-solvers in generating the library
h_stoich_spacing : float
the stoichiometric enthalpy spacing used in subsampling the transient solution history of each extinction solve
n_defect_st : Int
the number of stoichiometric enthalpy defect values to include in the library
integration_args : kwargs
extra arguments to be passed to the heat loss integration call (see Flamelet.integrate)
num_procs : Int
how many processors over which to distribute the parallel extinction solves
extend_defect_dim : bool
whether or not to add a buffer layer to the enthalpy defect field to aid in library lookups
Returns
-------
library : spitfire.chemistry.library.Library instance
the structured chemistry library
"""
return _build_nonadiabatic_defect_slfm_library(flamelet_specs,
'steady',
diss_rate_values,
diss_rate_ref,
verbose,
solver_verbose,
h_stoich_spacing,
num_procs,
integration_args,
n_defect_st,
extend_defect_dim,
diss_rate_log_scaled=diss_rate_log_scaled)
try:
from pytabprops import ClippedGaussMixMdl, BetaMixMdl, LagrangeInterpolant1D
def _convolve_full_property(p, managed_dict, turb_lib, lam_lib, pdf_spec):
use_scaled_variance = pdf_spec.scaled_variance_values is not None
variance_range = pdf_spec.scaled_variance_values if use_scaled_variance else pdf_spec.variance_values
prop_turb = turb_lib[p]
prop_lam = lam_lib[p]
if isinstance(pdf_spec.pdf, str):
use_pytabprops = True
pdf_obj = ClippedGaussMixMdl(201, 201, False) if pdf_spec.pdf == 'ClipGauss' else BetaMixMdl()
else:
pdf_obj = pdf_spec.pdf
use_pytabprops = isinstance(pdf_spec.pdf, ClippedGaussMixMdl) or isinstance(pdf_spec.pdf, BetaMixMdl)
for ((izm, zm), (isvm, svm)) in itertools.product(enumerate(turb_lib.dims[0].values),
enumerate(variance_range.copy())):
pdf_obj.set_mean(zm)
if use_scaled_variance:
pdf_obj.set_scaled_variance(svm)
else:
pdf_obj.set_variance(svm)
for indices in itertools.product(*[range(d.values.size) for d in turb_lib.dims[1:-1]]):
lam_ex_list = [slice(idx, idx + 1) for idx in indices]
lam_point_list = [slice(izm, izm + 1), *lam_ex_list]
lam_line_list = [slice(None), *lam_ex_list]
turb_slice = tuple(lam_point_list + [slice(isvm, isvm + 1)])
if use_pytabprops:
interp = LagrangeInterpolant1D(pdf_spec.convolution_spline_order,
turb_lib.dims[0].values,
prop_lam[tuple(lam_line_list)], True)
prop_turb[turb_slice] = pdf_obj.integrate(interp, pdf_spec.integrator_intervals)
else:
interp = interp1d(turb_lib.dims[0].values.ravel(), prop_lam[tuple(lam_line_list)].ravel(),
kind=pdf_spec.convolution_spline_order,
fill_value=(float(prop_lam[tuple(lam_line_list)][0]),
float(prop_lam[tuple(lam_line_list)][-1])),
bounds_error=False)
prop_turb[turb_slice] = pdf_obj.integrate(interp)
if managed_dict is None:
return prop_turb
else:
managed_dict[p] = prop_turb
def _extend_presumed_pdf_first_dim(lam_lib, pdf_spec, added_suffix, num_procs, verbose=False):
turb_dims = [Dimension(d.name + added_suffix, d.values, d.log_scaled) for d in lam_lib.dims]
if pdf_spec.pdf != 'delta':
turb_dims.append(Dimension(pdf_spec.variance_name,
pdf_spec.scaled_variance_values if pdf_spec.scaled_variance_values is not None else pdf_spec.variance_values,
pdf_spec.log_scaled))
turb_lib = Library(*turb_dims)
for p in lam_lib.props:
turb_lib[p] = turb_lib.get_empty_dataset()
if pdf_spec.pdf == 'delta':
turb_lib = Library(*turb_dims)
for p in lam_lib.props:
turb_lib[p] = lam_lib[p].copy()
return turb_lib
if verbose:
cput0 = perf_counter()
num_integrals = len(turb_lib.props)
for d in turb_lib.dims:
num_integrals *= d.npts
print(f'{pdf_spec.variance_name}: computing {num_integrals} integrals... ', end='', flush=True)
if num_procs == 1:
for p in turb_lib.props:
turb_lib[p] = _convolve_full_property(p, None, turb_lib, lam_lib, pdf_spec)
else:
pool = Pool(processes=num_procs)
manager = Manager()
managed_dict = manager.dict()
pool.map(partial(_convolve_full_property,
managed_dict=managed_dict,
turb_lib=turb_lib,
lam_lib=lam_lib,
pdf_spec=pdf_spec),
turb_lib.props)
for p in managed_dict:
turb_lib[p] = managed_dict[p]
pool.close()
pool.join()
if verbose:
cputf = perf_counter()
dcput = cputf - cput0
avg = float(num_integrals) / dcput
print(f'completed in {dcput:.1f} seconds, average = {int(avg)} integrals/s.')
return turb_lib
except ImportError:
pass
def require_pytabprops(method_name):
try:
from pytabprops import ClippedGaussMixMdl, BetaMixMdl, LagrangeInterpolant1D
except ImportError:
raise ModuleNotFoundError(f'{method_name} requires the pytabprops package')
def _apply_presumed_pdf_1var(library, variable_name, pdf_spec, added_suffix=_mean_suffix, num_procs=1, verbose=False):
require_pytabprops('apply_presumed_PDF_model')
index = 0
for d in library.dims:
if d.name == variable_name:
break
else:
index += 1
if index == len(library.dims):
raise KeyError(f'Invalid variable name \"{variable_name}\" for library with names {library.dim_names}')
_pdf_spec = copy.copy(pdf_spec)
if _pdf_spec.variance_name is None:
if variable_name == _mixture_fraction_name:
_pdf_spec.variance_name = _scaled_scalar_variance_name
else:
_pdf_spec.variance_name = variable_name + '_variance'
if index == 0:
library_t = _extend_presumed_pdf_first_dim(library, _pdf_spec, added_suffix, num_procs, verbose)
else:
swapped_dims = library.dims
swapped_dims[index], swapped_dims[0] = swapped_dims[0], swapped_dims[index]
swapped_lib = Library(*swapped_dims)
for p in library.props:
swapped_lib[p] = np.swapaxes(library[p], 0, index)
swapped_lib_t = _extend_presumed_pdf_first_dim(swapped_lib, _pdf_spec, added_suffix, num_procs, verbose)
swapped_lib_t_dims = copy.copy(swapped_lib_t.dims)
swapped_lib_t_dims[0], swapped_lib_t_dims[index] = swapped_lib_t_dims[index], swapped_lib_t_dims[0]
library_t = Library(*swapped_lib_t_dims)
for p in swapped_lib_t.props:
library_t[p] = np.swapaxes(swapped_lib_t[p], index, 0)
for key in library.extra_attributes:
library_t.extra_attributes[key] = copy.copy(library.extra_attributes[key])
return library_t
class PDFSpec:
def __init__(self,
pdf='delta',
scaled_variance_values=None,
variance_values=None,
convolution_spline_order=3,
integrator_intervals=100,
variance_name=None,
log_scaled=False):
"""Specification of a presumed PDF and integrator/spline details for a given single dimension in a library.
Parameters
----------
pdf : str, or custom object type
the PDF, either 'ClipGauss' or 'Beta' for TabProps methods, or any custom object that implements the
set_mean(), set_variance() or set_scaled_variance(), and integrate(scipy.interpolate.interp1d) methods.
scaled_variance_values : np.array
array of values of the scaled variance (varies between zero and one), provide this or variance_values
variance_values : np.array
array of values of the variance, provide this or scaled_variance_values
variance_name : str
the name of the variance dimension added to the output library
convolution_spline_order : Int
the order of the 1-D piecewise Lagrange reconstruction used in the convolution integrals, default is 3 (cubic)
integrator_intervals : Int
extra parameter provided to TabProps integrators, default 100
variance_name : str
the name of the variance dimension to be added, by default Spitfire will add "_variance" to the name
of the dimension being convolved, or use "scaled_scalar_variance_mean" for "mixture_fraction"
log_scaled : bool
whether or not the dimension is populated with log-scaled values, default False
"""
require_pytabprops('PDFSpec')
self.pdf = pdf
self.scaled_variance_values = scaled_variance_values
self.variance_values = variance_values
self.convolution_spline_order = convolution_spline_order
self.integrator_intervals = integrator_intervals
self.variance_name = variance_name
self.log_scaled = log_scaled
def apply_mixing_model(library, mixing_spec, added_suffix=_mean_suffix, num_procs=1, verbose=False):
"""Take an existing tabulated chemistry library and incorporate subgrid variation in each reaction variable with a
presumed PDF model. This requires statistical independence of the reaction variables. If a reaction variable
is not included in the mixing_spec dictionary, a delta PDF is presumed for it.
Parameters
----------
library : spitfire.Library
an existing library from a reaction model
mixing_spec : str
a dictionary mapping reaction variable names to PDFSpec objects that describe the variable's presumed PDF
added_suffix : str
string to add to each name, for instance '_mean' if this is the first PDF convolution, or '' if a successive convolution
num_procs : Int
how many processors over which to distribute the parallel extinction solves
verbose : bool
whether or not (default False) to print information about the PDF convolution
Returns
-------
library : spitfire.Library instance
the library with any nontrivial variance dimensions added
"""
require_pytabprops('apply_mixing_model')
for dim in mixing_spec:
if dim not in library.dim_names:
raise KeyError(f'Invalid variable name \"{dim}\" for library with names {library.dim_names}')
mixing_spec = copy.copy(mixing_spec)
for dim in library.dims:
if dim.name not in mixing_spec:
mixing_spec[dim.name] = 'delta'
for dim in mixing_spec:
if mixing_spec[dim] == 'delta':
mixing_spec[dim] = PDFSpec('delta', variance_values=np.array([0.]))
for dim in mixing_spec:
if (mixing_spec[dim].variance_values is None and
mixing_spec[dim].scaled_variance_values is None and
mixing_spec[dim].pdf == 'delta'):
mixing_spec[dim] = PDFSpec('delta', variance_values=np.array([0.]))
extensions = []
for i, key in enumerate(mixing_spec):
extensions.append({'variable_name': key,
'pdf_spec': mixing_spec[key],
'num_procs': num_procs,
'verbose': verbose})
def get_size(element):
pdfspec = element['pdf_spec']
if pdfspec.pdf == 'delta':
return 0
else:
if pdfspec.variance_values is not None:
return pdfspec.variance_values.size
else:
return pdfspec.scaled_variance_values.size
extensions = sorted(extensions, key=lambda element: get_size(element))
turb_lib = Library.copy(library)
for i, ext in enumerate(extensions):
ext['library'] = turb_lib
ext['added_suffix'] = '' if i < len(extensions) - 1 else added_suffix
turb_lib = _apply_presumed_pdf_1var(**ext)
if get_size(ext) == 1 and ext['pdf_spec'].pdf != 'delta':
turb_lib = Library.squeeze(turb_lib[tuple([slice(None)] * (len(turb_lib.dims) - 1) + [slice(0, 1)])])
if 'mixing_spec' in turb_lib.extra_attributes:
turb_lib.extra_attributes['mixing_spec'].update(mixing_spec)
else:
turb_lib.extra_attributes['mixing_spec'] = mixing_spec
return turb_lib
<file_sep>import unittest
from os.path import join, abspath
import os
from numpy.testing import assert_allclose
from tests.tabulation.adiabatic_equilibrium.rebless import run
from spitfire.chemistry.library import Library
import spitfire.chemistry.analysis as sca
from spitfire.chemistry.ctversion import check as cantera_version_check
if cantera_version_check('atleast', 2, 5, None):
tol_args = {'atol': 1e-14} if cantera_version_check('pre', 2, 6, None) else {'atol': 1e-7, 'rtol': 3e-3}
class Test(unittest.TestCase):
def test(self):
output_library = run()
gold_file = abspath(join('tests',
'tabulation',
'adiabatic_equilibrium',
'gold.pkl'))
gold_library = Library.load_from_file(gold_file)
for prop in gold_library.props:
self.assertIsNone(assert_allclose(gold_library[prop], output_library[prop], **tol_args))
if os.path.isfile('testlib.pkl'):
os.remove('testlib.pkl')
output_library.save_to_file('testlib.pkl')
l = Library.load_from_file('testlib.pkl')
m = l.extra_attributes['mech_spec']
l = sca.compute_specific_enthalpy(m, l)
l = sca.compute_isochoric_specific_heat(m, l)
l = sca.compute_isobaric_specific_heat(m, l)
l = sca.compute_density(m, l)
l = sca.compute_pressure(m, l)
l = sca.compute_viscosity(m, l)
for prop in gold_library.props:
self.assertIsNone(assert_allclose(gold_library[prop], l[prop], **tol_args))
os.remove('testlib.pkl')
if __name__ == '__main__':
unittest.main()
| 5f247d94e59c0ae0527513f981be3cd955d5b0ea | [
"Markdown",
"Python",
"C++",
"reStructuredText"
] | 83 | C++ | sandialabs/Spitfire | 10bd4cdde2f6b9f5a0ca0365c8f7d11e25d313c8 | c6ecc3f035914be2192d15695d441a09d8216b36 |
refs/heads/master | <repo_name>qiuyi116/csu_forum<file_sep>/csu_forum/urls.py
from django.conf.urls import patterns, include, url
# from django.contrib import admin
from csu_forum.views import test
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'csu_forum.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^test/$', test)
# url(r'^admin/', include(admin.site.urls)),
)
<file_sep>/csu_forum/views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
import datetime
def test(request):
now = datetime.datetime.now()
return render_to_response("test.html", {'current_date': now})
<file_sep>/storage/models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
password = models.CharField(max_length=30)
# some problem with password
time = models.DateField(auto_now_add=True)
icon = models.ImageField()
class Comment(models.Model):
content = models.CharField(max_length=500)
time = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User)
class Article(models.Model):
title = models.CharField(max_length=50)
content = models.CharField(max_length=500) ## ok?
comment = models.ManyToManyField(Comment)
label = models.CharField(max_length=20)
time = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User)
| 66ff6c4f5237e7274a28fff22d4adfd0ea49e98c | [
"Python"
] | 3 | Python | qiuyi116/csu_forum | d8cc2691e17064486941b99966ec32f4b6df6937 | ab68aabad60222d33a9e6c9de7a1ae29445e6bb0 |
refs/heads/master | <repo_name>grant-king/infinite-monkey-text<file_sep>/README.md
# Exercises
[](https://mybinder.org/v2/gh/grant-king/exercises/master)
Collection of Jupyter notebooks containing various exercises:
## Music_library.ipynb -
Notebook OOP analysis and design exercise to create the objects of a music library
## inf_monkey.ipynb -
Notebook exploration of randomly generated text and tts
## babble.py -
Script containing tts portions of inf_monkey to convert a text file into an .mp3
## serial_analysis.ipynb -
Notebook exploring how to analyze randomly sampled serial numbers in order to determine total production quantity
<file_sep>/babble.py
#Uses functions from inf_monkey with added code to save random words to mp3
#clearly there are better ways to generate random words
import random
def generate_string(length):
"""return a string of 'length' random characters, including space"""
alphabet = list('abcdefghijklmnopqrstuvwxyz ')
string = ""
for it in range(length):
string = string + random.choice(alphabet)
return string
def score(goal, test_string):
"""compare two input strings and return decimal value of quotient likeness"""
#goal = 'methinks it is like a weasel'
num_equal = 0
for i in range(len(goal)):
if goal[i] == test_string[i]:
num_equal += 1
return num_equal / len(goal)
def find_words(strings, min_length):
"""find all english words in input list that meet or exceed min_length"""
lower_words = generate_wordlist()
made_words = []
for string_item in strings:
#break each string into individual literals, stored in clump_list
clump_list = string_item.split()
for str_literal in clump_list:
#add literal to made_words list if it is an english word and >= min_length
if str_literal.lower() in lower_words and len(str_literal) >= min_length:
made_words.append(str_literal)
return made_words
def generate_wordlist():
"""generate and return set of all english words for fast searching"""
#must first download nltk data using nltk.download() copy to terminal
#the very first run to open gui to download required corpus for this function
#located under the corpus tab, 'words' needs to be dl'd
#import nltk
#nltk.download()
from nltk.corpus import words
#list of all english words
word_list = words.words()
#put lowercased words into a set for fast searching
return set(word.strip().lower() for word in word_list)
#create an n-member list consisting of lists nn-members long of random strings,
#28 characters each as specified by generate_string()
nn = 100000
n = 10
monkey_strings = [[generate_string(20) for i in range(nn)] for i in range(n)]
text = ['Each of the following',
'lists are the english words found among lists of',
'randomly generated', 'character strings.', 'Example string:']
print(text[0], len(monkey_strings), text[1], len(monkey_strings[0]), text[2], len(monkey_strings[0][0]), text[3])
print(text[4], monkey_strings[0][0])
#save tts version of generated words
from gtts import gTTS
long_string = ''
for string_list in monkey_strings:
for each_word in find_words(string_list, 5):
long_string = long_string + each_word + " "
print(long_string)
tts = gTTS(long_string)
tts.save('babble.mp3')
| af8e2414ee52b71182bfe61d0651dc6d3fb02243 | [
"Markdown",
"Python"
] | 2 | Markdown | grant-king/infinite-monkey-text | 31052cdcee9788e62d91f8ed6e3c5476d76e6f5c | 0fc9af32c2ecb5607e61779fed4b768fcc11304e |
refs/heads/master | <repo_name>full-coder/prettytable4j<file_sep>/src/test/java/com/sarojaba/prettytable4j/converter/GfmConverterTest.java
package com.sarojaba.prettytable4j.converter;
import com.sarojaba.prettytable4j.PrettyTable;
import com.sarojaba.prettytable4j.converter.GfmConverter;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class GfmConverterTest {
@Test
public void markdown() {
PrettyTable pt = PrettyTable
.fieldNames("name", "age", "city")
.addRow("john", 22, "new york")
.addRow("elizabeth", 43, "chicago")
.addRow("bill", 31, "atlanta")
.addRow("mary", 18, "los angeles")
.converter(new GfmConverter());
assertEquals(
"| name | age | city |\n" +
"| --- | --- | --- |\n" +
"| john | 22 | new york |\n" +
"| elizabeth | 43 | chicago |\n" +
"| bill | 31 | atlanta |\n" +
"| mary | 18 | los angeles |", pt.toString());
}
}
<file_sep>/README.md
# PrettyTable4J
PrettyTable4J is a CLI based library for printing tables on the console.
This project is inspired from the Python `prettytable` module.
## Features
- Simple and easy to use
- Support parsers
- JSON
- Support multiple converters
- Console
- GitHub Flavored Markdown
- HTML Table
## How to Install
### Using Maven
Add the JitPack repository to your Maven or Gradle build file.
And add the dependency.
```xml
<project>
...
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.github.sarojaba</groupId>
<artifactId>prettytable4j</artifactId>
<version>662a2fb</version>
</dependency>
</dependencies>
</project>
```
### Using Gradle
```groovy
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
compile 'com.github.sarojaba:prettytable4j:662a2fb'
}
```
## Basic Usage
```java
PrettyTable pt = PrettyTable
.fieldNames("name", "age", "city")
.addRow("john", 22, "new york")
.addRow("elizabeth", 43, "chicago")
.addRow("bill", 31, "atlanta")
.addRow("mary", 18, "los angeles");
System.out.println(pt);
```
```
+-----------+-----+-------------+
| name | age | city |
+-----------+-----+-------------+
| john | 22 | new york |
| elizabeth | 43 | chicago |
| bill | 31 | atlanta |
| mary | 18 | los angeles |
+-----------+-----+-------------+
```
## Sorting Table by Column
```java
pt.sortTable("age")
System.out.println(pt);
```
```
+-----------+-----+-------------+
| name | age | city |
+-----------+-----+-------------+
| mary | 18 | los angeles |
| john | 22 | new york |
| bill | 31 | atlanta |
| elizabeth | 43 | chicago |
+-----------+-----+-------------+
```
Also, PrettyTable4J support to sort in descending order.
```java
pt.sortTable("age", true);
System.out.println(pt);
```
```
+-----------+-----+-------------+
| name | age | city |
+-----------+-----+-------------+
| elizabeth | 43 | chicago |
| bill | 31 | atlanta |
| john | 22 | new york |
| mary | 18 | los angeles |
+-----------+-----+-------------+
```
## Deleting Data
```java
pt.deleteRow(2).deleteRow(1);
System.out.println(pt);
```
```
+------+-----+-------------+
| name | age | city |
+------+-----+-------------+
| bill | 31 | atlanta |
| mary | 18 | los angeles |
+------+-----+-------------+
```
## Decimal mark
```java
PrettyTable pt = PrettyTable
.fieldNames("City name", "Area", "Population", "ann")
.addRow("Adelaide",1295, 1158259, 600.5)
.addRow("Brisbane",5905, 1857594, 1146.4)
.addRow("Darwin", 112, 120900, 1714.7)
.addRow("Hobart", 1357, 205556, 619.5)
.addRow("Sydney", 2058, 4336374, 1214.8)
.addRow("Melbourne", 1566, 3806092, 646.9)
.addRow("Perth", 5386, 1554769, 869.4)
.comma(true);
System.out.println(pt)
```
```
+-----------+-------+------------+---------+
| City name | Area | Population | ann |
+-----------+-------+------------+---------+
| Adelaide | 1,295 | 1,158,259 | 600.5 |
| Brisbane | 5,905 | 1,857,594 | 1,146.4 |
| Darwin | 112 | 120,900 | 1,714.7 |
| Hobart | 1,357 | 205,556 | 619.5 |
| Sydney | 2,058 | 4,336,374 | 1,214.8 |
| Melbourne | 1,566 | 3,806,092 | 646.9 |
| Perth | 5,386 | 1,554,769 | 869.4 |
+-----------+-------+------------+---------+
```
## Hide border
```java
PrettyTable pt = PrettyTable
.fieldNames("name", "age", "city")
.addRow("john", 22, "new york")
.addRow("elizabeth", 43, "chicago")
.addRow("bill", 31, "atlanta")
.addRow("mary", 18, "los angeles")
.border(false);
System.out.println(pt);
```
```
name age city
john 22 new york
elizabeth 43 chicago
bill 31 atlanta
mary 18 los angeles
```
## JSON Object
```java
PrettyTable pt = Parser.parseJson(
"{\n" +
" \"name\": \"john\",\n" +
" \"age\": 22,\n" +
" \"city\": \"new york\"\n" +
"}");
System.out.println(pt);
```
```
+------+----------+
| Name | Value |
+------+----------+
| name | john |
| age | 22 |
| city | new york |
+------+----------+
```
## JSON Array
```java
PrettyTable pt = PrettyTable
.parser(new JsonParser())
.fromString(
"[{\n" +
" \"name\": \"john\",\n" +
" \"age\": 22,\n" +
" \"city\": \"new york\"\n" +
"},{" +
" \"name\": \"elizabeth\",\n" +
" \"age\": 43,\n" +
" \"city\": \"chicago\"\n" +
"}]");
System.out.println(pt);
```
```
+-----------+-----+----------+
| name | age | city |
+-----------+-----+----------+
| john | 22 | new york |
| elizabeth | 43 | chicago |
+-----------+-----+----------+
```
## GitHub Flavored Markdown
```java
PrettyTable pt = PrettyTable
.fieldNames("name", "age", "city")
.addRow("john", 22, "new york")
.addRow("elizabeth", 43, "chicago")
.addRow("bill", 31, "atlanta")
.addRow("mary", 18, "los angeles")
.converter(new GfmConverter());
System.out.println(pt);
```
```
| name | age | city |
| --- | --- | --- |
| john | 22 | new york |
| elizabeth | 43 | chicago |
| bill | 31 | atlanta |
| mary | 18 | los angeles |
```
## HTML
```java
PrettyTable pt = PrettyTable
.fieldNames("name", "age", "city")
.addRow("john", 22, "new york")
.addRow("elizabeth", 43, "chicago")
.addRow("bill", 31, "atlanta")
.addRow("mary", 18, "los angeles")
.converter(new HtmlConverter());
```
```html
<table>
<tr>
<th>name</th>
<th>age</th>
<th>city</th>
</tr>
<tr>
<td>john</td>
<td>22</td>
<td>new york</td>
</tr>
<tr>
<td>elizabeth</td>
<td>43</td>
<td>chicago</td>
</tr>
<tr>
<td>bill</td>
<td>31</td>
<td>atlanta</td>
</tr>
<tr>
<td>mary</td>
<td>18</td>
<td>los angeles</td>
</tr>
</table>
```<file_sep>/src/main/java/com/sarojaba/prettytable4j/Bordered.java
package com.sarojaba.prettytable4j;
public interface Bordered {
Converter border(boolean border);
}
<file_sep>/src/main/java/com/sarojaba/prettytable4j/package-info.java
/**
* prettytable4j.
*/
package com.sarojaba.prettytable4j;
<file_sep>/src/main/java/com/sarojaba/prettytable4j/Converter.java
package com.sarojaba.prettytable4j;
public interface Converter {
String convert(PrettyTable pt);
}
<file_sep>/src/main/java/com/sarojaba/prettytable4j/Colored.java
package com.sarojaba.prettytable4j;
public interface Colored {
Colored fontColor(final String colorName);
Colored borderColor(final String colorName);
}
<file_sep>/src/test/java/com/sarojaba/prettytable4j/parser/JsonParserTest.java
package com.sarojaba.prettytable4j.parser;
import com.sarojaba.prettytable4j.PrettyTable;
import com.sarojaba.prettytable4j.parser.JsonParser;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class JsonParserTest {
@Test
public void testEmptyObject() {
try {
PrettyTable pt = PrettyTable
.parser(new JsonParser())
.fromString("{}");
assertEquals(
"+------+-------+\n" +
"| Name | Value |\n" +
"+------+-------+\n" +
"+------+-------+", pt.toString());
} catch (IOException e) {
fail();
}
}
@Test
public void testEmptyArray() {
try {
PrettyTable pt = PrettyTable
.parser(new JsonParser())
.fromString("[]");
assertEquals("", pt.toString());
} catch (IOException e) {
fail();
}
}
@Test
public void testEmptyObjectInArray() {
try {
PrettyTable pt = PrettyTable
.parser(new JsonParser())
.fromString("[{}]");
assertEquals("", pt.toString());
} catch (IOException e) {
fail();
}
}
@Test
public void testObject() {
try {
PrettyTable pt = PrettyTable
.parser(new JsonParser())
.fromString(
"{\n" +
" \"name\": \"john\",\n" +
" \"age\": 22,\n" +
" \"city\": \"new york\"\n" +
"}");
assertEquals(
"+------+----------+\n" +
"| Name | Value |\n" +
"+------+----------+\n" +
"| name | john |\n" +
"| age | 22 |\n" +
"| city | new york |\n" +
"+------+----------+", pt.toString());
} catch (IOException e) {
fail();
}
}
@Test
public void testFloat() {
try {
PrettyTable pt = PrettyTable
.parser(new JsonParser())
.fromString(
"{\n" +
" \"City name\": \"Adelaide\",\n" +
" \"Area\": 1295,\n" +
" \"Population\": 1158259,\n" +
" \"ann\": 600.5\n" +
"}");
assertEquals(
"+------------+----------+\n" +
"| Name | Value |\n" +
"+------------+----------+\n" +
"| City name | Adelaide |\n" +
"| Area | 1295 |\n" +
"| Population | 1158259 |\n" +
"| ann | 600.5 |\n" +
"+------------+----------+", pt.toString());
} catch (IOException e) {
fail();
}
}
@Test
public void testArray() {
try {
PrettyTable pt = PrettyTable
.parser(new JsonParser())
.fromString(
"[{\n" +
" \"name\": \"john\",\n" +
" \"age\": 22,\n" +
" \"city\": \"new york\"\n" +
"},{" +
" \"name\": \"elizabeth\",\n" +
" \"age\": 43,\n" +
" \"city\": \"chicago\"\n" +
"}]");
assertEquals(
"+-----------+-----+----------+\n" +
"| name | age | city |\n" +
"+-----------+-----+----------+\n" +
"| john | 22 | new york |\n" +
"| elizabeth | 43 | chicago |\n" +
"+-----------+-----+----------+", pt.toString());
} catch (IOException e) {
fail();
}
}
@Test
public void testComma() {
try {
PrettyTable pt = PrettyTable
.parser(new JsonParser())
.fromString(
"{\n" +
" \"City name\": \"Adelaide\",\n" +
" \"Area\": 1295,\n" +
" \"Population\": 1158259,\n" +
" \"ann\": 600.5\n" +
"}")
.comma(true);
assertEquals(
"+------------+-----------+\n" +
"| Name | Value |\n" +
"+------------+-----------+\n" +
"| City name | Adelaide |\n" +
"| Area | 1,295 |\n" +
"| Population | 1,158,259 |\n" +
"| ann | 600.5 |\n" +
"+------------+-----------+", pt.toString());
} catch (IOException e) {
fail();
}
}
}
| f805541d8cafbefb6e9488575071fc04c2721069 | [
"Markdown",
"Java"
] | 7 | Java | full-coder/prettytable4j | 811ca23b94d48173d2bc77009912a4dcfb765d2e | b512f92514c4eddf5a024f6daafb0afd8db64882 |
refs/heads/master | <file_sep># Media files ingestion feeds for testing
## Metadata extraction feed
Feed for extracting metadata, saving the media content in HDFS and exporting to JSON files
File: `feeds/extract_metadata_from_my_pdfs.feed.zip`
Input data: `/opt/nifi/metadata_extract_in`
Output data: `/opt/nifi/metadata_extract_out`
Installation:
- Run `./setup_resources.sh` to prepare the input folders + clean HDFS/output folder
- In kylo UI -> add feed -> import feed from file -> select file
### Ingest feed
Feed for ingesting metadata JSON files into Hive tables.
File: `put_my_pdf_meta_in_hive.feed.zip`
Sample file for schema : `samples/pdf_json/21713737247670`
Input data: `/opt/nifi/metadata_extract_out`
Output data: `$category.$feedName` Hive table + `/media_content` HDFS
Installation:
- In Kylo UI -> add feed -> import feed from file -> select file<file_sep>#!/bin/bash
# This setup is used to test the media files metadata extraction and integration flow.
DIR_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Cleaning the present media resources
rm -rf /opt/nifi/metadata_extract_*
hdfs dfs -rm -r /media_content
# Media resources go in metadata_extract_in to have the metadata extracted with the Media Ingestion template
cp -r ${DIR_PATH}/resources /opt/nifi/metadata_extract_in
chown -R nifi:users /opt/nifi/metadata_extract_in
<file_sep># Ingestion and indexing of media files metadata and content
## Kibana installation
User may follow this [tutorial](https://www.digitalocean.com/community/tutorials/how-to-install-elasticsearch-logstash-and-kibana-elk-stack-on-centos-7#install-kibana) following Kibana and Nginx chapter.
## Media files ingestion
Please see this [readme](templates/media_ingestion/README.md)
<file_sep># Media files ingestion
## Description
The flow enables users to extract metadata from media files (pdf/images/word/video/ etc), and to ingest them into Hive tables, with/without the content.
The flow is:
- create a feed using "Media Ingest" template to extract the metadata +/- content and save the results as JSON files. (the content can be saved in several ways. Check below)
- create a feed using standard "Data Ingest" template to load the media file metadata +/- content into Hive
## Templates
### Media metadata extraction reusable template
Reusable template to extract metadata from a media file, and export the result in JSON format. It will also try to merge from several files, to generate fewer big files to be ingested.
File: `media-metadata-extraction.xml`
The content can be:
- saved in the file
- saved in HDFS
- don't save
Installation:
- In Kylo UI -> import template from file -> select file and select reusable + overwrite.
### Media metadata extraction for the feed template
File feed template.
File `Media_Metadata_Extraction.xml`
Installation:
- In Kylo UI -> import template from Nifi environment -> select fields. ** UNSELECT SKIP HEADER or you will lose the first row from the JSON file**
For the save content setting, you can give the following selectable options (or have a hardcoded default):
- "In file"
- "In HDFS"
- "Don't save"
### Testing with feeds
Check [the test doc](../../test/media_extraction/README.md) | 03546f529a42efd3b4156eb4d7b4004725ad067f | [
"Markdown",
"Shell"
] | 4 | Markdown | abourakba/es_ingestion_meta_doc | b6a65a3fc279876061baa8edf5d6bb36fe859cf5 | 1a998be164338e7c923f1c9a7b98119d98365c8a |
refs/heads/master | <repo_name>aporthos974/animalove974<file_sep>/announcement/lost.go
package announcement
import (
"encoding/base64"
"encoding/json"
"errors"
"github.com/gorilla/mux"
"html/template"
"labix.org/v2/mgo/bson"
"log"
"net/http"
"regexp"
"reunion/cache"
"reunion/configuration"
"reunion/websocket"
"strconv"
"strings"
)
const MAX_RESULT = 300
var ANNOUNCEMENT_TYPE = []string{"perdu", "errant", "adopter"}
func GetAnnouncementPage(writer http.ResponseWriter, request *http.Request) {
announcementId := mux.Vars(request)["announcementId"]
if announcementId == "" {
writer.WriteHeader(http.StatusBadRequest)
return
}
tmpl, page := GetOnlyAnouncementPage(announcementId)
writer.Header().Set("Cache-control", "public, max-age=3600")
error := tmpl.Execute(writer, page)
if error != nil {
log.Panicf("Erreur lors de la construction du template : %s", error.Error())
}
}
func GetOnlyAnouncementPage(id string) (tmpl *template.Template, page Page) {
announcement := FindById(id)
tmpl = template.Must(template.New("base").Delims("[[", "]]").ParseFiles(configuration.Conf.GetFilePath("static/html/location.html"), configuration.Conf.GetFilePath("static/html/contact.html"), configuration.Conf.GetFilePath("static/html/auth.html"), configuration.Conf.GetFilePath("static/html/result.html"), configuration.Conf.GetFilePath("static/html/announcement.html"), configuration.Conf.GetFilePath("static/html/base.html")))
page = Page{name: "annonce", Title: "AnimaLove - " + announcement.Description, Description: getMetaDescription(announcement), Image: announcement.GetImageLink(), Link: announcement.GetLink()}
return tmpl, page
}
func getMetaDescription(announcement Announcement) string {
return "Animal perdu - " + announcement.Description + "\n" + announcement.GetLink()
}
func GetAnimalPicture(writer http.ResponseWriter, request *http.Request) {
id := request.URL.Query().Get("id")
if id == "" {
log.Printf("Erreur id manquant")
writer.WriteHeader(http.StatusBadRequest)
writer.Write([]byte("id manquant"))
return
}
pictureContent := FindById(id).Picture
compile := regexp.MustCompile("data:(image/.+);.*$")
contentType := compile.FindStringSubmatch(pictureContent)[1]
content, err := base64.StdEncoding.DecodeString(strings.Replace(pictureContent, "data:"+contentType+";base64,", "", 1))
if err != nil {
log.Panicf("Erreur lors du décodage de l'image : %s", err.Error())
}
writer.Header().Add("Content-Type", contentType)
writer.Write(content)
}
func GetAnnouncementsPage(writer http.ResponseWriter, request *http.Request) {
GetLostTemplatePage(writer, request, "AnimaLove - Liste des animaux perdus à la Réunion", "loss_announcement", "Liste des chiens et chats perdus, errants et à adopter à la Réunion. Catégorisation des animaux.")
}
func GetLostFormPage(writer http.ResponseWriter, request *http.Request) {
GetLostTemplatePage(writer, request, "AnimaLove - Signaler un animal perdu ou trouvé à la Réunion", "create_loss_announcement", "Formulaire de signalement d'un chien ou un chat perdu. Ce formulaire permet de décrire l'animal et d'indiquer le lieux où il a été vu pour la dernière fois.")
}
func GetLostTemplatePage(writer http.ResponseWriter, request *http.Request, title string, htmlFilename string, description string) {
tmpl := template.Must(template.New("base").Delims("[[", "]]").ParseFiles(configuration.Conf.GetFilePath("static/html/location.html"), configuration.Conf.GetFilePath("static/html/contact.html"), configuration.Conf.GetFilePath("static/html/auth.html"), configuration.Conf.GetFilePath("static/html/result.html"), configuration.Conf.GetFilePath("static/html/search.html"), configuration.Conf.GetFilePath("static/html/"+htmlFilename+".html"), configuration.Conf.GetFilePath("static/html/base.html")))
page := Page{name: "Animal perdu", Title: title, Description: description, Image: "/static/images/logo.png", Link: configuration.Conf.GetUrl()}
writer.Header().Set("Cache-control", "public, max-age=3600")
error := tmpl.Execute(writer, page)
if error != nil {
log.Panicf("Erreur lors de la construction du template : %s", error.Error())
}
}
func GetLostActionHandler(writer http.ResponseWriter, request *http.Request) {
requestToken := request.Header.Get("Authorization")
id := bson.ObjectIdHex(mux.Vars(request)["announcementId"])
if action := request.URL.Query().Get("action"); action != "" {
if CheckTokenOnAnnouncement(id, requestToken) {
UpdateState(id, action)
} else {
log.Printf("Erreur dans la vérification du token : %s, les tokens ne correspondent pas", requestToken)
writer.WriteHeader(http.StatusForbidden)
writer.Write([]byte("Erreur lors de l'identification"))
return
}
} else {
log.Printf("Paramètre manquant : %s", request.URL.RequestURI())
writer.WriteHeader(http.StatusBadRequest)
}
}
func getId(uri string, idValueIndex int) (id bson.ObjectId, err error) {
splittedUri := strings.Split(uri, "/")
if len(splittedUri) > idValueIndex {
endUri := strings.Split(splittedUri[idValueIndex], "?")
id = bson.ObjectIdHex(endUri[0])
return id, nil
}
err = errors.New("Pas d'identifiant dans l'URL")
return id, err
}
func GetLocationsHandler(writer http.ResponseWriter, request *http.Request) {
var announcement Announcement
err := json.NewDecoder(request.Body).Decode(&announcement)
if err != nil {
log.Panicf("Erreur lors de la reconversion JSON : %s", err.Error())
}
AddLocation(announcement)
writer.WriteHeader(http.StatusOK)
}
func GetAllHandler(writer http.ResponseWriter, request *http.Request) {
if request.Method == "GET" {
announcements := GetAll(1, 1000, request.URL.Query().Get("state"))
jsonAnnouncements, err := json.Marshal(announcements)
if err != nil {
log.Panicf("Erreur lors de la conversion JSON : %s", err.Error())
}
writer.Write(jsonAnnouncements)
} else {
log.Printf("Opération non autorisée : %s", request.Method)
writer.WriteHeader(http.StatusMethodNotAllowed)
}
}
func GetAnnouncementsHandler(writer http.ResponseWriter, request *http.Request) {
typeAnnouncement := mux.Vars(request)["announcementType"]
if !validateAnnouncementType(typeAnnouncement) {
log.Panicf("Type incorrect : %s", typeAnnouncement)
}
var announcements []Announcement
var total int
offset, limit := findAndValidateLimit(request)
if queryParam := request.URL.Query().Get("criteria"); queryParam != "" {
announcements, total = Find(queryParam, offset, limit)
} else if city := request.URL.Query().Get("city"); city != "" {
announcements, total = FindByCity(city, offset, limit)
} else if id := request.URL.Query().Get("id"); id != "" {
announcements = append(announcements, FindById(id))
} else {
announcements, total = GetAnnouncementsByType(typeAnnouncement, offset, limit)
}
jsonAnnouncements, err := json.Marshal(map[string]interface{}{"announcements": announcements, "total": total})
if err != nil {
log.Panicf("Erreur lors de la conversion JSON : %s", err.Error())
}
cache.AddHttpCacheContent(writer, request, jsonAnnouncements)
}
func CreateAnnouncementsHandler(writer http.ResponseWriter, request *http.Request) {
typeAnnouncement := mux.Vars(request)["announcementType"]
if !validateAnnouncementType(typeAnnouncement) {
log.Panicf("Type incorrect : %s", typeAnnouncement)
}
var announcement Announcement
err := json.NewDecoder(request.Body).Decode(&announcement)
if err != nil {
log.Panicf("Erreur lors de la reconversion JSON : %s", err.Error())
}
if announcement.Locations[0] == nil {
announcement.Locations = []*Location{}
}
Create(&announcement)
notifySeenCreated(writer, request, announcement)
writer.WriteHeader(http.StatusCreated)
}
func notifySeenCreated(writer http.ResponseWriter, request *http.Request, announcement Announcement) {
if announcement.Type == "seen" {
websocket.SendNotification(writer, request, map[string]interface{}{"action": "seen-created", "announcement": announcement})
}
}
func validateAnnouncementType(typeAnnouncement string) bool {
if typeAnnouncement == "" {
return true
}
for _, value := range ANNOUNCEMENT_TYPE {
if value == typeAnnouncement {
return true
}
}
return false
}
func findAndValidateLimit(request *http.Request) (int, int) {
offsetParam := request.URL.Query().Get("offset")
limitParam := request.URL.Query().Get("limit")
if offsetParam == "" || limitParam == "" {
log.Panicf("Paramètre manquant limit ou offset")
}
limit := convertToInt(limitParam)
if limit > MAX_RESULT {
limit = MAX_RESULT
}
offset := convertToInt(offsetParam)
return offset, limit
}
func convertToInt(value string) int {
intValue, err := strconv.Atoi(value)
if err != nil {
log.Panicf("Erreur lors de la conversion en entier : %s", err.Error())
}
return intValue
}
<file_sep>/token/token_test.go
package token
import (
"github.com/stretchr/testify/assert"
"reunion/configuration"
"testing"
)
func TestCreateToken(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
token := Create("")
assert.NotEmpty(test, token)
}
func TestVerifyToken(test *testing.T) {
token := Create("")
valid := Verify(token)
assert.True(test, valid)
}
func TestVerifyMandatoryClaimsToken(test *testing.T) {
token := Create("user_authentication")
valid := Verify(token)
assert.True(test, valid)
}
func TestVerifyInvalidToken(test *testing.T) {
expiredToken := "<KEY>"
invalid := Verify(expiredToken)
assert.False(test, invalid)
}
<file_sep>/cache/cache_test.go
package cache
import (
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
)
func TestAddMaxAgeInHttpResponse(test *testing.T) {
writer := httptest.NewRecorder()
addCacheHeader(writer, CacheHeader{MaxAge: 600}, nil)
assert.Equal(test, "max-age=600", writer.Header().Get("Cache-Control"))
}
func TestAddETagInHttpResponse(test *testing.T) {
writer := httptest.NewRecorder()
responseContent := []byte("{ toto: 'fait du vélo'}")
eTag := addCacheHeader(writer, CacheHeader{MaxAge: 600}, responseContent)
assert.Equal(test, "4804f7dad78e1d3487651eb471fdc8f1", writer.Header().Get("ETag"))
assert.Equal(test, "4804f7dad78e1d3487651eb471fdc8f1", eTag)
}
func TestCheckRequestETagIsTheSame(test *testing.T) {
request := &http.Request{Header: http.Header{}}
request.Header.Add("If-None-Match", "4804f7dad78e1d3487651eb471fdc8f1")
isTheSame := checkETag(request, "4804f7dad78e1d3487651eb471fdc8f1")
assert.True(test, isTheSame)
}
func TestCheckRequestETagIsNotTheSame(test *testing.T) {
request := &http.Request{Header: http.Header{}}
request.Header.Add("If-None-Match", "4804f7dad78e1d3487651eb471fdc8f2")
isTheSame := checkETag(request, "4804f7dad78e1d3487651eb471fdc8f1")
assert.False(test, isTheSame)
}
<file_sep>/announcement/lost_test.go
package announcement
import (
"github.com/stretchr/testify/assert"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"reunion/configuration"
"testing"
"time"
)
func TestCreateLostAnnouncement(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
announcement := &Announcement{Description: "new announcement", PhoneNumber: "0606060606", Type: "seen", State: "validated", Account: &Account{}}
Create(announcement)
announcements, _ := GetAnnouncementsByType("seen", 0, 1)
assert.Equal(test, "new announcement", announcements[0].Description)
assert.Equal(test, "seen", announcements[0].Type)
}
func TestGetLostAnnouncement(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
first := Announcement{Description: "description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"}
second := Announcement{Description: "second description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"}
collection := GetAdsCollection()
collection.DropCollection()
collection.Insert(first)
collection.Insert(second)
announcements, total := GetAnnouncementsByType("lost", 0, 2)
assert.Len(test, announcements, 2)
assert.Equal(test, 2, total)
assert.Equal(test, first.Description, announcements[0].Description)
assert.Equal(test, second.Description, announcements[1].Description)
}
func TestGetAllAnnouncement(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
first := Announcement{Description: "description test", PhoneNumber: "0606060606", Type: "lost", State: "deactivated"}
second := Announcement{Description: "second description test", PhoneNumber: "0606060606", Type: "lost", State: "deleted"}
collection := GetAdsCollection()
collection.DropCollection()
collection.Insert(first)
collection.Insert(second)
announcements := GetAll(0, 2, "deleted")
assert.Len(test, announcements, 1)
assert.Equal(test, second.Description, announcements[0].Description)
assert.Equal(test, "deleted", announcements[0].State)
}
func TestGetAllWithOffsetAndLimit(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
collection.Insert(Announcement{Description: "description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
collection.Insert(Announcement{Description: "second description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
collection.Insert(Announcement{Description: "second description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
collection.Insert(Announcement{Description: "pre last description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
collection.Insert(Announcement{Description: "last description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
announcements := GetAll(3, 5, "validated")
assert.Len(test, announcements, 2)
assert.Equal(test, "pre last description test", announcements[0].Description)
assert.Equal(test, "last description test", announcements[1].Description)
}
func TestFindByIdLostAnnouncement(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
collection.Insert(Announcement{Id: bson.ObjectIdHex("54f47ae176a10ee8daace822"), Description: "description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
collection.Insert(Announcement{Id: bson.ObjectIdHex("54f47ae176a10ee8daace823"), Description: "second description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
announcement := FindById("54f47ae176a10ee8daace822")
assert.Equal(test, "description test", announcement.Description)
}
func TestFindLostAnnouncement(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
collection.Insert(Announcement{Description: "description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
collection.Insert(Announcement{Description: "second description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
collection.Insert(Announcement{Description: "second description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
collection.Insert(Announcement{Description: "pre last description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
collection.Insert(Announcement{Description: "pre last description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
collection.Insert(Announcement{Description: "last description test", PhoneNumber: "0606060606", Type: "lost", State: "validated"})
announcements, total := Find("pre", 1, 1)
assert.Len(test, announcements, 1)
assert.Equal(test, 2, total)
assert.Equal(test, "pre last description test", announcements[0].Description)
}
func TestFindOnlyLostAnimalsByCity(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
collection.Insert(Announcement{Description: "first description test", PhoneNumber: "0606060606", City: "Saint Denis", State: "validated"})
collection.Insert(Announcement{Description: "second description test", PhoneNumber: "0606060606", City: "Saint Denis", State: "validated"})
collection.Insert(Announcement{Description: "third description test", PhoneNumber: "0606060606", City: "Saint Denis", State: "found"})
collection.Insert(Announcement{Description: "last description test", PhoneNumber: "0606060606", City: "Saint Denis", State: "deleted"})
announcements, total := FindByCity("Saint Denis", 0, 2)
assert.Len(test, announcements, 2)
assert.Equal(test, 2, total)
assert.Equal(test, "first description test", announcements[0].Description)
assert.Equal(test, "second description test", announcements[1].Description)
}
func TestFindByCityLostAnnouncement(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
collection.Insert(Announcement{Description: "description test", PhoneNumber: "0606060606", City: "stdenis", Type: "lost", State: "validated"})
collection.Insert(Announcement{Description: "second description test", PhoneNumber: "0606060606", City: "stemarie", Type: "lost", State: "validated"})
announcements, total := FindByCity("stemarie", 0, 10)
assert.Len(test, announcements, 1)
assert.Equal(test, 1, total)
assert.Equal(test, "second description test", announcements[0].Description)
assert.Equal(test, "stemarie", announcements[0].City)
}
func TestUpdateAnnouncementForAnimalFound(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
insertedAnnouncement := Announcement{Description: "updated", PhoneNumber: "0606060606", City: "stdenis", Type: "lost", State: "lost"}
collection.Insert(Announcement{Description: "not updated", PhoneNumber: "0606060606", City: "stdenis", Type: "lost", State: "lost"})
collection.Insert(insertedAnnouncement)
collection.Insert(Announcement{Description: "not updated", PhoneNumber: "0606060606", City: "stdenis", Type: "lost", State: "lost"})
collection.Find(bson.M{"description": "updated"}).One(&insertedAnnouncement)
UpdateState(insertedAnnouncement.Id, "found")
var announcements []Announcement
collection.Find(bson.M{}).All(&announcements)
assert.Equal(test, "not updated", announcements[0].Description)
assert.Equal(test, "lost", announcements[0].State)
assert.Equal(test, "updated", announcements[1].Description)
assert.Equal(test, "found", announcements[1].State)
assert.Equal(test, "not updated", announcements[2].Description)
assert.Equal(test, "lost", announcements[2].State)
}
func TestDontUpdateWithWrongState(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
insertedAnnouncement := Announcement{Description: "updated", PhoneNumber: "0606060606", City: "stdenis", Type: "lost", State: "waiting for validation"}
collection.Insert(insertedAnnouncement)
collection.Find(bson.M{"description": "updated"}).One(&insertedAnnouncement)
assert.Panics(test, func() { UpdateState(insertedAnnouncement.Id, "toto") }, "Calling UpdateState() should panic")
var announcement Announcement
collection.Find(bson.M{}).One(&announcement)
assert.Equal(test, "waiting for validation", announcement.State)
}
func TestSaveLocationAnnouncement(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
Create(&Announcement{Locations: []*Location{&Location{Latitude: -55.1232343, Longitude: 1.12122332, Date: time.Now()}}, Account: &Account{}})
var announcements []Announcement
collection.Find(bson.M{}).All(&announcements)
assert.Equal(test, -55.1232343, announcements[0].Locations[0].Latitude)
assert.Equal(test, 1.12122332, announcements[0].Locations[0].Longitude)
assert.NotNil(test, announcements[0].Locations[0].Date)
}
func TestAddLocationAnnouncement(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
collection.Insert(Announcement{Id: bson.ObjectIdHex("54f47ae176a10ee8daace822"), Locations: []*Location{&Location{Latitude: 1, Longitude: 2}}, Account: &Account{Email: "toto<EMAIL>"}})
AddLocation(Announcement{Id: bson.ObjectIdHex("54f47ae176a10ee8daace822"), Locations: []*Location{&Location{Latitude: 1, Longitude: 2}, &Location{Latitude: -55.1232343, Longitude: 1.12122332, Date: time.Now()}}, Account: &Account{Email: "toto@<PASSWORD>"}})
var announcements []Announcement
collection.Find(bson.M{}).All(&announcements)
locations := announcements[0].Locations
assert.Len(test, locations, 2)
assert.Equal(test, 1, locations[0].Latitude)
assert.Equal(test, 2, locations[0].Longitude)
assert.Equal(test, -55.1232343, locations[1].Latitude)
assert.Equal(test, 1.12122332, locations[1].Longitude)
assert.NotNil(test, locations[1].Date)
}
func GetAdsCollection() *mgo.Collection {
dbConf := configuration.GetConfiguration().GetDatabase()
session, _ := mgo.Dial(dbConf.Url)
database := session.DB(dbConf.Name)
database.Login(dbConf.Username, dbConf.Password)
collection := database.C("announcement")
return collection
}
<file_sep>/minify/css.go
package minify
import (
"net/http"
)
var urlCss = "http://cssminifier.com/raw"
func MinifyCss(filepath string) {
MinifyFromFile(filepath, urlCss, "styles")
}
func AppCssHandler(writer http.ResponseWriter, request *http.Request) {
write(writer, "styles")
}
<file_sep>/announcement/admin_test.go
package announcement
import (
"github.com/stretchr/testify/assert"
"labix.org/v2/mgo/bson"
"reunion/configuration"
"testing"
)
func TestUpdateState(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetAdsCollection()
collection.DropCollection()
insertedAnnouncement := Announcement{Description: "updated", PhoneNumber: "0606060606", City: "stdenis", Type: "lost", State: "waiting for validation"}
collection.Insert(insertedAnnouncement)
collection.Find(bson.M{"description": "updated"}).One(&insertedAnnouncement)
UnrestrictedUpdateState(insertedAnnouncement.Id, "validated")
var announcement Announcement
collection.Find(bson.M{}).One(&announcement)
assert.Equal(test, "validated", announcement.State)
}
<file_sep>/announcement/specy/specy.go
package specy
import (
"encoding/json"
. "labix.org/v2/mgo/bson"
"log"
"net/http"
"reunion/configuration"
"strings"
)
var SPECIES_URL = map[string]string{"Chien": "http://wamiz.com/chiens/race-chien/races", "Chat": "http://wamiz.com/chats/race-chat/races"}
type Species []Specy
type Specy struct {
Name, Picture, Animal string
}
func (species Species) Len() int {
return len(species)
}
func (species Species) Swap(i, j int) {
species[i], species[j] = species[j], species[i]
}
func (species Species) Less(i, j int) bool {
return strings.Replace(species[i].Name, "É", "E", 1) < strings.Replace(species[j].Name, "É", "E", 1)
}
func GetSpeciesHandler(writer http.ResponseWriter, request *http.Request) {
jsonSpecies, err := json.Marshal(GetSpecies())
if err != nil {
log.Panicf("Erreur lors de la conversion JSON : %s", err.Error())
}
writer.Write(jsonSpecies)
}
func GetSpecies() Species {
if isAlreadyFetchedFromSite() {
return getSpeciesFromCollection()
}
log.Panicf("Aucune donnée concernant les races d'animaux")
return nil
}
func isAlreadyFetchedFromSite() bool {
collection, session := configuration.GetSpecyCollection()
defer session.Close()
count, err := collection.Find(M{}).Count()
logError(err)
return count > 0
}
func getSpeciesFromCollection() (species Species) {
collection, session := configuration.GetSpecyCollection()
defer session.Close()
collection.Find(M{}).All(&species)
return species
}
func logError(err error) {
if err != nil {
log.Panicf("Erreur lors du parsing de la page des races : %s", err.Error())
}
}
<file_sep>/announcement/seen_test.go
package announcement
import (
"github.com/stretchr/testify/assert"
"reunion/configuration"
"testing"
)
func TestGetSeenAnnouncement(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
first := Announcement{Description: "description test", PhoneNumber: "0606060606", Type: "seen", State: "validated"}
second := Announcement{Description: "second description test", PhoneNumber: "0606060606", Type: "seen", State: "validated"}
collection := GetAdsCollection()
collection.DropCollection()
collection.Insert(first)
collection.Insert(second)
announcements, total := GetAnnouncementsByType("seen", 0, 2)
assert.Len(test, announcements, 2)
assert.Equal(test, 2, total)
assert.Equal(test, first.Description, announcements[0].Description)
assert.Equal(test, second.Description, announcements[1].Description)
}
<file_sep>/init_data.sh
#!/bin/bash
mongo reunion --eval "db.announcement.remove({})"
indexGlobal=1
for j in {1..100}
do
insertValue=""
for i in {1..10}
do
insertValue=$insertValue"{'name': 'Médor $i$j', 'description' : 'description test','race': 'Shiba Inu', 'city': 'Saint Denis', 'color': 'Noir et blanc', 'phonenumber' : '0606060606','account': {'email': '<EMAIL>', 'password': '<PASSWORD>'}, 'type' : 'lost', 'state': 'validated', 'creationdate' : ISODate('20$i$j-02-21T15:00:00Z')},"
indexGlobal=$indexGlobal+1
done
insertValue="db.announcement.insert([$insertValue])"
echo $insertValue | mongo reunion
done
for j in {1..3}
do
insertValue=""
for i in {1..10}
do
insertValue=$insertValue"{'name': 'Toto $i$j', 'description' : 'description test','race': 'Shiba Inu', 'city': 'Saint Pierre', 'color': 'Noir et blanc', 'phonenumber' : '0606060606','account': {'email': '<EMAIL>', 'password': '<PASSWORD>'}, 'type' : 'lost', 'state': 'validated', 'creationdate' : ISODate('20$i$j-02-21T15:00:00Z')},"
indexGlobal=$indexGlobal+1
done
insertValue="db.announcement.insert([$insertValue])"
echo $insertValue | mongo reunion
done
<file_sep>/static/js/reunionctrl.js
"use strict"
var app = angular.module('reunion', ['mapRaphael', 'ui.select', 'ngSanitize', 'ui.bootstrap']);
app.controller('ReunionCtrl', ['$rootScope', '$scope', '$http', '$location', '$q', 'WSService', 'utils', function($rootScope, $scope, $http, $location, $q, WSService, utils) {
$scope.cities = [ { id: 'stdenis', label: '<NAME>', region: 'Nord', img: '/static/images/map.png' }, { id: 'standre', label: '<NAME>', region: 'Est', img: '/static/images/map.png' }, { id: 'stpaul', label: '<NAME>', region: 'Ouest', img: '/static/images/map.png' },{ id: 'lesavirons', label: 'Les Avirons', region: 'Sud', img: '/static/images/map.png' },
{ id: 'stemarie', label: '<NAME>', region: 'Nord', img: '/static/images/map.png' }, { id: 'lapossession', label: 'La Possession', region: 'Ouest', img: '/static/images/map.png' }, { id: 'stesuzanne', label: '<NAME>', region: 'Nord', img: '/static/images/map.png' },
{ id: 'leport', label: 'Le Port', region: 'Ouest', img: '/static/images/map.png' }, { id: 'stleu', label: '<NAME>', region: 'Ouest', img: '/static/images/map.png' }, { id: 'stlouis', label: '<NAME>', region: 'Sud', img: '/static/images/map.png' }, { id: 'stpierre', label: '<NAME>', region: 'Sud', img: '/static/images/map.png' }, { id: 'letampon', label: 'Le Tampon', region: 'Sud', img: '/static/images/map.png' },
{ id: 'entredeux', label: '<NAME>', region: 'Sud', img: '/static/images/map.png' }, { id: 'cilaos', label: 'Cilaos', region: 'Sud', img: '/static/images/map.png' }, { id: 'salazie', label: 'Salazie', region: 'Est', img: '/static/images/map.png' }, { id: 'laplainedespalmistes', label: 'La Plaine des Palmistes', region: 'Est', img: '/static/images/map.png' },
{ id: 'sterose', label: '<NAME>', region: 'Est', img: '/static/images/map.png' }, { id: 'braspanon', label: '<NAME>', region: 'Est', img: '/static/images/map.png' }, { id: 'stbenoit', label: '<NAME>', region: 'Est', img: '/static/images/map.png' }, { id: 'stjoseph', label: '<NAME>', region: 'Est', img: '/static/images/map.png' }, { id: 'stphilippe', label: '<NAME>', region: 'Est', img: '/static/images/map.png' },
{ id: 'troisbassins', label: '<NAME>', region: 'Ouest', img: '/static/images/map.png' }, { id: 'petiteile', label: '<NAME>', region: 'Sud', img: '/static/images/map.png' }, { id: 'etangsale', label: '<NAME>', region: 'Sud', img: '/static/images/map.png' } ];
$rootScope.numberByPage = 5;
$scope.oneResultTemplates = { 'perdu': '/static/html/loss_one_result.html', 'errant': '/static/html/seen_one_result.html', 'adopter': '/static/html/adopt_one_result.html', 'found': '/static/html/found_one_result.html' };
$scope.getOneResultTemplate = function(announcement) {
var path = announcement.State == 'found' ? announcement.State : announcement.Type;
return $scope.oneResultTemplates[path];
};
$scope.isTab = function(path) {
if (path == 'accueil') {
return new RegExp('^http://.+/.+$').exec(window.location.toString())== null;
}
return new RegExp(path + '$').exec(window.location.toString().split('?')[0]) != null;
};
$scope.hoverCity = function(city) {
$('path#' + city).attr('fill', '#F9C866');
};
$scope.outCity = function(city) {
$('path#' + city).attr('fill', '#F4EAD6');
};
$rootScope.$on('seen-created', function(event, announcement) {
$rootScope.$apply(function() {
$rootScope.createdSeenAnnouncement = announcement;
});
showNotification();
});
$scope.hideNotification = function() {
$('.notification').addClass('notification-hidden');
};
$scope.showContact = function() {
$('#contact-uncompressed').toggleClass('show');
};
$scope.hideContact = function() {
$('#contact-uncompressed').toggleClass('show');
};
$scope.sendMessage = function() {
$http.post('/ws/contact/message', { sender: $scope.contactSender, message: $scope.contactMessage }).success(function(data, status, headers) {
$scope.contactSender = undefined;
$scope.contactMessage = undefined;
notifySuccess('Contact', 'Message envoyé');
}).error(function(data, status, headers) {
notifyError('Contact', 'Erreur lors l\'envoi du message.<br/> Veuillez réessayer, si cela persiste merci de contacter l\'administrateur');
});
};
function showNotification() {
$('.notification').removeClass('notification-hidden');
}
function searchCityLabel(cities, id) {
for (var index in cities) {
if (cities[index].id == id) {
return cities[index];
}
}
return undefined;
}
$scope.$on('map-mouseover', function (event, city) {
$('[name="'+city.id+'"] span').addClass('selected-cities');
$scope.$apply();
});
$rootScope.$on('location-saved', function() {
$('#location').modal('hide');
});
$('#authentication').on('shown.bs.modal', function () {
$('#email').focus()
});
$('#contact').on('shown.bs.modal', function () {
$('#sender').focus()
});
$scope.displayLoading = function (display) {
$scope.displayProgressbar = display;
};
$scope.selectAnnouncement = function(announcement) {
$scope.selectedAnnouncement = announcement;
};
$scope.searchById = function(id) {
$scope.displayLoading(true);
$http.get('/ws/animaux?id=' + id + '&offset=0&limit=1').success(function(data, status, headers) {
$scope.announcements = data.announcements;
$scope.totalItems = 1;
$scope.displayLoading(false);
}).error(function(data, status, headers) {
notifyError('Recherche', 'Erreur lors de l\'exécution de la recherche.<br/> Veuillez réessayer, si cela persiste merci de contacter l\'administrateur');
$scope.displayLoading(false);
});
};
$scope.utils = utils;
$scope.contactSubmitted = false;
}]
);
app.factory('WSService', ['$rootScope', function($rootScope) {
var Service = {};
var websocket = new WebSocket("ws://" + window.location.host + "/socket");
websocket.onopen = function(){
};
websocket.onmessage = function(message) {
var notification = JSON.parse(message.data);
$rootScope.$emit(notification.action, notification.announcement);
};
window.onbeforeunload = function() {
websocket.close();
};
return Service;
}]
);
app.service('announcementService', [ '$rootScope', '$q', '$http', function($rootScope, $q, $http) {
return {
getAnnouncements: function(offset, type, searchQueryParam) {
$rootScope.$emit('loading', true);
var deferred = $q.defer();
var type = type ? '/' + type : '';
var searchQueryParam = searchQueryParam ? '&' + searchQueryParam : '';
$http.get('/ws/animaux' + type + '?offset=' + offset + '&limit=' + $rootScope.numberByPage + searchQueryParam).success(function(data, status, headers) {
deferred.resolve({ 'announcements': data.announcements, 'totalItems': data.total });
$rootScope.$emit('loading', false);
}).error(function(data, status, headers) {
notifyError('Liste des animaux', 'Erreur lors de la récupération de la liste des animaux.<br/> Veuillez réessayer, si cela persiste merci de contacter l\'administrateur');
deferred.reject({ 'announcements': [], 'totalItems': 0 });
$rootScope.$emit('loading', false);
});
return deferred.promise;
},
addLocation: function(announcement, newLocation) {
if (announcement.Locations == undefined) {
announcement.Locations = [];
}
announcement.Locations.push(newLocation);
notifyInfo('Localisation', 'Prise en compte de la demande d\'ajout...');
$http.put('/ws/animaux/perdu/locations', announcement).success(function(data, status, headers) {
notifySuccess('Localisation', 'Ajout d\'une nouvelle localisation effectué avec succès');
$rootScope.$emit('location-saved', false);
}).error(function(data, status, headers) {
notifyError('Localisation', 'Erreur survenue lors de la localisation', data);
});
},
updateState: function(announcementId, action) {
notifyInfo('Modification', 'Prise en compte de la demande de modification...');
var deferred = $q.defer();
$http.put('/ws/animaux/id/' + announcementId + '?action=' + action).success(function(data, status, headers) {
deferred.resolve();
notifySuccess('Modification', 'Modification effectuée avec succès');
}).error(function(data, status, headers) {
if (status == 403) {
notifyError('Modification', 'Vous n\'avez pas les droits sur cette annonce');
} else {
notifyError('Modification', 'Erreur survenue lors de la modification');
}
deferred.reject();
});
return deferred.promise;
},
authenticate: function(announcementId, account) {
$http.post('/login?id=' + announcementId, account).success(function(data, status, headers) {
if (status == 200) {
$rootScope.$emit('isAuthenticated', headers('Authorization'));
}
$rootScope.$emit('loading', false);
}).error(function(data, status, headers) {
if (status == 401) {
notifyWarning('Authentification', 'Email / mot de passe incorrect pour cette annonce');
} else {
notifyWarning('Authentification', 'Erreur lors de l\'authentication.<br/> Veuillez réessayer, si cela persiste merci de contacter l\'administrateur');
}
$rootScope.$emit('loading', false);
});
}
};
}]
);
app.service('dateService', function() {
return {
computeDuration: function(date) {
return moment(date).locale('fr').calendar();
},
getFormattedDate: function(date) {
return moment(date).locale('fr').fromNow();
},
fetchLastLocationDate: function(locations) {
if (locations && locations.length > 0) {
return moment(locations[locations.length - 1].Date).locale('fr').calendar();
}
}
};
});
app.service('utils', function() {
return {
getPicture: function(picture) {
return picture ? '/photos/' + picture : '/static/images/noimage.gif';
},
displayPhoneNumber: function(announcement) {
announcement.displayedPhoneNumber = announcement.PhoneNumber;
}
};
});
app.controller('IndexCtrl', ['$scope', '$http', 'announcementService', 'utils', function($scope, $http, announcementService, utils) {
$scope.getOneAnnouncement = function() {
announcementService.getAnnouncements(0, 'perdu').then(function(result) {
$scope.announcements = result.announcements;
$scope.totalItems = result.totalItems;
});
};
$scope.searchCriteria = function() {
if ($scope.criteria && $scope.criteria != '') {
window.location = '/animaux?criteria=' + $scope.criteria;
} else {
window.location = '/animaux';
}
};
$scope.getThumbnail = function(value) {
return getPicture(value.img);
};
function getPicture(picture) {
return picture ? picture : '/static/images/noimage.gif';
}
$scope.searchSuggestion = function(value) {
var suggestions = [];
var indexFound = 0;
for (var i = 0;i < $scope.cities.length && i < 5;i++) {
var cityLabel = $scope.cities[i].label;
if (cityLabel.toLowerCase().indexOf(value) > -1) {
suggestions.push({img: '/static/images/gps.png', label: cityLabel, category: 'city', index: ++indexFound});
}
}
return $http.get('/ws/animaux?offset=0&limit=5&criteria=' + value)
.then(function(response){
if (response.data.announcements) {
var indexFound = 0;
for (var i = 0;i < response.data.announcements.length;i++) {
var announcement = response.data.announcements[i];
suggestions.push({img: '/photos/' + announcement.Picture, label: announcement.Name, category: 'announcement', index: ++indexFound});
}
}
return suggestions;
});
return suggestions;
};
$scope.getOneAnnouncement();
}]
);
app.controller('ContactCtrl', ['$scope', '$http', function($scope, $http) {
$scope.sendMail = function() {
if ($scope.contactForm.$invalid) {
$scope.contactFormSubmitted = true;
return;
}
$scope.contactFormSubmitted = false;
$http.post('/ws/mail', { sender: $scope.mail.Sender, message: $scope.mail.Message, announcementId: $scope.selectedAnnouncement.Id }).success(function(data, status, headers) {
$('#contact').modal('hide');
$scope.mail = undefined;
notifySuccess('Contact', 'Message envoyé');
}).error(function(data, status, headers) {
notifyError('Contact', 'Erreur lors l\'envoi du message.<br/> Veuillez réessayer, si cela persiste merci de contacter l\'administrateur');
});
};
}]
);
app.controller('OneAnnouncementCtrl', ['$scope', '$http', 'announcementService', 'utils', 'dateService', function($scope, $http, announcementService, utils, dateService) {
$scope.searchById = function(id) {
$http.get('/ws/animaux?id=' + id + '&offset=0&limit=1').success(function(data, status, headers) {
$scope.announcements = data.announcements;
}).error(function(data, status, headers) {
notifyError('Recherche', 'Erreur lors de l\'exécution de la recherche.<br/> Veuillez réessayer, si cela persiste merci de contacter l\'administrateur');
});
};
$scope.addLocation = function() {
announcementService.addLocation($scope.selectedAnnouncement, $scope.location);
};
$scope.prepareUpdate = function(action, announcement) {
$scope.actionRequiredAuth = action;
$scope.announcementToUpdate = announcement;
};
$('#authentication').on('hide.bs.modal', function (e) {
$scope.account = undefined;
});
$('#authentication').on('shown.bs.modal', function () {
$('#email').focus()
});
$('#contact').on('shown.bs.modal', function () {
$('#sender').focus()
});
$('#location').on('shown.bs.modal', function () {
if ($scope.selectedAnnouncement.Locations && $scope.selectedAnnouncement.Locations.length > 0) {
var lastLocation = $scope.selectedAnnouncement.Locations[$scope.selectedAnnouncement.Locations.length - 1];
initializeMaps(true, $scope, 12, { lat: lastLocation.Latitude, lng: lastLocation.Longitude}, $scope.selectedAnnouncement.Locations);
} else {
initializeMaps(true, $scope, 10, { lat: -21.1306889, lng: 55.5264794});
}
});
var url = window.location.pathname.split('/');
if (url.length >= 4) {
$scope.searchById(url[3]);
} else {
notifyError('Animal perdu et errant', 'Le paramètre identifiant est manquant');
}
$scope.dateService = dateService;
}]
);
app.controller('LostListCtrl', ['$rootScope', '$scope', '$http', 'announcementService', 'dateService', 'utils', function($rootScope, $scope, $http, announcementService, dateService, utils) {
$scope.getAnnouncements = function(offset, type, searchQueryParam) {
if (offset == 0) {
$scope.currentPage = 1;
}
announcementService.getAnnouncements(offset, type, searchQueryParam).then(function(result) {
$scope.announcements = result.announcements;
$scope.totalItems = result.totalItems;
});
};
$scope.getAnnouncementsFromType = function(type) {
if (type != $scope.type) {
$scope.type = type;
$scope.criteria = undefined;
$scope.city = undefined;
$scope.getAnnouncements(0, type);
}
};
$rootScope.$on('loading', function(event, loading) {
event.stopPropagation();
$scope.displayLoading(loading);
});
$scope.searchCity = function(offset) {
$scope.search('city', offset);
};
$scope.searchCriteria = function(offset) {
$scope.search('criteria', offset);
};
$scope.search = function(queryParam, offset) {
offset = offset ? offset : 0;
$scope.find(queryParam, $scope.criteria, offset);
};
$scope.addLocation = function() {
announcementService.addLocation($scope.selectedAnnouncement, $scope.location);
};
$scope.prepareUpdate = function(action, announcement) {
$scope.actionRequiredAuth = action;
$scope.announcementToUpdate = announcement;
};
$('#location').on('shown.bs.modal', function () {
if ($scope.selectedAnnouncement.Locations && $scope.selectedAnnouncement.Locations.length > 0) {
var lastLocation = $scope.selectedAnnouncement.Locations[$scope.selectedAnnouncement.Locations.length - 1];
initializeMaps(true, $scope, 12, { lat: lastLocation.Latitude, lng: lastLocation.Longitude}, $scope.selectedAnnouncement.Locations);
} else {
initializeMaps(true, $scope, 10, { lat: -21.1306889, lng: 55.5264794});
}
});
$scope.find = function(searchQueryParam, criteria, offset) {
var searchQueryParam = searchQueryParam + '=' + $scope.criteria;
$scope.getAnnouncements(offset, undefined, searchQueryParam);
};
$scope.pageChanged = function() {
var offset = ($scope.currentPage - 1) * $rootScope.numberByPage;
$scope.getAnnouncements(offset, $scope.type, $scope.querySearchParam);
var target_offset = $('.search-result').offset();
var target_top = target_offset.top;
$('html, body').animate({scrollTop:target_top}, 500);
};
$scope.querySearchParam = undefined;
var url = decodeURI(window.location.toString()).split('?');
if (url.length >= 2) {
var splittedQueryParam = /^(id|criteria|city)=(.+)/g.exec(url[1]);
if (splittedQueryParam[1] == 'id') {
$scope.searchById(splittedQueryParam[2]);
return;
}
$scope.querySearchParam = splittedQueryParam[0];
$scope.criteria = splittedQueryParam[2];
}
$scope.getAnnouncements(0, $scope.type, $scope.querySearchParam);
$scope.dateService = dateService;
$scope.currentPage = 1;
$scope.maxSize = 3;
$scope.numPages = 15;
}]
);
app.controller('AuthCtrl', ['$rootScope', '$scope', '$http', '$q', 'announcementService', function($rootScope, $scope, $http, $q, announcementService) {
$scope.launchUpdate = function(action, announcement) {
closeAuth();
var deferred = $q.defer();
deferred.promise.then(announcementService.updateState(announcement.Id, action))
.then(announcementService.getAnnouncements(0, $scope.type).then(function(result) {
$scope.$parent.announcements = result.announcements;
$scope.$parent.totalItems = result.totalItems;
}));
};
$scope.authenticate = function() {
announcementService.authenticate($scope.announcementToUpdate.Id, $scope.account);
};
$rootScope.$on('isAuthenticated', function(event, token, action) {
$http.defaults.headers.common['Authorization'] = token;
$scope.launchUpdate($scope.actionRequiredAuth, $scope.announcementToUpdate);
});
}]);
app.controller('AdminCtrl', ['$scope', '$http', function($scope, $http) {
$scope.authenticate = function() {
if ($scope.loginForm.$invalid) {
$scope.submitted = true;
return;
}
$http.post('/admin/login', $scope.account).success(function(data, status, headers) {
if (status == 200) {
$scope.$emit('isAuthenticated', headers('Authorization'));
}
}).error(function(data, status, headers) {
if (status == 401) {
notifyWarning('Authentification', 'Email / mot de passe incorrect pour cette annonce');
} else {
notifyWarning('Authentification', 'Erreur lors de l\'authentication.<br/> Veuillez réessayer, si cela persiste merci de contacter l\'administrateur');
}
});
};
$scope.$on('isAuthenticated', function(event, data) {
$http.defaults.headers.common['Authorization'] = data;
fetchAddAnnouncementsTemplate();
});
function fetchAddAnnouncementsTemplate() {
$http.get('/admin/announcements').success(function(data, status) {
$scope.addAnnouncementsTemplate = data;
})
.error(function(status, data) {
notifyError('Annonces', 'Erreur lors de la récupération du contenu des annonces');
});
}
$scope.availableStates = ['waiting for validation', 'validated', 'deleted', 'found', 'deactivated'];
$scope.getAllAnnouncements = function() {
$scope.displayLoading(true);
$http.get('/ws/admin/announcements/lost/all?state=' + $scope.state).success(function(data, status, headers) {
$scope.announcements = data;
$scope.displayLoading(false);
}).error(function(data, status, headers) {
notifyError('Liste des animaux perdus', 'Erreur lors de la récupération de la liste des animaux perdus.<br/> Veuillez réessayer, si cela persiste merci de contacter l\'administrateur');
$scope.displayLoading(false);
});
};
$scope.updateState = function(announcement, state) {
notifyInfo('Modification', 'Prise en compte de la demande de modification');
$http.put('/ws/admin/announcements/id/' + announcement.Id + '?state=' + state).success(function(data, status, headers) {
notifySuccess('Modification', 'Modification effectuée');
$scope.getAllAnnouncements();
}).error(function(data, status, headers) {
notifyError('Modification', 'Erreur lors de la modification');
});
};
}]);
app.controller('CreateCtrl', ['$scope', '$http', function($scope, $http) {
$scope.maxDate = new Date();
$scope.isDateInvalid = function() {
if ($scope.announcement == undefined || $scope.announcement.LostDate == undefined) {
return false;
}
return !moment($scope.announcement.LostDate, momentDateFormat).locale('fr').isValid();
};
$scope.geoLocationActivated = function() {
return navigator.geolocation;
};
$scope.geoLocalize = function() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
map.setZoom(13);
var locationMarker;
var image = {
url: '/static/images/location.png',
size: new google.maps.Size(45, 45),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(15, 20)
};
locationMarker = new google.maps.Marker({ position: pos, map: map, animation: google.maps.Animation.DROP, icon: image });
window.setTimeout(function() {
locationMarker.setMap(null);
}, 3000);
});
}
};
$scope.isPasswordsDifferent = function() {
return $scope.announcement && $scope.announcement.Account && $scope.announcement.Account.Password != $scope.announcement.Account.Confirmation;
};
$scope.groupByRegion = function (item){
return angular.uppercase(item.region);
};
$scope.searchLocation = function () {
var geocodeRequest = {
'address': $scope.locationAddress,
'latLng': new google.maps.LatLng(-21.1306889, 55.5264794),
'region': 'fr',
'componentRestrictions': {'country': 'Réunion'}
};
var geocoder = new google.maps.Geocoder();
geocoder.geocode(geocodeRequest, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var firstAddress = results[0];
map.panTo(firstAddress.geometry.location);
map.setZoom(15);
}
});
};
$scope.createAnnouncement = function(type) {
if ($scope.createForm.$invalid || $scope.isPasswordsDifferent()) {
$scope.submitted = true;
return;
}
$scope.announcement.Type = type;
$scope.announcement.Locations = [ $scope.location ];
notifyInfo('Signalement', 'Prise en compte de la demande de signalement d\'un animal...')
$http.post('/ws/animaux/' + $scope.announcement.Type, $scope.announcement)
.success(function(data, status, headers) {
notifySuccess('Signalement', 'Enregistrement du signalement de l\'animal effectué avec succès')
$scope.announcement = undefined;
$scope.submitted = false;
$scope.displayLoading(false);
}).error(function(data, status, headers) {
notifyError('Signalement', 'Erreur lors du signalement d\'un animal.<br/> Veuillez réessayer, si cela persiste merci de contacter l\'administrateur', data)
$scope.displayLoading(false);
});
};
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.fetchSpecies = function() {
$http.get('/ws/species').success(function(data, status, headers) {
$scope.species = data;
}).error(function(data, status, headers) {
notifyError('Race', 'Erreur lors de la récupération de la liste des races de chien.<br/> Veuillez réessayer, si cela persiste merci de contacter l\'administrateur');
});
}();
$scope.initMaps = function() {
initializeMaps(false, $scope, 10, { lat: -21.1306889, lng: 55.5264794});
};
$scope.submitted = false;
$scope.announcement = {};
$scope.dateFormat = 'EEEE dd MMMM yyyy';
var momentDateFormat = 'dddd D MMMM YYYY';
}]
);
var map;
function initializeMaps(hasValidateBtn, $scope, zoom, position, locations) {
var mapOptions = {
center: position,
zoom: zoom,
panControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: false,
scaleControl: false,
streetViewControl: true,
overviewMapControl: false
};
map = new google.maps.Map(document.getElementById('google-maps'), mapOptions);
var infoDiv = document.createElement('div');
var displayInfo = new DisplayInfo(infoDiv, map);
infoDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_LEFT].push(infoDiv);
if (hasValidateBtn) {
var validateDiv = document.createElement('div');
var validateControl = new ValidateControl(validateDiv, map);
validateDiv.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(validateDiv);
google.maps.event.addDomListener(validateDiv, 'click', function() {
$scope.addLocation()
});
}
var markers = [];
if (locations) {
var lastLocation = false;
var coordonates = [];
var lastCoordonate;
for (var index in locations) {
if (index == locations.length - 1) {
lastLocation = true;
}
var coordonate = new google.maps.LatLng(locations[index].Latitude, locations[index].Longitude);
placeMarker(coordonate, locations[index].Date, lastLocation);
coordonates.push(coordonate);
if (lastCoordonate) {
computeItinery(lastCoordonate, coordonate);
}
lastCoordonate = coordonate;
}
var way = new google.maps.Polyline({
path: coordonates,
strokeColor: "#FF0000",
strokeOpacity: 0,
strokeWeight: 1,
icons: [{
icon: { path: 'M 0,-1 0,1', strokeWeight: 1, strokeOpacity: 0.5, scale: 4 },
offset: '0',
repeat: '20px'
}]
});
way.setMap(map);
}
function computeItinery(origin, destination) {
var request = {
origin : origin,
destination : destination,
travelMode : google.maps.DirectionsTravelMode.WALKING
}
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status){
if(status == google.maps.DirectionsStatus.OK){
new google.maps.DirectionsRenderer({
map : map,
options : { suppressMarkers: true }
}).setDirections(response);
}
});
}
google.maps.event.addListener(map, 'click', function(e) {
clearMarkers();
placeTempMarker(e.latLng, new Date());
});
function placeMarker(position, date, lastLocation) {
var animal = $scope.selectedAnnouncement && $scope.selectedAnnouncement.Animal ? $scope.selectedAnnouncement.Animal : $scope.announcement.Animal;
var image = {
url: animal == 'Chat' ? '/static/images/cat-maps.png' : '/static/images/dog-maps.png',
size: new google.maps.Size(45, 45),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(45, 45)
};
var marker = new google.maps.Marker({
position: position,
map: map,
animation: google.maps.Animation.DROP,
icon: image
});
function createMarker(address) {
var markerinfo = new google.maps.InfoWindow({
content: (lastLocation ? 'Dernière localisation<br/>' + moment(date).locale('fr').calendar() : moment(date).locale('fr').calendar()) + (address ? ' <br/>Adresse : ' + address : '')
});
if (lastLocation) {
markerinfo.open(map, marker);
}
google.maps.event.addListener(marker, 'click', function() {
markerinfo.open(map, marker);
});
}
new google.maps.Geocoder().geocode({location: position}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
createMarker(results[0].formatted_address);
}
});
return marker;
}
function placeTempMarker(position, date) {
var marker = placeMarker(position, date);
markers.push(marker);
$scope.location = { Latitude: marker.position.lat(), Longitude: marker.position.lng(), Date: date};
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
}
}
function DisplayInfo(infoDiv, map) {
infoDiv.style.padding = '5px';
var infoUI = document.createElement('div');
infoUI.style.backgroundColor = 'white';
infoUI.style.borderStyle = 'solid';
infoUI.style.borderWidth = '2px';
infoUI.style.textAlign = 'center';
infoDiv.appendChild(infoUI);
var infoText = document.createElement('div');
infoText.style.fontFamily = 'Arial,sans-serif';
infoText.style.fontSize = '12px';
infoText.style.paddingLeft = '4px';
infoText.style.paddingRight = '4px';
infoText.innerHTML = 'Faites un <b>clic</b> sur la carte <br/>pour localiser l\'animal';
infoUI.appendChild(infoText);
}
function ValidateControl(validateDiv, map) {
validateDiv.style.padding = '5px';
var validateUI = document.createElement('div');
validateUI.style.backgroundColor = 'white';
validateUI.style.borderStyle = 'solid';
validateUI.style.borderWidth = '2px';
validateUI.style.cursor = 'pointer';
validateUI.style.textAlign = 'center';
validateDiv.appendChild(validateUI);
var validateText = document.createElement('div');
validateText.style.fontFamily = 'Arial,sans-serif';
validateText.style.fontSize = '15px';
validateText.style.paddingLeft = '14px';
validateText.style.paddingRight = '14px';
validateText.innerHTML = 'Valider';
validateUI.appendChild(validateText);
}
function closeAuth() {
$('#authentication').modal('hide');
}
app.directive('restrictedContent', function($compile, $parse) {
return {
restrict: 'E',
link: function(scope, element, attr) {
scope.$watch(attr.content, function() {
element.html($parse(attr.content)(scope));
$compile(element.contents())(scope);
}, true);
}
}
});
app.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
if (changeEvent.target.files[0] != undefined) {
reader.readAsDataURL(changeEvent.target.files[0]);
}
});
}
}
}]);
<file_sep>/token/token.go
package token
import (
"github.com/dgrijalva/jwt-go"
"io/ioutil"
"log"
"reunion/configuration"
"time"
)
func Create(subject string) string {
token := jwt.New(jwt.GetSigningMethod("RS256"))
token.Claims["exp"] = getExpiration()
token.Claims["sub"] = subject
tokenString, err := token.SignedString(getPrivateKey())
if err != nil {
log.Panicf("Erreur lors de la signature du token : %s", err)
}
return tokenString
}
func Verify(myToken string) bool {
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
return getPublicKey(), nil
})
if err != nil {
log.Printf("Erreur lors du parsing du token : %s", err)
}
return token != nil && token.Valid && token.Claims["sub"] != nil
}
func getExpiration() int64 {
return time.Now().Add(time.Minute * 2).Unix()
}
func getPrivateKey() []byte {
privateKey, err := ioutil.ReadFile(configuration.Conf.GetFilePath(configuration.GetConfiguration().GetKeys().Private))
if err != nil {
log.Panicf("Erreur dans l'ouverture de la clé privée : %s", err)
}
return privateKey
}
func getPublicKey() []byte {
publicKey, err := ioutil.ReadFile(configuration.Conf.GetFilePath(configuration.GetConfiguration().GetKeys().Public))
if err != nil {
log.Panicf("Erreur dans l'ouverture de la clé publique : %s", err)
}
return publicKey
}
<file_sep>/announcement/rss/rss.go
package rss
import (
"fmt"
"net/http"
"reunion/announcement"
"reunion/configuration"
)
func GetFile(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte(GetRss()))
writer.Header().Set("Content-Type", "application/xml")
}
func GetRss() string {
announcements, _ := announcement.GetAnnouncementsByType("", 0, 25)
return Get(announcements)
}
func Get(announcements []announcement.Announcement) string {
base := `<?xml version="1.0" ?><rss version="2.0"><channel><title>AnimaLove - Liste des animaux perdus à la Réunion</title><link>http://` + configuration.Conf.GetUrl() + `</link>
<description>AnimaLove propose un système de recherche par mot clef d'animaux perdus à la Réunion. Les personnes qui auraient aperçu un animal perdu peuvent indiquer sur une carte satellite sa localisation, ce qui permettra aux propriétaires de le retrouver plus rapidement.</description>%s</channel></rss>`
var xmlItems string
for _, ads := range announcements {
xmlAnnouncement := fmt.Sprintf("<guid>%s</guid>", ads.Id.Hex())
xmlAnnouncement += fmt.Sprintf("<pubDate>%s</pubDate>", ads.CreationDate)
xmlAnnouncement += fmt.Sprintf("<title>%s</title>", getTitle(ads))
xmlAnnouncement += fmt.Sprintf("<thumbnail>%s</thumbnail>", ads.GetImageLink())
xmlDescription := ads.Description
xmlDescription += "<br>Lien : " + ads.GetLink()
xmlDescription += "<br>C'est un " + ads.Animal
if ads.Specy != nil {
xmlDescription += "<br>" + ads.Specy.Name
}
xmlDescription += "<br>Couleur : " + ads.Color
xmlDescription += "<br>" + ads.PhoneNumber
xmlAnnouncement += fmt.Sprintf("<description>%s</description>", xmlDescription)
xmlItems += fmt.Sprintf("<item>%s</item>", xmlAnnouncement)
}
return fmt.Sprintf(base, xmlItems)
}
func getTitle(ads announcement.Announcement) string {
title := "Animal " + ads.Type
if ads.Name != "" {
title += " - " + ads.Name
}
return title
}
<file_sep>/home/home.go
package home
import (
"html/template"
"log"
"net/http"
. "reunion/announcement"
. "reunion/configuration"
)
type HomePage struct {
name, Title, Description, Image, Link string
Announcements []Announcement
}
func GetPage(writer http.ResponseWriter, request *http.Request) {
tmpl := template.Must(template.New("base").Delims("[[", "]]").ParseFiles(Conf.GetFilePath("static/html/search.html"), Conf.GetFilePath("static/html/index.html"), Conf.GetFilePath("static/html/base.html")))
announcements, _ := GetAnnouncementsByType("", 0, 15)
page := HomePage{Announcements: announcements, name: "index", Title: "AnimaLove - Recherche d'animaux perdus, trouvés et à adopter", Description: "Service de signalement et de recherche d'animaux perdus, errants et à adopter à la Réunion. Chien ou chat à aider.", Image: "/static/images/logo.png", Link: Conf.GetUrl()}
writer.Header().Set("Cache-control", "public, max-age=3600")
error := tmpl.Execute(writer, page)
if error != nil {
log.Printf("Erreur lors de la construction du template.", error)
http.Error(writer, error.Error(), http.StatusInternalServerError)
}
}
<file_sep>/configuration/file.go
package configuration
import (
"io/ioutil"
"log"
"net/http"
)
func GetRobotsHandler(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte(GetRobots()))
}
func GetRobots() string {
content, err := ioutil.ReadFile(Conf.GetFilePath("static/robots.txt"))
if err != nil {
log.Panicf("Erreur lors la lecture du fichier robots.txt : %s", err.Error())
}
return string(content)
}
func GetSitemapHandler(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte(GetSitemap()))
writer.Header().Set("Content-Type", "application/xml")
}
func GetSitemap() string {
content, err := ioutil.ReadFile(Conf.GetFilePath("static/sitemap.xml"))
if err != nil {
log.Panicf("Erreur lors la lecture du fichier robots.txt : %s", err.Error())
}
return string(content)
}
<file_sep>/minify/minify.go
package minify
import (
"io/ioutil"
"log"
"net/http"
"net/url"
"reunion/configuration"
)
var MinifiedContents = make(map[string]string)
func Store(filename string, minified string) {
MinifiedContents[filename] += minified
}
func MinifyFromFile(filepath string, minifyUrl string, fileType string) {
content, err := ioutil.ReadFile(configuration.Conf.GetFilePath(filepath))
if err != nil {
log.Panicf("Erreur de compression de fichier : %s", err.Error())
}
Store(fileType, Minify(string(content), minifyUrl))
}
func Minify(content string, minifyUrl string) string {
response, err := http.PostForm(minifyUrl, url.Values{"input": {content}})
if err != nil || response.StatusCode != 200 {
log.Printf("Erreur de compression de fichier lors de l'appel au WS : %s", minifyUrl)
return content
}
defer response.Body.Close()
var minifiedContent []byte
if minifiedContent, err = ioutil.ReadAll(response.Body); err != nil {
log.Panicf("Erreur de compression de fichier : %s", err.Error())
}
return string(minifiedContent)
}
func write(writer http.ResponseWriter, filename string) {
writer.Write([]byte(MinifiedContents[filename]))
}
<file_sep>/authentication/authentication.go
package authentication
import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"hash"
"io/ioutil"
"labix.org/v2/mgo/bson"
"log"
"net/http"
"reunion/configuration"
"reunion/token"
)
type User struct {
Email string
Password string
}
func Login(writer http.ResponseWriter, request *http.Request) {
if request.Method != "POST" {
writer.WriteHeader(http.StatusMethodNotAllowed)
return
}
var user User
jsonErr := json.NewDecoder(request.Body).Decode(&user)
if jsonErr != nil {
log.Printf("Erreur lors de la désérialisation pour l'authentification : %s", jsonErr)
return
}
defineAuthentication(writer, user)
}
func EncryptSHA256(password string) string {
salt, err := ioutil.ReadFile(configuration.Conf.GetFilePath(configuration.GetConfiguration().GetKeys().Private))
if err != nil {
log.Printf("Erreur lors récupération du salt : %s", err)
return ""
}
return base64.StdEncoding.EncodeToString(computeHasherWithSalt(password, salt).Sum([]byte(password)))
}
func computeHasherWithSalt(data string, salt []byte) (hasher hash.Hash) {
hasher = sha256.New()
hasher.Write([]byte(data))
hasher.Write(salt)
return hasher
}
func isCorrectUserAndPassword(user User) bool {
number, err := configuration.GetUserCollection().Find(bson.M{"email": user.Email, "password": EncryptSHA256(user.Password)}).Count()
if err != nil {
log.Printf("Erreur lors vérification du username et password en bdd : %s", err)
return false
}
return number == 1
}
func defineAuthentication(writer http.ResponseWriter, user User) {
if isCorrectUserAndPassword(user) {
writer.Header().Set("Authorization", token.Create("Authorization"))
writer.WriteHeader(http.StatusOK)
} else {
writer.WriteHeader(http.StatusUnauthorized)
}
}
<file_sep>/announcement/authentication.go
package announcement
import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"hash"
"io/ioutil"
"labix.org/v2/mgo/bson"
"log"
"net/http"
"reunion/configuration"
"reunion/token"
)
type Account struct {
Email, Password string `xml:"-"`
}
func Login(writer http.ResponseWriter, request *http.Request) {
announcementId := request.FormValue("id")
if request.Method != "POST" || announcementId == "" {
doResponse(writer, http.StatusMethodNotAllowed, "Opération non autorisée ou paramètre manquant: %s", request.Method+" id = "+announcementId)
return
}
var account Account
jsonErr := json.NewDecoder(request.Body).Decode(&account)
if jsonErr != nil {
doResponse(writer, http.StatusBadRequest, "Erreur lors de la désérialisation pour l'authentification : %s", jsonErr.Error())
return
}
defineAuthenticated(writer, account, announcementId)
}
func EncryptSHA256(password string) string {
salt, err := ioutil.ReadFile(configuration.Conf.GetFilePath(configuration.GetConfiguration().GetKeys().Private))
if err != nil {
log.Panicf("Erreur lors de la récupération du salt : %s", err)
}
return base64.StdEncoding.EncodeToString(computeHasherWithSalt(password, salt).Sum([]byte(password)))
}
func doResponse(writer http.ResponseWriter, httpCode int, logMessage string, logComplement string) {
writer.WriteHeader(httpCode)
writer.Write([]byte(fmt.Sprintf(logMessage, logComplement)))
log.Printf(logMessage, logComplement)
}
func computeHasherWithSalt(data string, salt []byte) (hasher hash.Hash) {
hasher = sha256.New()
hasher.Write([]byte(data))
hasher.Write(salt)
return hasher
}
func isCorrectUserAndPasswordForAnnouncement(account Account, announcementId string) bool {
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
number, err := collection.Find(bson.M{"_id": bson.ObjectIdHex(announcementId), "account.email": account.Email, "account.password": EncryptSHA256(account.Password)}).Count()
if err != nil {
log.Panicf("Erreur lors vérification du username et password en bdd : %s", err)
}
return number == 1
}
func CheckTokenOnAnnouncement(announcementId bson.ObjectId, tokenToVerify string) bool {
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
number, err := collection.Find(bson.M{"_id": announcementId, "account.token": tokenToVerify}).Count()
if err != nil {
log.Panicf("Erreur lors vérification du token en bdd : %s", err.Error())
}
return number == 1
}
func defineAuthenticated(writer http.ResponseWriter, account Account, announcementId string) {
if isCorrectUserAndPasswordForAnnouncement(account, announcementId) {
generatedToken := token.Create("Authorization")
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
if err := collection.UpdateId(bson.ObjectIdHex(announcementId), bson.M{"$set": bson.M{"account.token": generatedToken}}); err != nil {
log.Panicf("Erreur lors la modification du token en bdd : %s", err.Error())
}
writer.Header().Set("Authorization", generatedToken)
doResponse(writer, http.StatusOK, "Authentification réussie pour : %s", account.Email)
} else {
doResponse(writer, http.StatusUnauthorized, "Erreur lors de l'authentification pour le user : %s", account.Email)
}
}
<file_sep>/configuration/collection.go
package configuration
import (
"labix.org/v2/mgo"
"log"
"os"
)
const ERROR_MESSAGE = "Erreur lors du dialogue avec la base de donnée : %s"
func GetAnnouncementCollection() (*mgo.Collection, *mgo.Session) {
db := GetConfiguration().GetDatabase()
session, err := mgo.Dial(os.Getenv("MONGOLAB_URI"))
if err != nil {
log.Printf(ERROR_MESSAGE, err.Error())
}
database := session.DB(db.Name)
collection := database.C("announcement")
return collection, session
}
func GetAccountCollection() (*mgo.Collection, *mgo.Session) {
db := GetConfiguration().GetDatabase()
session, err := mgo.Dial(os.Getenv("MONGOLAB_URI"))
if err != nil {
log.Printf(ERROR_MESSAGE, err.Error())
return nil, nil
}
database := session.DB(db.Name)
collection := database.C("account")
return collection, session
}
func GetUserCollection() *mgo.Collection {
db := GetConfiguration().GetDatabase()
session, err := mgo.Dial(os.Getenv("MONGOLAB_URI"))
if err != nil {
log.Printf("Erreur lors du dialogue avec la base de donnée : ", err)
}
database := session.DB(db.Name)
collection := database.C("users")
return collection
}
func GetSpecyCollection() (*mgo.Collection, *mgo.Session) {
db := GetConfiguration().GetDatabase()
session, err := mgo.Dial(os.Getenv("MONGOLAB_URI"))
if err != nil {
log.Panicf(ERROR_MESSAGE, err.Error())
}
database := session.DB(db.Name)
collection := database.C("species")
return collection, session
}
<file_sep>/announcement/seen.go
package announcement
import (
"html/template"
"log"
"net/http"
. "reunion/configuration"
)
func GetSeenFormPage(writer http.ResponseWriter, request *http.Request) {
tmpl := template.Must(template.New("base").Delims("[[", "]]").ParseFiles(Conf.GetFilePath("static/html/create_seen_announcement.html"), Conf.GetFilePath("static/html/base.html")))
description := "Formulaire de signalement d'un chien ou chat errant. Ce formulaire permet de décrire l'animal aperçu et d'indiquer le lieux où il a été vu pour la dernière fois."
page := Page{name: "Animal errant", Title: "AnimaLove - Signaler un chien ou chat errant à la Réunion", Description: description, Image: "/static/images/logo.png", Link: Conf.GetUrl()}
writer.Header().Set("Cache-control", "public, max-age=3600")
err := tmpl.Execute(writer, page)
if err != nil {
log.Panicf("Erreur lors de la construction du template : %s", err.Error())
}
}
<file_sep>/announcement/authentication_test.go
package announcement
import (
"github.com/stretchr/testify/assert"
"labix.org/v2/mgo/bson"
"net/http"
"net/http/httptest"
"reunion/configuration"
"strings"
"testing"
)
func TestLoginSuccessWithEncryptedPassword(test *testing.T) {
initCollections()
insertUserAndAnnouncement("t<EMAIL>", "<PASSWORD>")
writer := httptest.NewRecorder()
request, _ := http.NewRequest("POST", "localhost:8080/authentication?id=54f070908d7d4f1bfdb7a9dd", strings.NewReader("{\"email\": \"toto@test\", \"password\": \"<PASSWORD>\"}"))
Login(writer, request)
assert.Equal(test, http.StatusOK, writer.Code)
assert.Equal(test, "Authentification réussie pour : toto@test", writer.Body.String())
assert.NotEmpty(test, writer.Header().Get("Authorization"))
}
func TestLoginIsMethodNotAllowedWhenItIsNotPostMethod(test *testing.T) {
initCollections()
insertUserAndAnnouncement("toto<EMAIL>", "<PASSWORD>")
writer := httptest.NewRecorder()
request, _ := http.NewRequest("PUT", "localhost:8080/authentication?id=54f070908d7d4f1bfdb7a9dd", strings.NewReader("{\"email\": \"toto@test\", \"password\": \"<PASSWORD>\"}"))
Login(writer, request)
assert.Equal(test, http.StatusMethodNotAllowed, writer.Code)
assert.Equal(test, "Opération non autorisée ou paramètre manquant: PUT id = 5<PASSWORD>", writer.Body.String())
assert.Empty(test, writer.Header().Get("Authorization"))
}
func TestLoginFailedOnIncorrectUsername(test *testing.T) {
initCollections()
insertUserAndAnnouncement("t<EMAIL>", "tutu")
writer := httptest.NewRecorder()
request, _ := http.NewRequest("POST", "localhost:8080/authentication?id=54f070908d7d4f1bfdb7a9dd", strings.NewReader("{\"email\": \"otherUser\", \"password\": \"<PASSWORD>\"}"))
Login(writer, request)
assert.Equal(test, http.StatusUnauthorized, writer.Code)
assert.Equal(test, "Erreur lors de l'authentification pour le user : otherUser", writer.Body.String())
assert.Empty(test, writer.Header().Get("Authorization"))
}
func TestLoginFailedOnIncorrectPassword(test *testing.T) {
initCollections()
insertUserAndAnnouncement("<EMAIL>", "tutu")
writer := httptest.NewRecorder()
request, _ := http.NewRequest("POST", "localhost:8080/authentication?id=54f070908d7d4f1bfdb7a9dd", strings.NewReader("{\"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\"}"))
Login(writer, request)
assert.Equal(test, "Erreur lors de l'authentification pour le user : <EMAIL>", writer.Body.String())
assert.Empty(test, writer.Header().Get("Authorization"))
}
func insertUserAndAnnouncement(username string, password string) {
collections, session := configuration.GetAnnouncementCollection()
defer session.Close()
collections.Insert(Announcement{Id: bson.ObjectIdHex("54f070908d7d4f1bfdb7a9dd"), Account: &Account{Email: username, Password: EncryptSHA256(password)}})
}
func initCollections() {
configuration.Conf = new(configuration.TestConfiguration)
collections, session := configuration.GetAnnouncementCollection()
defer session.Close()
collections.DropCollection()
}
<file_sep>/static/js/notify.js
function notifySuccess(title, message) {
notify('success', title, message);
}
function notifyInfo(title, message) {
notify('info', title, message, 4000);
}
function notifyWarning(title, message) {
notify('warning', title, message);
}
function notifyError(title, message) {
notify('danger', title, message);
}
function notify(type, title, message, delay) {
$.notify({
// options
icon: 'glyphicon glyphicon-warning-sign',
title: '<strong>'+title+'</strong><br/>',
message: message
},{
// settings
element: 'body',
position: null,
type: type,
allow_dismiss: true,
newest_on_top: false,
placement: {
from: "top",
align: "right"
},
offset: 20,
spacing: 10,
z_index: 5031,
delay: delay ? delay : 6000,
timer: 1000,
url_target: '_blank',
animate: {
enter: 'animated fadeInDown',
exit: 'animated fadeOutUp'
},
icon_type: 'class',
template: '<div id="notification-popin" data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
'<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
'<span data-notify="icon"></span> ' +
'<span data-notify="title">{1}</span> ' +
'<span data-notify="message">{2}</span>' +
'</div>'
});
}<file_sep>/configuration/configuration_struct.go
package configuration
import (
"io/ioutil"
"launchpad.net/goyaml"
"log"
"os"
"path/filepath"
)
type Configuration interface {
GetDatabase() Database
GetKeys() Keys
GetMail() Mails
GetUrl() string
loadConfiguration()
GetFilePath(filename string) string
}
type FileConfiguration struct {
Db Database
Key Keys
Mail Mails
Url string
}
func (conf *FileConfiguration) loadConfiguration() {
buffer, err := ioutil.ReadFile(conf.GetFilePath(CONF_FILENAME))
if err != nil {
log.Fatalf("Erreur dans le chargement de la configuration.", err.Error())
}
goyaml.Unmarshal(buffer, conf)
}
func (conf *FileConfiguration) GetFilePath(filename string) string {
folder, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatalf("Erreur dans le path du fichier. %s", err.Error())
}
return folder + "/" + filename
}
func (conf *FileConfiguration) GetDatabase() Database {
return conf.Db
}
func (conf *FileConfiguration) GetKeys() Keys {
return conf.Key
}
func (conf *FileConfiguration) GetMail() Mails {
return conf.Mail
}
func (conf *FileConfiguration) GetUrl() string {
return conf.Url
}
type TestConfiguration struct{}
func (conf *TestConfiguration) loadConfiguration() {}
func (conf *TestConfiguration) GetFilePath(filename string) string {
return filename
}
func (conf *TestConfiguration) GetDatabase() Database {
return Database{"localhost", "reunion", "test", "test"}
}
func (conf *TestConfiguration) GetMail() Mails {
return Mails{"test@test", "<EMAIL>"}
}
func (conf *TestConfiguration) GetUrl() string {
return "localhost:8080"
}
func (conf *TestConfiguration) GetKeys() Keys {
return Keys{Private: "../token/private_key", Public: "../token/public_key"}
}
<file_sep>/minify/css_test.go
package minify
import (
"github.com/stretchr/testify/assert"
"io/ioutil"
"reunion/configuration"
"testing"
)
func TestMinifyContentCss(test *testing.T) {
minified := Minify(".test { color: red; }", urlCss)
assert.Equal(test, ".test{color:red}", minified)
}
func TestMinifyCssFromFile(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
file, _ := ioutil.TempFile("", "")
file.WriteString(".test { color: red; }")
MinifyCss(file.Name())
assert.Equal(test, ".test{color:red}", MinifiedContents["styles"])
}
<file_sep>/websocket/websocket.go
package websocket
import (
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"net/url"
)
const WS_URL = "http://localhost:8080"
var connections = make(map[*websocket.Conn]bool)
var wsHeaders = http.Header{
"Origin": {WS_URL},
"Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
}
func sendAll(msg []byte) {
for conn := range connections {
if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
delete(connections, conn)
conn.Close()
}
}
}
func WsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
if _, ok := err.(websocket.HandshakeError); ok {
http.Error(w, "Not a websocket handshake", 400)
return
} else if err != nil {
log.Panicln(err)
}
connections[conn] = true
for {
_, msg, err := conn.ReadMessage()
if err != nil {
delete(connections, conn)
conn.Close()
return
}
sendAll(msg)
}
}
func SendNotification(writer http.ResponseWriter, request *http.Request, object interface{}) {
wsUrl, err := url.Parse(WS_URL + "/socket")
wsConn, resp, err := websocket.NewClient(getRawUrl(wsUrl), wsUrl, wsHeaders, 1024, 1024)
if err != nil {
log.Panicf("websocket.NewClient Error: %s\nResp:%+v", err, resp)
}
defer wsConn.Close()
wsConn.WriteJSON(object)
}
func getRawUrl(wsUrl *url.URL) net.Conn {
rawConn, err := net.Dial("tcp", wsUrl.Host)
if err != nil {
log.Panicln(err)
}
return rawConn
}
<file_sep>/announcement/admin.go
package announcement
import (
"html/template"
"io/ioutil"
"log"
"net/http"
"reunion/configuration"
"reunion/token"
)
type SecureHandler func(writer http.ResponseWriter, request *http.Request)
func (fn SecureHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
currentToken := request.Header.Get("Authorization")
if !token.Verify(currentToken) {
log.Printf("Opération non autorisée : %s", currentToken)
writer.WriteHeader(http.StatusUnauthorized)
return
}
fn(writer, request)
}
func GetAdminHandler(writer http.ResponseWriter, request *http.Request) {
if request.Method == "GET" {
tmpl := template.Must(template.New("base").Delims("[[", "]]").ParseFiles(configuration.Conf.GetFilePath("static/html/admin.html"), configuration.Conf.GetFilePath("static/html/base.html")))
page := Page{name: "annonce", Title: "Administration"}
error := tmpl.Execute(writer, page)
if error != nil {
log.Panicf("Erreur lors de la construction du template : %s", error.Error())
}
} else {
log.Printf("Opération non autorisée : %s", request.Method)
writer.WriteHeader(http.StatusMethodNotAllowed)
}
}
func GetAdminAnnouncementsHandler(writer http.ResponseWriter, request *http.Request) {
if request.Method == "GET" {
writer.WriteHeader(http.StatusOK)
writer.Write(GetAnnouncementsTemplate())
} else {
log.Printf("Opération non autorisée : %s", request.Method)
writer.WriteHeader(http.StatusMethodNotAllowed)
}
}
func GetAnnouncementsTemplate() []byte {
content, err := ioutil.ReadFile(configuration.Conf.GetFilePath("static/html/announcements_admin.html"))
if err != nil {
log.Panicf("Erreur lors de la récupération du template : %s", err.Error())
}
return content
}
func GetAdminLostActionHandler(writer http.ResponseWriter, request *http.Request) {
if request.Method == "PUT" {
id, err := getId(request.URL.RequestURI(), 5)
if state := request.URL.Query().Get("state"); err == nil && state != "" {
UnrestrictedUpdateState(id, state)
} else {
log.Printf("Paramètre manquant : %s", request.URL.RequestURI())
if err != nil {
log.Printf("Paramètre manquant : %s", err.Error())
}
writer.WriteHeader(http.StatusBadRequest)
}
} else {
log.Printf("Opération non autorisée : %s", request.Method)
writer.WriteHeader(http.StatusMethodNotAllowed)
}
}
<file_sep>/announcement/specy/specy_test.go
package specy
import (
"github.com/stretchr/testify/assert"
"labix.org/v2/mgo"
"reunion/configuration"
"testing"
)
func TestGetSpeciesOfDog(test *testing.T) {
configuration.Conf = new(configuration.TestConfiguration)
collection := GetSpecyCollection("species")
collection.DropCollection()
collection.Insert(Specy{Name: "Race 1", Picture: "test.jpg", Animal: "Chien"})
collection.Insert(Specy{Name: "Race 2", Picture: "test.jpg", Animal: "Chat"})
species := GetSpecies()
assert.Len(test, species, 2)
assert.Equal(test, Specy{Name: "Race 1", Picture: "test.jpg", Animal: "Chien"}, species[0])
assert.Equal(test, Specy{Name: "Race 2", Picture: "test.jpg", Animal: "Chat"}, species[1])
}
func GetSpecyCollection(collectionName string) *mgo.Collection {
dbConf := configuration.GetConfiguration().GetDatabase()
session, _ := mgo.Dial(dbConf.Url)
database := session.DB(dbConf.Name)
database.Login(dbConf.Username, dbConf.Password)
collection := database.C(collectionName)
return collection
}
<file_sep>/cache/cache.go
package cache
import (
"crypto/md5"
"encoding/hex"
"net/http"
"strconv"
)
type CacheHeader struct {
MaxAge int
}
func checkETag(request *http.Request, newETagHash string) bool {
return newETagHash == request.Header.Get("If-None-Match")
}
func AddHttpCacheContent(writer http.ResponseWriter, request *http.Request, responseContent []byte) {
newETagHash := addCacheHeader(writer, CacheHeader{MaxAge: 0}, responseContent)
if checkETag(request, newETagHash) {
writer.WriteHeader(http.StatusNotModified)
} else {
writer.WriteHeader(http.StatusOK)
writer.Write(responseContent)
}
}
func addCacheHeader(writer http.ResponseWriter, cacheHeader CacheHeader, responseContent []byte) (eTagHash string) {
writer.Header().Add("Cache-Control", "max-age="+strconv.Itoa(cacheHeader.MaxAge))
hash := md5.New()
hash.Write(responseContent)
eTagHash = hex.EncodeToString(hash.Sum(nil))
writer.Header().Add("ETag", eTagHash)
return eTagHash
}
<file_sep>/main.go
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
"os"
. "reunion/announcement"
"reunion/announcement/rss"
"reunion/announcement/specy"
"reunion/authentication"
. "reunion/compression"
"reunion/configuration"
"reunion/home"
"reunion/minify"
"reunion/websocket"
)
func main() {
configuration.NewInstance()
minify.MinifyJs("static/js/reunionctrl.js")
minify.MinifyJs("static/js/notify.js")
minify.MinifyJs("static/js/angular-locale_fr-fr.js")
minify.MinifyCss("static/css/reunion.css")
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(configuration.Conf.GetFilePath("static/")))))
http.Handle("/photos/", http.StripPrefix("/photos/", http.FileServer(http.Dir("/opt/animalove/photos/"))))
http.HandleFunc("/static/js/javascript-min.js", GziperHandler(minify.AppJsHandler, "application/javascript"))
http.HandleFunc("/static/css/styles-min.css", GziperHandler(minify.AppCssHandler, "text/css"))
http.HandleFunc("/rss.xml", rss.GetFile)
http.HandleFunc("/robots.txt", configuration.GetRobotsHandler)
http.HandleFunc("/sitemap.xml", configuration.GetSitemapHandler)
router := mux.NewRouter()
router.HandleFunc("/", home.GetPage)
router.HandleFunc("/animaux", GziperHandler(GetAnnouncementsPage, "text/html")).Methods("GET")
router.HandleFunc("/animaux/perdu/nouveau", GziperHandler(GetLostFormPage, "text/html")).Methods("GET")
router.HandleFunc("/animaux/errant/nouveau", GziperHandler(GetSeenFormPage, "text/html")).Methods("GET")
router.HandleFunc("/animaux/adopter/nouveau", GziperHandler(GetAdoptFormPage, "text/html")).Methods("GET")
router.HandleFunc("/animaux/id/{announcementId}", GziperHandler(GetAnnouncementPage, "text/html")).Methods("GET")
router.HandleFunc("/login", Login)
router.HandleFunc("/admin", GetAdminHandler)
router.HandleFunc("/admin/login", authentication.Login)
router.Handle("/admin/announcements", SecureHandler(GetAdminAnnouncementsHandler))
router.Handle("/ws/admin/announcements/id/", SecureHandler(GetAdminLostActionHandler))
router.Handle("/ws/admin/announcements/lost/all", SecureHandler(GetAllHandler))
router.HandleFunc("/socket", websocket.WsHandler).Methods("GET")
router.HandleFunc("/ws/mail", GetMailHandler).Methods("POST")
router.HandleFunc("/ws/species", specy.GetSpeciesHandler).Methods("GET")
router.HandleFunc("/ws/contact/message", GetContactMessageHandler).Methods("POST")
router.HandleFunc("/ws/animaux", GetAnnouncementsHandler).Methods("GET")
router.HandleFunc("/ws/animaux/{announcementType}", GetAnnouncementsHandler).Methods("GET")
router.HandleFunc("/ws/animaux/{announcementType}", CreateAnnouncementsHandler).Methods("POST")
router.Handle("/ws/animaux/id/{announcementId}", SecureHandler(GetLostActionHandler)).Methods("PUT")
router.HandleFunc("/ws/animaux/perdu/locations", GetLocationsHandler).Methods("PUT")
http.Handle("/", router)
fmt.Printf("Running on port %s...\n", os.Getenv("PORT"))
err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)
if err != nil {
fmt.Printf("Erreur au démarrage du serveur : %s\n", err.Error())
panic("Erreur au démarrage du serveur")
}
}
<file_sep>/announcement/announcement.go
package announcement
import (
"bytes"
"encoding/base64"
"encoding/xml"
"github.com/disintegration/imaging"
"image"
_ "image/gif"
"image/jpeg"
_ "image/png"
"io/ioutil"
. "labix.org/v2/mgo/bson"
"log"
"os/exec"
"regexp"
"reunion/announcement/specy"
"reunion/configuration"
"strings"
"time"
)
type Announcement struct {
XMLName xml.Name `bson:"-" xml:"item"`
Id ObjectId `bson:"_id,omitempty" xml:"-"`
Name string `xml:"title,omitempty"`
Description string `xml:"description,omitempty"`
City, PhoneNumber, Sex string `xml:",omitempty"`
Color, Animal string `xml:",omitempty"`
Type string `xml:"-"`
Picture string `xml:"-"`
State string `xml:"-"`
CreationDate, LostDate *time.Time `xml:",omitempty"`
Account *Account `xml:",omitempty"`
Specy *specy.Specy `xml:",omitempty"`
Link string `xml:"link,omitempty"`
Locations []*Location `bson:"locations,omitempty" json:",omitempty"`
}
type Location struct {
Latitude, Longitude float64
Date time.Time `json:",omitempty"`
}
type Page struct {
name, Title, Description, Image, Link string
}
func (announcement *Announcement) GetLink() string {
return configuration.Conf.GetUrl() + "/animaux/id/" + announcement.Id.Hex()
}
func (announcement *Announcement) GetImageLink() string {
return configuration.Conf.GetUrl() + "/photos/" + announcement.Picture
}
func GetAnnouncementsByType(typeAnnouncement string, offset int, limit int) ([]Announcement, int) {
announcements := []Announcement{}
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
filter := M{"state": M{"$in": []string{"validated", "waiting for validation", "found"}}}
if typeAnnouncement != "" {
filter["type"] = typeAnnouncement
}
if err := collection.Find(M{"$and": []interface{}{filter}}).Sort("-creationdate").Skip(offset).Limit(limit).All(&announcements); err != nil {
log.Panicf("Erreur lors de la récupération des annonces : %s", err.Error())
}
total, err := collection.Find(filter).Count()
if err != nil {
log.Panicf("Erreur lors de la récupération du nombre total d'annonces : %s", err.Error())
}
return announcements, total
}
func GetAll(offset int, limit int, state string) []Announcement {
announcements := []Announcement{}
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
if err := collection.Find(M{"state": state}).Sort("-creationdate").Skip(offset).Limit(limit).All(&announcements); err != nil {
log.Panicf("Erreur lors de la récupération des annonces : %s", err.Error())
}
return announcements
}
func Find(criteria string, offset int, limit int) (announcements []Announcement, total int) {
regexp := RegEx{Pattern: `.*` + criteria + `.*`, Options: "i"}
matches := M{"$and": []interface{}{M{"state": M{"$in": []string{"validated", "waiting for validation", "found"}}}, M{"$or": []interface{}{M{"description": regexp}, M{"name": regexp}, M{"city": regexp}, M{"type": regexp}, M{"color": regexp}, M{"specy.name": regexp}, M{"animal": regexp}, M{"phonenumber": regexp}}}}}
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
if err := collection.Find(matches).Sort("-creationdate").Skip(offset).Limit(limit).All(&announcements); err != nil {
log.Panicf("Erreur lors de la récupération des annonces : %s", err.Error())
}
total, err := collection.Find(matches).Count()
if err != nil {
log.Panicf("Erreur lors de la récupération du nombre total d'annonces : %s", err.Error())
}
return announcements, total
}
func FindByCity(city string, offset int, limit int) (announcements []Announcement, total int) {
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
if err := collection.Find(M{"$and": []interface{}{M{"state": M{"$in": []string{"validated", "waiting for validation"}}}, M{"city": city}}}).Sort("-creationdate").Skip(offset).Limit(limit).All(&announcements); err != nil {
log.Panicf("Erreur lors de la récupération des annonces : %s", err.Error())
}
total, err := collection.Find(M{"$and": []interface{}{M{"state": M{"$in": []string{"validated", "waiting for validation"}}}, M{"city": city}}}).Count()
if err != nil {
log.Panicf("Erreur lors de la récupération du nombre total d'annonces : %s", err.Error())
}
return announcements, total
}
func FindById(id string) (announcement Announcement) {
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
if err := collection.Find(M{"_id": ObjectIdHex(id)}).One(&announcement); err != nil {
log.Panicf("Erreur lors de la récupération de l'annonce : %s", err.Error())
}
return announcement
}
func Create(announcement *Announcement) {
now := time.Now()
announcement.CreationDate = &now
announcement.State = "waiting for validation"
announcement.Account.Password = <PASSWORD>SHA256(announcement.Account.Password)
announcement.Picture = saveImage(announcement.Picture)
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
if err := collection.Insert(announcement); err != nil {
log.Panicf("Erreur lors de l'ajout d'une nouvelle annonce : %s", err.Error())
}
sendMail(Mail{Sender: configuration.Conf.GetMail().Contact, Recipient: configuration.Conf.GetMail().Admin}, "Un nouvel animal perdu a été publié : "+announcement.CreationDate.String()+" \nVoici son email :"+announcement.Account.Email)
sendMail(Mail{Sender: configuration.Conf.GetMail().Contact, Recipient: announcement.Account.Email}, "Bonjour,\n\nNous vous confirmons la publication de l'animal perdu sur AnimaLove.\nVoici le lien vers cet animal : "+announcement.GetLink())
}
func saveImage(imageContent string) string {
if imageContent == "" {
return ""
}
uuid, err := exec.Command("uuidgen", "-r").Output()
if err != nil {
log.Panicf("Erreur dans la génération du nom du fichier : %s", err.Error())
}
pictureName := strings.Replace(string(uuid), "\n", "", 1) + ".jpeg"
picture := compressAndResizeImage(imageContent)
ioutil.WriteFile("/opt/animalove/photos/"+pictureName, picture, 0664)
return pictureName
}
func compressAndResizeImage(pictureInString string) []byte {
if pictureInString == "" {
return nil
}
compile := regexp.MustCompile("data:image/.+;base64,")
pictureWithoutHeader := compile.ReplaceAllString(pictureInString, "")
pictureInBytes := make([]byte, base64.StdEncoding.DecodedLen(len(pictureWithoutHeader)))
_, err := base64.StdEncoding.Decode(pictureInBytes, []byte(pictureWithoutHeader))
if err != nil {
log.Panicf("Erreur lors de la compression de l'image : %s", err.Error())
}
picture, _, err := image.Decode(bytes.NewReader(pictureInBytes))
if err != nil {
log.Panicf("Erreur lors de la compression de l'image : %s", err.Error())
}
resizedImage := picture
ratio := picture.Bounds().Dx() / 400
if ratio > 0 {
resizedImage = imaging.Resize(picture, picture.Bounds().Dx()/ratio, picture.Bounds().Dy()/ratio, imaging.NearestNeighbor)
}
var buffer bytes.Buffer
jpeg.Encode(&buffer, resizedImage, &jpeg.Options{Quality: 60})
return buffer.Bytes()
}
func AddLocation(announcement Announcement) {
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
err := collection.UpdateId(announcement.Id, M{"$set": M{"locations": announcement.Locations}})
if err != nil {
log.Panicf("Erreur lors de la modification des localisations : %s", err.Error())
}
mailContent := Mail{Sender: configuration.Conf.GetMail().Contact, Recipient: announcement.Account.Email}
sendMail(mailContent, "Bonjour,\n\nQuelqu'un a localisé votre animal sur la carte \nVous pouvez la consulter sur ce lien : "+announcement.GetLink())
}
func UpdateState(announcementId ObjectId, state string) {
if state != "deleted" && state != "found" && state != "adopted" {
log.Panicf("Statut de la demande de mise à jour invalide")
}
UnrestrictedUpdateState(announcementId, state)
}
func UnrestrictedUpdateState(announcementId ObjectId, state string) {
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
if err := collection.UpdateId(announcementId, M{"$set": M{"state": state}}); err != nil {
log.Panicf("Erreur lors de la modification de l'état d'une annonce : %s", err.Error())
}
}
<file_sep>/static/js/maps.js
var mapRaphael = angular.module('mapRaphael',[]);
mapRaphael.factory('mapFactory', function() {
return map;
});
mapRaphael.directive('map', function ($rootScope, $window) {
function createRapha(element) {
var width = $('#map-wrapper').outerWidth(false);
var paper = new Raphael(element, '100%', '100%');
var attr = {
fill: "#F4EAD6",
stroke: "#CC5C3C",
"stroke-width": 1,
"stroke-linejoin": "round"
};
paper.canvas.setAttribute('viewBox', '62 59 978 900');
paper.canvas.setAttribute('preserveAspectRatio', 'xMinYMin meet');
paper.canvas.setAttribute('class', 'svg-content');
$.get('/static/svg/reunion.svg', function(svg) {
var map = {};
$(svg).find('path').each(function (index, region) {
var path = $(region).attr('d');
var id = $(region).attr('id');
map[id] = paper.path(path).attr(attr);
});
$rootScope.$broadcast('map-data-ok', map);
});
}
$rootScope.$on('map-data-ok', function (event, toDraw) {
for (var state in toDraw) {
toDraw[state].color = "#000";
(function (st, state) {
st[0].id = state;
st[0].style.cursor = "pointer";
st[0].onmouseover = function () {
st.animate({fill: "#F9C866", stroke: "#CC5C3C"}, 300);
$rootScope.$broadcast('map-mouseover', st[0]);
};
st[0].onmouseout = function () {
st.animate({fill: "#F4EAD6", stroke: "#CC5C3C"}, 300);
$rootScope.$broadcast('map-mouseout', st[0]);
};
st[0].onmouseup = function () {
$rootScope.$broadcast('map-mouseup', st[0]);
};
st[0].onmousedown = function () {
$rootScope.$broadcast('map-mousedown', st[0]);
};
})( toDraw[state], state);
}
});
return function (scope, element, attrs) {
createRapha(element[0]);
};
});
<file_sep>/authentication/authentication_test.go
package authentication
import (
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"reunion/configuration"
"strings"
"testing"
)
func TestLoginSuccessWithEncryptedPassword(test *testing.T) {
initCollections()
insertUser("toto@toto", "<PASSWORD>")
writer := httptest.NewRecorder()
request, _ := http.NewRequest("POST", "localhost:8080/authentication", strings.NewReader("{\"Email\": \"toto@toto\", \"Password\": \"<PASSWORD>\"}"))
Login(writer, request)
assert.Equal(test, http.StatusOK, writer.Code)
assert.NotEmpty(test, writer.Header().Get("Authorization"))
}
func TestLoginIsMethodNotAllowedWhenItIsNotPostMethod(test *testing.T) {
initCollections()
insertUser("toto@toto", "<PASSWORD>")
writer := httptest.NewRecorder()
request, _ := http.NewRequest("PUT", "localhost:8080/authentication", strings.NewReader("{\"Email\": \"toto@toto\", \"Password\": \"<PASSWORD>\"}"))
Login(writer, request)
assert.Equal(test, http.StatusMethodNotAllowed, writer.Code)
assert.Empty(test, writer.Header().Get("Authorization"))
}
func TestLoginFailedOnIncorrectUsername(test *testing.T) {
initCollections()
insertUser("toto@toto", "<PASSWORD>")
writer := httptest.NewRecorder()
request, _ := http.NewRequest("POST", "localhost:8080/authentication", strings.NewReader("{\"Email\": \"otherUser\", \"Password\": \"<PASSWORD>\"}"))
Login(writer, request)
assert.Equal(test, http.StatusUnauthorized, writer.Code)
assert.Empty(test, writer.Header().Get("Authorization"))
}
func TestLoginFailedOnIncorrectPassword(test *testing.T) {
initCollections()
insertUser("toto@toto", "<PASSWORD>")
writer := httptest.NewRecorder()
request, _ := http.NewRequest("POST", "localhost:8080/authentication", strings.NewReader("{\"Email\": \"t<EMAIL>\", \"Password\": \"<PASSWORD>\"}"))
Login(writer, request)
assert.Equal(test, http.StatusUnauthorized, writer.Code)
assert.Empty(test, writer.Header().Get("Authorization"))
}
func insertUser(username string, password string) {
collections := configuration.GetUserCollection()
collections.Insert(User{Email: "t<EMAIL>", Password: Encrypt<PASSWORD>(password)})
}
func initCollections() {
configuration.Conf = new(configuration.TestConfiguration)
collections := configuration.GetUserCollection()
collections.DropCollection()
}
<file_sep>/minify/javascript_test.go
package minify
import (
"github.com/stretchr/testify/assert"
"io/ioutil"
"testing"
)
func TestMinifyContentJs(test *testing.T) {
minified := Minify("var test = 'essai' ; console.log( test ) ;", urlJs)
assert.Equal(test, "var test=\"essai\";console.log(test);", minified)
}
func TestMinifyJsFromFile(test *testing.T) {
file, _ := ioutil.TempFile("", "")
file.WriteString("var test = 'essai' ; console.log( test ) ;")
MinifyJs(file.Name())
assert.Equal(test, "var test=\"essai\";console.log(test);", MinifiedContents["javascript"])
}
<file_sep>/announcement/mail.go
package announcement
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"labix.org/v2/mgo/bson"
"log"
"net/http"
"net/smtp"
"reunion/configuration"
)
type MailRequest struct {
Sender, Message, AnnouncementId string
}
type Mail struct {
Sender, Recipient, Message string
}
func GetContactMessageHandler(writer http.ResponseWriter, request *http.Request) {
var mail = Mail{Recipient: configuration.Conf.GetMail().Contact}
parseBody(request, &mail)
if mail.Sender == "" || mail.Message == "" {
log.Panicf("Paramètre manquant, Sender : %s, Message : %s", mail.Sender, mail.Message)
}
sendMail(mail, "Bonjour,\n\nVoici un message envoyé de la part de : "+mail.Sender+"\n\n"+mail.Message)
}
func GetMailHandler(writer http.ResponseWriter, request *http.Request) {
var mailRequest = MailRequest{}
parseBody(request, &mailRequest)
if mailRequest.AnnouncementId == "" || mailRequest.Message == "" {
log.Panicf("Paramètre manquant, announcementId : %s, message : %s", mailRequest.AnnouncementId, mailRequest.Message)
}
mail := Mail{Message: mailRequest.Message, Sender: mailRequest.Sender}
var announcement Announcement
collection, session := configuration.GetAnnouncementCollection()
defer session.Close()
if err := collection.FindId(bson.ObjectIdHex(mailRequest.AnnouncementId)).One(&announcement); err == nil {
mail.Recipient = announcement.Account.Email
sendMail(mail, "Bonjour,\n\nVoici un message envoyé de la part de : "+mail.Sender+"\n\n"+mail.Message)
} else {
log.Panicf("Erreur lors de l'accès à la bdd : %s", err.Error())
}
}
func parseBody(request *http.Request, mailRequest interface{}) {
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Panicf("Erreur dans le contenu de la requête : %s", err.Error())
}
err = json.Unmarshal(body, mailRequest)
if err != nil {
log.Panicf("Erreur dans le contenu de la requête : %s", err.Error())
}
}
func sendMail(mailContent Mail, format string) {
header := make(map[string]string)
header["From"] = mailContent.Sender
header["To"] = mailContent.Recipient
header["Subject"] = "Site des animaux perdus - Message"
header["MIME-Version"] = "1.0"
header["Content-Type"] = "text/plain; charset=\"utf-8\""
header["Content-Transfer-Encoding"] = "base64"
var message string
for key, value := range header {
message += fmt.Sprintf("%s: %s\r\n", key, value)
}
message += "\r\n" + base64.StdEncoding.EncodeToString([]byte(format+"\n\nAnimaLove\n"+configuration.Conf.GetUrl()))
auth := smtp.PlainAuth("", configuration.Conf.GetMail().Contact, "animalove311212", "smtp.animalove.re")
err := smtp.SendMail("smtp.animalove.re:587", auth, configuration.Conf.GetMail().Contact, []string{mailContent.Recipient}, []byte(message))
if err != nil {
log.Printf("Erreur lors l'envoi de mail : %s", err.Error())
}
}
<file_sep>/configuration/configuration.go
package configuration
const CONF_FILENAME = "configuration.yml"
var Conf Configuration
type Database struct {
Url, Name, Username, Password string
}
type Keys struct {
Private, Public string
}
type Mails struct {
Admin, Contact string
}
func NewInstance() {
Conf = new(FileConfiguration)
Conf.loadConfiguration()
}
func GetConfiguration() Configuration {
return Conf
}
<file_sep>/minify/javascript.go
package minify
import (
"net/http"
)
var urlJs = "http://javascript-minifier.com/raw"
func MinifyJs(filepath string) {
MinifyFromFile(filepath, urlJs, "javascript")
}
func AppJsHandler(writer http.ResponseWriter, request *http.Request) {
write(writer, "javascript")
}
| 36a5868c45b35632f1ee2a014c0ac9126d325677 | [
"JavaScript",
"Go",
"Shell"
] | 35 | Go | aporthos974/animalove974 | 40b1da63e139bf91949960a123541ac6de028e54 | e707afd3129829aab73f650249da93f5cbad7b0d |
refs/heads/master | <repo_name>jki00129/js-deli-counter-bootcamp-prep-000<file_sep>/index.js
function takeANumber(line, name){
var katzDeli = [];
line.push(name)
}
function takeANumber(deliLine,name){
var katzDeli = [];
deliLine.push(name)
return "Welcome, " + name + ". You are number " + deliLine.length + " in line."
}
function nowServing (deliLine){
var name;
if(deliLine.length === 0){
return "There is nobody waiting to be served!"
}
name = deliLine.shift()
return "Currently serving "+ name + "."
}
function currentLine(deliLine){
if(deliLine.length === 0){
return "The line is currently empty."
} else {
var myString = `The line is currently: 1. ${deliLine[0]}`
for(let i = 1; i<deliLine.length;i++){
myString += `, ${i+1}. ${deliLine[i]}`
}
return myString
}
}
| cb85c84a1d3fd528b0afa42df493fde51731eb76 | [
"JavaScript"
] | 1 | JavaScript | jki00129/js-deli-counter-bootcamp-prep-000 | a9240af16ad3d53c76e78f138790bbabaee9f0b9 | 81f4f435f4411ce7c8dd81be7d505e2f2378dba5 |
refs/heads/master | <file_sep>package com.example.dummydictionary;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import com.example.dummydictionary.util.VerticalSpacingItemDecorator;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class DictionaryActivity extends AppCompatActivity
{
private static final String TAG = "DictionaryActivity";
private RecyclerView mRecyclerView;
private FloatingActionButton mFab;
private SwipeRefreshLayout mSwipeRefresh;
private Handler mMainThreadHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onRestoreInstanceState(savedInstanceState);
setContentView(R.layout.activity_dictionary);
mRecyclerView = findViewById(R.id.recyclerView);
mFab = findViewById(R.id.fab);
mSwipeRefresh = findViewById(R.id.swipe_refresh);
mFab.setOnClickListener(this);
mSwipeRefresh.setOnRefreshListener(this);
mMainThreadHandler = new Handler(this);
setupRecyclerView();
}
ItemTouchHelper.SimpleCallback itemTouchHelperCallback
= new ItemTouchHelper.SimpleCallback(0, ) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
}
private void setupRecyclerView() {
Log.d(TAG, "setupRecyclerView: called.");
LinearLayoutManager linearLayoutManager
= new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
VerticalSpacingItemDecorator itemDecorator
= new VerticalSpacingItemDecorator(10);
mRecyclerView.addItemDecoration(itemDecorator);
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView();
}
}
<file_sep># A dummy dictionary
<file_sep>include ':app'
rootProject.name='Dummy Dictionary'
| 3a2f81e413e39727e76678c68902e9df8c634fe7 | [
"Markdown",
"Java",
"Gradle"
] | 3 | Java | khalidtouch/DummyDict | a9adb6eb919b90192efb1e82aeedd052ce2d33be | 6785e4fa1b56f02ddf0150b57951cbc6c476498c |
refs/heads/master | <repo_name>tsal/token<file_sep>/multi_token_test.go
package token
import (
"log"
"math/rand"
"sync"
"testing"
"time"
)
var useTestParallel = true
func TestTok0(t *testing.T) {
if useTestParallel {
t.Parallel()
}
tks := NewTokenChan(1, "")
tks.Get("fred")
log.Println("Got a token for fred")
tks.Put("fred")
log.Println("Returned Fred")
tks.Get("fred")
log.Println("Got a token for fred")
tks.Put("fred")
log.Println("Returned Fred")
}
func TestTok00(t *testing.T) {
if useTestParallel {
t.Parallel()
}
tks := NewTokenChan(1, "")
tks.Get("")
log.Println("Got a token for es")
tks.Put("")
log.Println("Returned es")
tks.Get("")
log.Println("Got a token for es")
tks.Put("")
log.Println("Returned es")
}
func TestTok1(t *testing.T) {
if useTestParallel {
t.Parallel()
}
tks := NewTokenChan(1, "")
tks.Get("fred")
log.Println("Got a token for fred")
tks.Get("bob")
log.Println("Got a token for bob")
tks.Put("fred")
log.Println("Returned Fred")
tks.Put("bob")
log.Println("Returned Bob")
tks.Get("fred")
log.Println("Got a token for fred")
tks.Put("fred")
log.Println("Returned Fred")
}
func TestTok2(t *testing.T) {
if useTestParallel {
t.Parallel()
}
tks := NewTokenChan(1, "")
tks.Get("fred")
log.Println("Got a token for fred")
tks.Get("bob")
log.Println("Got a token for bob")
tks.Put("bob")
log.Println("Returned Bob")
tks.Put("fred")
log.Println("Returned Fred")
tks.Get("fred")
log.Println("Got a token for fred")
tks.Put("fred")
log.Println("Returned Fred")
}
func TestTok3(t *testing.T) {
if useTestParallel {
t.Parallel()
}
var wg sync.WaitGroup
tks := NewTokenChan(1, "")
tks.Get("fred")
log.Println("Got a token for fred")
tks.Get("bob")
log.Println("Got a token for bob")
wg.Add(1)
go func() {
tks.Get("bob")
log.Println("Got another token for bob")
tks.Put("bob")
log.Println("Returned Bob")
wg.Done()
}()
tks.Put("fred")
log.Println("Returned Fred")
tks.Put("bob")
log.Println("Returned Bob")
tks.Get("fred")
log.Println("Got a token for fred")
tks.Put("fred")
log.Println("Returned Fred")
wg.Wait()
}
func TestTok4(t *testing.T) {
var wg sync.WaitGroup
if useTestParallel {
t.Parallel()
}
tks := NewTokenChan(1, "")
tks.Get("fred")
log.Println("Got a token for fred")
tks.Get("bob")
log.Println("Got a token for bob")
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
tks.Get("bob")
log.Println("Got another token for bob")
tks.Put("bob")
log.Println("Returned Bob")
wg.Done()
}()
}
tks.Put("fred")
log.Println("Returned Fred")
tks.Put("bob")
log.Println("Returned Bob")
wg.Wait()
tks.Get("fred")
log.Println("Got a token for fred")
tks.Put("fred")
log.Println("Returned Fred")
}
func TestTok5(t *testing.T) {
if useTestParallel {
t.Parallel()
}
var wg sync.WaitGroup
tks := NewTokenChan(1, "")
tks.Get("fred")
log.Println("Got a token for fred")
tks.Get("bob")
log.Println("Got a token for bob")
numLoops := 100
wg.Add(numLoops)
for i := 0; i < numLoops; i++ {
go func() {
tks.Get("bob")
log.Println("Got another token for bob")
yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)
tks.Put("bob")
log.Println("Returned Bob")
wg.Done()
}()
}
tks.Put("fred")
log.Println("Returned Fred")
tks.Put("bob")
log.Println("Returned Bob")
wg.Wait()
tks.Get("fred")
log.Println("Got a token for fred")
tks.Put("fred")
log.Println("Returned Fred")
}
func TestTok6(t *testing.T) {
if useTestParallel {
t.Parallel()
}
var wg sync.WaitGroup
domains := []string{"bob", "fred", "steve", "wibble"}
locks := make([]int, len(domains))
tks := NewTokenChan(1, "")
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
randTok := rand.Intn(4)
tokenAct := domains[randTok]
tks.Get(tokenAct)
//log.Println("Got a token for ", token_act)
if locks[randTok] == 0 {
locks[randTok] = 1
} else {
log.Fatal("Bugger, We've been given the lock for someone else's data")
}
yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)
if locks[randTok] == 1 {
locks[randTok] = 0
} else {
log.Fatal("Bugger, someone else messed with it while we had the lock")
}
tks.Put(tokenAct)
//log.Println("Returned ", token_act)
wg.Done()
}()
}
wg.Wait()
}
func TestTok7(t *testing.T) {
if useTestParallel {
t.Parallel()
}
var wg sync.WaitGroup
domains := []string{"bob", "fred", "steve", "wibble"}
locks := make([]int, 4)
maxProcs := 2
tks := NewTokenChan(maxProcs, "")
for i := 0; i < 100; i++ {
wg.Add(1)
var masterLock sync.Mutex
go func() {
randTok := rand.Intn(4)
tokenAct := domains[randTok]
tks.Get(tokenAct)
log.Println("Got another token for ", tokenAct)
masterLock.Lock()
if locks[randTok] < maxProcs {
locks[randTok]++
} else {
log.Fatalf("Domain:%s,%v\n", tokenAct, locks)
}
masterLock.Unlock()
yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)
masterLock.Lock()
if locks[randTok] <= maxProcs {
locks[randTok]--
} else if locks[randTok] == 0 {
log.Fatal("Decrement of zero")
} else {
log.Fatalf("Release Domain:%s,%v\n", tokenAct, locks)
}
masterLock.Unlock()
tks.Put(tokenAct)
log.Println("Returned ", tokenAct)
wg.Done()
}()
}
wg.Wait()
}
<file_sep>/work_token_test.go
package token
import (
"log"
"testing"
"time"
)
func TestWorkToken0(t *testing.T) {
wt := NewWkTok(10)
wt.Get()
log.Println("Got")
wt.Put()
log.Println("Put")
log.Println("Waiting")
wt.Wait()
}
func TestWorkToken1(t *testing.T) {
wt := NewWkTok(10)
wt.Get()
wt.Put()
log.Println("Waiting")
wt.Wait()
}
func TestWorkToken2(t *testing.T) {
wt := NewWkTok(10)
wt.Get()
go func() {
<-time.After(1 * time.Second)
wt.Put()
}()
log.Println("Waiting")
wt.Wait()
}
func TestWorkToken3(t *testing.T) {
wt := NewWkTok(2)
wt.Get()
log.Println("Got")
wt.Get()
log.Println("Got")
wt.Put()
log.Println("Put")
wt.Get()
log.Println("Got")
go func() {
<-time.After(1 * time.Second)
wt.Put()
log.Println("Put")
}()
go func() {
<-time.After(2 * time.Second)
wt.Put()
log.Println("Put")
}()
log.Println("Waiting")
wt.Wait()
}
func TestWorkToken4(t *testing.T) {
wt := NewWkTok(2)
wt.Get()
log.Println("Got")
wt.Get()
log.Println("Got")
go func() {
<-time.After(1 * time.Second)
wt.Put()
log.Println("Put")
}()
go func() {
<-time.After(2 * time.Second)
wt.Put()
log.Println("Put")
}()
wt.Get()
log.Println("Got")
wt.Put()
log.Println("Put")
log.Println("Waiting")
wt.Wait()
}
<file_sep>/README.md
# token
Manage work tokens
<file_sep>/multi_token.go
package token
import (
"log"
"sync"
)
// MultiToken is used to check that we have a limited number of things happening at once
type MultiToken struct {
sync.Mutex
name string
maxCnt int
array map[string]*WkTok
}
// NewTokenChan creates a new token chan tracker
func NewTokenChan(numTokens int, name string) *MultiToken {
var itm MultiToken
itm.array = make(map[string]*WkTok)
itm.name = name
itm.maxCnt = numTokens
return &itm
}
func (tc *MultiToken) getWk(basename string) *WkTok {
tc.Lock()
val, ok := tc.array[basename]
if !ok {
val = NewWkTok(tc.maxCnt)
tc.array[basename] = val
}
tc.Unlock()
return val
}
// Get get a token for the supplied basename
// blocks until it suceeds
func (tc *MultiToken) Get(basename string) {
if basename == "" {
return
}
tc.getWk(basename).Get()
}
// TryGet attempts to get a token
// return true if it got a token
// returns false if it fails
// does not block
func (tc *MultiToken) TryGet(basename string) bool {
if basename == "" {
return true
}
// This is a variant of Get that doesn't block
// it returns true if it can give you a token
// false otherwise
//log.Printf("Token requested for \"%v\"\n", basename)
return tc.getWk(basename).TryGet()
}
// Put returns the token after use
func (tc *MultiToken) Put(basename string) {
if basename == "" {
return
}
_, ok := tc.array[basename]
if !ok {
log.Fatal("Tried to put a token that doesn't exist", basename)
}
tc.getWk(basename).Put()
}
// TryPut alias to allow consustent naming
func (tc *MultiToken) TryPut(basename string) {
tc.Put(basename)
}
// Exist - Check if the basename exists
func (tc *MultiToken) Exist(urx string) bool {
tc.Lock()
_, ok := tc.array[urx]
tc.Unlock()
return ok
}
<file_sep>/work_token.go
package token
import (
"sync"
)
//WkTok is a work token - Wait for a token before working
type WkTok struct {
sync.Mutex
cnt int
maxCount int
broadcastChan chan struct{}
waitChan chan struct{}
}
// NewWkTo creates a work token that you can get and put for
func NewWkTok(cnt int) *WkTok {
itm := new(WkTok)
itm.maxCount = cnt
itm.broadcastChan = make(chan struct{})
return itm
}
func (wt *WkTok) qTok() bool {
its := wt.cnt < wt.maxCount
//fmt.Println("qTok", its)
return its
}
// Wait for all wokens to complete
func (wt *WkTok) Wait() {
wt.Lock()
if wt.waitChan == nil {
wt.waitChan = make(chan struct{})
}
if wt.cnt == 0 {
wt.Unlock()
} else {
wt.Unlock()
<-wt.waitChan
}
}
// Get waits until we get a token
func (wt *WkTok) Get() {
wt.Lock()
wt.loopToken() // loop until we can increment
wt.cnt++
wt.Unlock()
}
// TryGet tries to get a token, returns true if suceeds
func (wt *WkTok) TryGet() bool {
wt.Lock()
defer wt.Unlock()
if wt.qTok() {
wt.cnt++
return true
}
return false
}
// TryPut always succeeds
func (wt *WkTok) TryPut() {
wt.Put()
}
// Put says we have finished with the token, put it back
func (wt *WkTok) Put() {
wt.Lock()
wt.cnt--
// one of possibly many receivers will get this
go func() {
select {
case wt.broadcastChan <- struct{}{}:
//default:
}
}()
defer wt.Unlock()
if (wt.cnt == 0) && (wt.waitChan != nil) {
close(wt.waitChan)
wt.waitChan = nil
}
}
// loopToken loops waiting for a token
func (wt *WkTok) loopToken() {
// Stay in here until the entry does not exist
for success := wt.qTok(); !success; success = wt.qTok() {
wt.Unlock()
// when we get a message
// There may be many of us waiting
<-wt.broadcastChan
// Get the lock
wt.Lock()
// and go around again. This time we should succeed
}
}
| 53a3d2955950eed8af711d64833163d1c4f431c9 | [
"Markdown",
"Go"
] | 5 | Go | tsal/token | ee9045c34caf5447ecfc4974b609d260c6cce6e4 | 4837e1e444f2c33855c90be51d9ad6a4cab64bd0 |
refs/heads/master | <repo_name>TinaMehra15/LearnAutomation<file_sep>/src/com/test/AutomateTestCase.java
package com.test;
//Import All the packages
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import com.pages.OpenBrowser;
import com.pages.CloseBrowser;
import com.pages.HomePage;
public class AutomateTestCase {
//DECLERATION OF ALL THE VARIABLES
WebDriver driver;
HomePage objHomePage;
CloseBrowser objCloseBrowser;
@Test(priority=1)
public void firstScenario()
{
//Open the browser
driver = OpenBrowser.startBrowser();
//Search for the jobType Permanent and get the total count
objHomePage = new HomePage(driver);
objHomePage.scenario1();
//Quit the browser
objCloseBrowser = new CloseBrowser(driver);
objCloseBrowser.QuitBrowser();
}
@Test(priority=2)
public void secondScenario()
{
//Open the browser
driver = OpenBrowser.startBrowser();
//Scenario2 functionality
objHomePage = new HomePage(driver);
objHomePage.scenario2();
//Quit the browser
objCloseBrowser = new CloseBrowser(driver);
objCloseBrowser.QuitBrowser();
}
}<file_sep>/src/com/pages/OpenBrowser.java
package com.pages;
import org.apache.http.impl.SocketHttpServerConnection;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class OpenBrowser {
static WebDriver driver;
public static WebDriver startBrowser()
{
String path = System.getProperty("user.dir");
System.out.println("The path is :" + path);
System.setProperty("webdriver.chrome.driver",path+"/resources/chromedriver");
//System.setProperty("webdriver.chrome.driver","/Users/tina.mehra/Documents/chromedriver");
driver= new ChromeDriver();
String appURL = "https://www.cwjobs.co.uk/";
driver.get(appURL);
return driver;
//System.out.println();
}
}
| 0e1259ae1180de718df4a71a4b422283b5666f58 | [
"Java"
] | 2 | Java | TinaMehra15/LearnAutomation | 72f5b32391a2a1bcc0cdf18c185a5668859b9032 | 2ac6d89740e0e925f6434fe9dba45d97dc7e1de8 |
refs/heads/master | <file_sep>// example of async handler using async-await
// https://github.com/netlify/netlify-lambda/issues/43#issuecomment-444618311
import fetch from "node-fetch";
export async function handler(event) {
try {
const { searchTerm, location } = event.queryStringParameters || {};
console.log("searching: ", { searchTerm, location });
const allJobs = await fetchGithub(searchTerm, location);
return {
statusCode: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ jobs: allJobs })
};
} catch (err) {
console.log(err); // output to netlify function log
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }) // Could be a custom message or object i.e. JSON.stringify(err)
};
}
}
async function fetchGithub(searchTerm, location) {
const query = searchTerm
.trim()
.toLowerCase()
.split(" ")
.filter(word => word.length > 1)
.join("+");
const loc = location
.trim()
.toLowerCase()
.split(" ")
.filter(word => word.length > 1)
.join("+");
const baseURL = `https://jobs.github.com/positions.json?description=${query}&location=${loc}`;
console.log({ query, loc, baseURL });
let resultCount = 1;
let currentPage = 0;
const allJobs = [];
// fetch all jobs from all pages
console.log("Fetching Github...");
while (resultCount > 0) {
const res = await fetch(`${baseURL}&page=${currentPage}`);
const jobs = await res.json();
allJobs.push(...jobs);
resultCount = jobs.length;
currentPage++;
console.log(`page: ${currentPage}, got ${resultCount} jobs`);
}
console.log(`got a total of ${allJobs.length} jobs (UNFILTERED)`);
// filter algorithm
const jrJobs = allJobs.filter(job => {
const jobTitle = job.title.toLowerCase();
const isSenior = jobTitle.includes("sr.") || jobTitle.includes("senior");
const isManager = jobTitle.includes("manager");
const isArchitect = jobTitle.includes("architect");
if (isSenior || isManager || isArchitect) {
return false;
}
return true;
});
// sort by date
const monthMap = {
Jan: "01",
Feb: "02",
Mar: "03",
Apr: "04",
May: "05",
Jun: "06",
Jul: "07",
Aug: "08",
Sep: "09",
Oct: "10",
Nov: "11",
Dec: "12"
};
const sortedJobs = jrJobs.sort((a, b) => {
let splitDateA = a.created_at.split(" ").splice(1);
let splitDateB = b.created_at.split(" ").splice(1);
let [monthA, dayA, , , yearA] = splitDateA;
let [monthB, dayB, , , yearB] = splitDateB;
let dateA = new Date(`${yearA}-${monthMap[monthA]}-${dayA}Z`);
let dateB = new Date(`${yearB}-${monthMap[monthB]}-${dayB}Z`);
if (dateA < dateB) {
return 1;
} else {
return -1;
}
});
// remove duplicates
function removeDuplicatesBy(keyFn, array) {
let mySet = new Set();
return array.filter(el => {
let key = keyFn(el);
let isNew = !mySet.has(key);
if (isNew) {
mySet.add(key);
}
return isNew;
});
}
const sortedUniqueJobs = removeDuplicatesBy(job => job.id, sortedJobs);
console.log(`got a total of ${sortedUniqueJobs.length} jobs (FILTERED)`);
console.log("fetching complete");
return sortedUniqueJobs;
}
<file_sep>import React from "react";
import { Paper, Typography } from "@material-ui/core";
import style from "./Job.module.scss";
function Job({ job, onClick }) {
return (
<Paper onClick={onClick} className={style.job}>
<div className={style.info}>
<Typography variant="h5">{job.title}</Typography>
<Typography variant="h6">{job.company}</Typography>
<Typography>{job.location}</Typography>
</div>
<div className={style.date}>
<Typography>
{job.created_at
.split(" ")
.slice(0, 3)
.join(" ")}
</Typography>
</div>
</Paper>
);
}
export default Job;
<file_sep>import React from "react";
import { Typography, AppBar, Toolbar, Slide } from "@material-ui/core";
import useScrollTrigger from "@material-ui/core/useScrollTrigger";
import { makeStyles } from "@material-ui/core/styles";
import IconButton from "@material-ui/core/IconButton";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faGithub } from "@fortawesome/free-brands-svg-icons";
import style from "./Header.module.scss";
const useStyles = makeStyles(theme => ({
title: {
flexGrow: 1
},
link: {
color: "black"
}
}));
function HideOnScroll(props) {
const { children, window } = props;
const trigger = useScrollTrigger({ target: window ? window() : undefined });
return (
<Slide appear={false} direction="down" in={!trigger}>
{children}
</Slide>
);
}
export default function Header(props) {
const classes = useStyles();
return (
<>
<div className={style.header}>
<HideOnScroll {...props}>
<AppBar className={style.appBar}>
<Toolbar>
<Typography variant="h6" className={classes.title}>
Job Finder
</Typography>
<a
href="https://github.com/nicmeriano/job-board"
rel="noopener noreferrer"
target="_blank"
className={classes.link}
>
<IconButton
aria-label="account of current user"
aria-controls="menu-appbar"
aria-haspopup="true"
color="inherit"
>
<FontAwesomeIcon icon={faGithub} />
</IconButton>
</a>
</Toolbar>
</AppBar>
</HideOnScroll>
</div>
<div className={style.wrapper}>
<Typography
variant="h3"
component="h1"
gutterBottom={true}
className={style.title}
>
Entry level software jobs
</Typography>
<Typography
variant="h4"
component="p"
gutterBottom={true}
className={style.paragraph}
>
All in one place
</Typography>
</div>
</>
);
}
<file_sep>import React, { useState } from "react";
import {
AppBar,
Toolbar,
Button,
Paper,
InputBase,
IconButton,
TextField
} from "@material-ui/core";
import SearchIcon from "@material-ui/icons/Search";
import { makeStyles } from "@material-ui/styles";
import style from "./SearchBar.module.scss";
const useStyles = makeStyles({
root: {
background: "#70D5AF",
border: "2px solid #70D5AF",
boxShadow: "none",
color: "white",
flex: 1,
"&:hover": {
background: "transparent",
color: "#70D5AF"
}
},
textField: {
flex: 2,
"&:hover fieldset": {
borderColor: "#70D5AF !important"
},
"& label.Mui-focused": {
color: "#70D5AF"
}
},
cssLabel: {},
cssOutlinedInput: {
height: "100%",
"&$cssFocused $notchedOutline": {
borderColor: `#70D5AF !important`
}
},
cssFocused: {},
notchedOutline: {
borderWidth: "1px",
borderColor: "rgba(0, 0, 0, .2)"
},
toolbar: {
background: "white"
},
appBar: {
boxShadow: "1px 2px 5px 2px rgba(0,0,0,0.1)"
}
});
function SearchBar({ updateSearchTerm, updateLocation }) {
const [search, setSearch] = useState("");
const [location, setLocation] = useState("");
const classes = useStyles();
return (
<>
<AppBar position="static" color="default" className={classes.appBar}>
<Toolbar className={classes.toolbar}>
<div className={style.formWrapper}>
<form className={style.form}>
<div className={style.search}>
<Paper className={style.inputWrapper}>
<IconButton className={style.iconButton} aria-label="search">
<SearchIcon />
</IconButton>
<InputBase
className={style.input}
placeholder="Job title, keywords, or company"
onChange={e => {
setSearch(e.target.value);
}}
/>
</Paper>
</div>
<div className={style.spacer} />
<div className={style.filters}>
<TextField
className={classes.textField}
variant="outlined"
label="Location"
onChange={e => {
setLocation(e.target.value);
}}
InputLabelProps={{
classes: {
root: classes.cssLabel,
focused: classes.cssFocused
}
}}
InputProps={{
classes: {
root: classes.cssOutlinedInput,
focused: classes.cssFocused,
notchedOutline: classes.notchedOutline
}
}}
/>
<div className={style.spacer} />
<Button
className={classes.root}
color="primary"
size="large"
type="submit"
onClick={e => {
e.preventDefault();
updateSearchTerm(search);
updateLocation(location);
}}
>
search
</Button>
</div>
</form>
</div>
</Toolbar>
</AppBar>
</>
);
}
export default SearchBar;
<file_sep>import React, { useState, useEffect } from "react";
import Header from "./components/Header";
import SearchBar from "./components/SearchBar";
import JobList from "./components/JobList";
import Loader from "./components/Loader";
import { Container } from "@material-ui/core";
import "./App.css";
async function fetchJobs(searchTerm, location, loading) {
loading(true);
const LAMBDA_API = `/.netlify/functions/async-jobs?searchTerm=${searchTerm}&location=${location}`;
const res = await fetch(LAMBDA_API);
let data;
try {
data = await res.json();
} catch (e) {
data = { jobs: [] };
}
loading(false);
return data.jobs;
}
function App() {
const [jobList, updateJobs] = useState([]);
const [searchTerm, updateSearchTerm] = useState("");
const [location, updateLocation] = useState("");
const [isLoading, updateLoading] = useState(true);
useEffect(() => {
fetchJobs(searchTerm, location, updateLoading).then(updateJobs);
}, [searchTerm, location]);
return (
<Container maxWidth="lg">
<Header />
<SearchBar
updateSearchTerm={updateSearchTerm}
updateLocation={updateLocation}
/>
{isLoading ? <Loader /> : <JobList jobs={jobList} />}
</Container>
);
}
export default App;
| f6ff55fdd14acf706527756956c4b6a9c59c6d3c | [
"JavaScript"
] | 5 | JavaScript | nicmeriano/job-board | 3ab64af8c3fe733efdab758a6efc3b58e3cac300 | 68c6e36d42e8991e75640d92863cfd46bfc6e724 |
refs/heads/master | <repo_name>skyerider/pxt-generic-sensors<file_sep>/README.md
# makecode扩展包,用于在micro:bit上使用一些常用的元器件
这个扩展用于帮助师生们不受限制的在各种micro:bit扩展板上使用常用的电子模块,仅限教育用途
## License
Licensed under the MIT License (MIT). See LICENSE file for more details.
<file_sep>/main.ts
enum PingUnit {
//% block="厘米"
Centimeters,
//% block="英寸"
Inches
}
enum RgbColors {
//% block=红色
Red = 0xFF0000,
//% block=橙色
Orange = 0xFFA500,
//% block=黄色
Yellow = 0xFFFF00,
//% block=绿色
Green = 0x00FF00,
//% block=蓝色
Blue = 0x0000FF,
//% block=靛蓝色
Indigo = 0x4b0082,
//% block=紫罗兰色
Violet = 0x8a2be2,
//% block=紫色
Purple = 0xFF00FF,
//% block=白色
White = 0xFFFFFF,
//% block=熄灭
Black = 0x000000
}
enum RgbUltrasonics {
//% block=左
Left = 0x00,
//% block=右
Right = 0x01,
//% block=全部
All = 0x02
}
enum ColorEffect {
//% block=无
None = 0x00,
//% block=呼吸灯
Breathing = 0x01,
//% block=旋转灯
Rotate = 0x02,
//% block=闪烁
Flash = 0x03
}
enum DHT11Type {
//% block="温度(℃)"
DHT11_temperature_C = 0,
//% block="湿度(0~100)"
DHT11_humidity = 1,
}
enum _selectpin {
//% block="A引脚"
Apin = 0,
//% block="B引脚"
Bpin = 1,
//% block="D引脚"
Dpin = 2,
}
// enum RemoteButton {
// //% block=A
// A = 0x45,
// //% block=B
// B = 0x46,
// //% block=C
// C = 0x47,
// //% block=D
// D = 0x44,
// //% block=UP
// UP = 0x40,
// //% block=+
// Add = 0x43,
// //% block=LEFT
// Left = 0x07,
// //% block=OK
// Ok = 0x15,
// //% block=RIGHT
// Right = 0x09,
// //% block=DOWN
// Down = 0x19,
// //% block=-
// EQ = 0x0d,
// //% block=0
// NUM0 = 0x16,
// //% block=1
// NUM1 = 0x0c,
// //% block=2
// NUM2 = 0x18,
// //% block=3
// NUM3 = 0x5e,
// //% block=4
// NUM4 = 0x8,
// //% block=5
// NUM5 = 0x1c,
// //% block=6
// NUM6 = 0x5a,
// //% block=7
// NUM7 = 0x42,
// //% block=8
// NUM8 = 0x52,
// //% block=9
// NUM9 = 0x4A,
// }
enum IrPins {
P0 = 3,
P1 = 2,
P2 = 1,
P3 = 4,
P4 = 5,
P5 = 17,
P6 = 12,
P7 = 11,
P8 = 18,
P9 = 10,
P10 = 6,
P11 = 26,
P12 = 20,
P13 = 23,
P14 = 22,
P15 = 21,
P16 = 16,
P19 = 0,
P20 = 30,
}
enum _rockerpin {
//% block="X引脚"
Xpin = 0,
//% block="Y引脚"
Ypin = 1
}
enum ledon_off {
//% block="开启"
_on = 1,
//% block="关闭"
_off = 0,
}
enum on_off {
//% block="打开"
_on = 1,
//% block="关闭"
_off = 0,
}
enum _selectlight {
//% block="_yellow"
_yellow = 0,
//% block="_red"
_red = 1,
//% block="_green"
_green = 2,
}
enum _selectcolor {
//% block="_blue"
_blue = 0,
//% block="_red"
_red = 1,
//% block="_green"
_green = 2,
}
enum run_turn {
//% block="向前"
forward = 0,
//% block="向后"
reverse = 1,
}
enum LcdBacklight {
//% block="打开"
_on = 1,
//% block="关闭"
_off = 0,
}
enum Item {
//% block="打开"
_on = 1,
//% block="关闭"
_off = 2,
//% block="清除"
_clear = 3,
}
enum Select {
//% block="on"
_on = 0,
//% block="off"
_off = 1,
//% block="clear"
_clear = 2,
}
enum Mode {
//% block="LOOP"
LOOP_MODE = 0, // 循环模式
//% block="BUTTON"
BUTTON_MODE = 1, // 按键模式
//% block="KEYWORDS"
KEYWORDS_MODE = 2, // 关键字模式
//% block="KEYWORDS_AND"
KEYWORDS_AND_BUTTON = 3, //关键字加按键模式
}
enum barb_fitting {
//% block="左"
BUTOON_LEFT = 0,
//% block="右"
BUTOON_RIGHT = 1,
//% block="上"
BUTOON_UP = 2,
//% block="下"
BUTOON_DOWN = 3,
//% block="按下"
JOYSTICK_BUTTON = 4,
}
enum key_status {
//% block="按下"
PRESS_DOWN = 0, //按下
//% block="释放"
PRESS_UP = 1, //释放
//% block="单击"
SINGLE_CLICK = 3, //单击
//% block="双击"
DOUBLE_CLICK = 4, //双击
//% block="长按"
LONG_PRESS_HOLD = 6, //长按
//% block="未按下"
NONE_PRESS = 8, //未按
}
enum Shaft{
//% block="X"
X_Shaft = 0,
//% block="Y"
Y_Shaft = 1,
}
const enum IrButton {
//% block="任意"
Any = -1,
//% block="▲"
Up = 0x62,
//% block=" "
Unused_2 = -2,
//% block="◀"
Left = 0x22,
//% block="OK"
Ok = 0x02,
//% block="▶"
Right = 0xc2,
//% block=" "
Unused_3 = -3,
//% block="▼"
Down = 0xa8,
//% block=" "
Unused_4 = -4,
//% block="1"
Number_1 = 0x68,
//% block="2"
Number_2 = 0x98,
//% block="3"
Number_3 = 0xb0,
//% block="4"
Number_4 = 0x30,
//% block="5"
Number_5 = 0x18,
//% block="6"
Number_6 = 0x7a,
//% block="7"
Number_7 = 0x10,
//% block="8"
Number_8 = 0x38,
//% block="9"
Number_9 = 0x5a,
//% block="*"
Star = 0x42,
//% block="0"
Number_0 = 0x4a,
//% block="#"
Hash = 0x52,
}
const enum IrButtonAction {
//% block="按下"
Pressed = 0,
//% block="释放"
Released = 1,
}
const enum IrProtocol {
//% block="Keyestudio"
Keyestudio = 0,
//% block="NEC"
NEC = 1,
}
//% color=#0fbc11 weight=10 icon="\u272a" block="创之翼工具箱"
//% category="创之翼工具箱"
namespace makerbit {
let irState: IrState;
const MICROBIT_MAKERBIT_IR_NEC = 777;
const MICROBIT_MAKERBIT_IR_DATAGRAM = 778;
const MICROBIT_MAKERBIT_IR_BUTTON_PRESSED_ID = 789;
const MICROBIT_MAKERBIT_IR_BUTTON_RELEASED_ID = 790;
const IR_REPEAT = 256;
const IR_INCOMPLETE = 257;
const IR_DATAGRAM = 258;
interface IrState {
protocol: IrProtocol;
hasNewDatagram: boolean;
bitsReceived: uint8;
addressSectionBits: uint16;
commandSectionBits: uint16;
hiword: uint16;
loword: uint16;
}
function appendBitToDatagram(bit: number): number {
irState.bitsReceived += 1;
if (irState.bitsReceived <= 8) {
irState.hiword = (irState.hiword << 1) + bit;
if (irState.protocol === IrProtocol.Keyestudio && bit === 1) {
// recover from missing message bits at the beginning
// Keyestudio address is 0 and thus missing bits can be detected
// by checking for the first inverse address bit (which is a 1)
irState.bitsReceived = 9;
irState.hiword = 1;
}
} else if (irState.bitsReceived <= 16) {
irState.hiword = (irState.hiword << 1) + bit;
} else if (irState.bitsReceived <= 32) {
irState.loword = (irState.loword << 1) + bit;
}
if (irState.bitsReceived === 32) {
irState.addressSectionBits = irState.hiword & 0xffff;
irState.commandSectionBits = irState.loword & 0xffff;
return IR_DATAGRAM;
} else {
return IR_INCOMPLETE;
}
}
function decode(markAndSpace: number): number {
if (markAndSpace < 1600) {
// low bit
return appendBitToDatagram(0);
} else if (markAndSpace < 2700) {
// high bit
return appendBitToDatagram(1);
}
irState.bitsReceived = 0;
if (markAndSpace < 12500) {
// Repeat detected
return IR_REPEAT;
} else if (markAndSpace < 14500) {
// Start detected
return IR_INCOMPLETE;
} else {
return IR_INCOMPLETE;
}
}
function enableIrMarkSpaceDetection(pin: DigitalPin) {
pins.setPull(pin, PinPullMode.PullNone);
let mark = 0;
let space = 0;
pins.onPulsed(pin, PulseValue.Low, () => {
// HIGH, see https://github.com/microsoft/pxt-microbit/issues/1416
mark = pins.pulseDuration();
});
pins.onPulsed(pin, PulseValue.High, () => {
// LOW
space = pins.pulseDuration();
const status = decode(mark + space);
if (status !== IR_INCOMPLETE) {
control.raiseEvent(MICROBIT_MAKERBIT_IR_NEC, status);
}
});
}
/**
* Connects to the 红外接收模块 module at the specified pin and configures the IR protocol.
* @param pin 红外接收模块 pin, eg: DigitalPin.P0
* @param protocol IR protocol, eg: IrProtocol.Keyestudio
*/
//% subcategory="红外接收模块"
//% blockId="makerbit_infrared_connect_receiver"
//% block="连接红外接收模块到引脚 %pin 解码方式 %protocol"
//% pin.fieldEditor="gridpicker"
//% pin.fieldOptions.columns=4
//% pin.fieldOptions.tooltips="false"
//% weight=90
export function connectIrReceiver(
pin: DigitalPin,
protocol: IrProtocol
): void {
if (irState) {
return;
}
irState = {
protocol: protocol,
bitsReceived: 0,
hasNewDatagram: false,
addressSectionBits: 0,
commandSectionBits: 0,
hiword: 0, // TODO replace with uint32
loword: 0,
};
enableIrMarkSpaceDetection(pin);
let activeCommand = -1;
let repeatTimeout = 0;
const REPEAT_TIMEOUT_MS = 120;
control.onEvent(
MICROBIT_MAKERBIT_IR_NEC,
EventBusValue.MICROBIT_EVT_ANY,
() => {
const irEvent = control.eventValue();
// Refresh repeat timer
if (irEvent === IR_DATAGRAM || irEvent === IR_REPEAT) {
repeatTimeout = input.runningTime() + REPEAT_TIMEOUT_MS;
}
if (irEvent === IR_DATAGRAM) {
irState.hasNewDatagram = true;
control.raiseEvent(MICROBIT_MAKERBIT_IR_DATAGRAM, 0);
const newCommand = irState.commandSectionBits >> 8;
// Process a new command
if (newCommand !== activeCommand) {
if (activeCommand >= 0) {
control.raiseEvent(
MICROBIT_MAKERBIT_IR_BUTTON_RELEASED_ID,
activeCommand
);
}
activeCommand = newCommand;
control.raiseEvent(
MICROBIT_MAKERBIT_IR_BUTTON_PRESSED_ID,
newCommand
);
}
}
}
);
control.inBackground(() => {
while (true) {
if (activeCommand === -1) {
// sleep to save CPU cylces
basic.pause(2 * REPEAT_TIMEOUT_MS);
} else {
const now = input.runningTime();
if (now > repeatTimeout) {
// repeat timed out
control.raiseEvent(
MICROBIT_MAKERBIT_IR_BUTTON_RELEASED_ID,
activeCommand
);
activeCommand = -1;
} else {
basic.pause(REPEAT_TIMEOUT_MS);
}
}
}
});
}
/**
* Do something when a specific button is pressed or released on the remote control.
* @param button the button to be checked
* @param action the trigger action
* @param handler body code to run when the event is raised
*/
//% subcategory="红外接收模块"
//% blockId=makerbit_infrared_on_ir_button
//% block="当红外接收模块按钮 | %button | %action"
//% button.fieldEditor="gridpicker"
//% button.fieldOptions.columns=3
//% button.fieldOptions.tooltips="false"
//% weight=50
export function onIrButton(
button: IrButton,
action: IrButtonAction,
handler: () => void
) {
control.onEvent(
action === IrButtonAction.Pressed
? MICROBIT_MAKERBIT_IR_BUTTON_PRESSED_ID
: MICROBIT_MAKERBIT_IR_BUTTON_RELEASED_ID,
button === IrButton.Any ? EventBusValue.MICROBIT_EVT_ANY : button,
() => {
handler();
}
);
}
/**
* Returns the code of the IR button that was pressed last. Returns -1 (IrButton.Any) if no button has been pressed yet.
*/
//% subcategory="红外接收模块"
//% blockId=makerbit_infrared_ir_button_pressed
//% block="红外接收模块按钮"
//% weight=70
export function irButton(): number {
basic.pause(0); // Yield to support background processing when called in tight loops
if (!irState) {
return IrButton.Any;
}
return irState.commandSectionBits >> 8;
}
/**
* Do something when an IR datagram is received.
* @param handler body code to run when the event is raised
*/
//% subcategory="红外接收模块"
//% blockId=makerbit_infrared_on_ir_datagram
//% block="当红外接收模块收到数据包"
//% weight=40
export function onIrDatagram(handler: () => void) {
control.onEvent(
MICROBIT_MAKERBIT_IR_DATAGRAM,
EventBusValue.MICROBIT_EVT_ANY,
() => {
handler();
}
);
}
/**
* Returns the IR datagram as 32-bit hexadecimal string.
* The last received datagram is returned or "0x00000000" if no data has been received yet.
*/
//% subcategory="红外接收模块"
//% blockId=makerbit_infrared_ir_datagram
//% block="红外接收模块数据包"
//% weight=30
export function irDatagram(): string {
basic.pause(0); // Yield to support background processing when called in tight loops
if (!irState) {
return "0x00000000";
}
return (
"0x" +
ir_rec_to16BitHex(irState.addressSectionBits) +
ir_rec_to16BitHex(irState.commandSectionBits)
);
}
/**
* Returns true if any IR data was received since the last call of this function. False otherwise.
*/
//% subcategory="红外接收模块"
//% blockId=makerbit_infrared_was_any_ir_datagram_received
//% block="红外接收模块收到数据"
//% weight=80
export function wasIrDataReceived(): boolean {
basic.pause(0); // Yield to support background processing when called in tight loops
if (!irState) {
return false;
}
if (irState.hasNewDatagram) {
irState.hasNewDatagram = false;
return true;
} else {
return false;
}
}
/**
* Returns the command code of a specific IR button.
* @param button the button
*/
//% subcategory="红外接收模块"
//% blockId=makerbit_infrared_button_code
//% button.fieldEditor="gridpicker"
//% button.fieldOptions.columns=3
//% button.fieldOptions.tooltips="false"
//% block="红外接收模块按钮代码 %button"
//% weight=60
export function irButtonCode(button: IrButton): number {
basic.pause(0); // Yield to support background processing when called in tight loops
return button as number;
}
function ir_rec_to16BitHex(value: number): string {
let hex = "";
for (let pos = 0; pos < 4; pos++) {
let remainder = value % 16;
if (remainder < 10) {
hex = remainder.toString() + hex;
} else {
hex = String.fromCharCode(55 + remainder) + hex;
}
value = Math.idiv(value, 16);
}
return hex;
}
let initialized = false
let emRGBLight: EMRGBLight.EmakefunRGBLight;
let matBuf = pins.createBuffer(17);
let distanceBuf = 0;
/**
* Get RUS04 distance
* @param pin Microbit ultrasonic pin; eg: P2
*/
//% blockId=Ultrasonic block="从引脚 %pin 上的RGB超声波模块获取距离(cm)" group="RGB超声波"
//% weight=76
//% inlineInputMode=inline
//% subcategory="传感器"
export function Ultrasonic(pin: DigitalPin): number {
pins.setPull(pin, PinPullMode.PullNone);
pins.digitalWritePin(pin, 0);
control.waitMicros(2);
pins.digitalWritePin(pin, 1);
control.waitMicros(50);
pins.digitalWritePin(pin, 0);
control.waitMicros(1000);
while(!pins.digitalReadPin(pin));
// read pulse
let d = pins.pulseIn(pin, PulseValue.High, 25000);
let ret = d;
// filter timeout spikes
if (ret == 0 && distanceBuf != 0) {
ret = distanceBuf;
}
distanceBuf = d;
//return d;
return Math.floor(ret * 9 / 6 / 58);
//return Math.floor(ret / 40 + (ret / 800));
// Correction
}
function RgbDisplay(indexstart: number, indexend: number, rgb: RgbColors): void {
for (let i = indexstart; i <= indexend; i++) {
emRGBLight.setPixelColor(i, rgb);
}
emRGBLight.show();
}
export function rus04_rgb(pin: DigitalPin, offset: number, index: number, rgb: number, effect: number): void {
let start = 0, end = 0;
if (!emRGBLight) {
emRGBLight = EMRGBLight.create(pin, offset+6, EMRGBPixelMode.RGB)
}
if(offset>=4){
if (index == RgbUltrasonics.Left) {
start = 0;
end = 2;
} else if (index == RgbUltrasonics.Right) {
start = 3;
end = 5;
} else if (index == RgbUltrasonics.All) {
start = 0;
end = 5;
}
}
start += offset;
end += offset;
switch (effect) {
case ColorEffect.None:
RgbDisplay(start, end, rgb);
break;
case ColorEffect.Breathing:
for (let i = 0; i < 255; i += 2) {
emRGBLight.setBrightness(i);
RgbDisplay(start, end, rgb);
//basic.pause((255 - i)/2);
basic.pause((i < 20) ? 80 : (255 / i));
}
for (let i = 255; i > 0; i -= 2) {
emRGBLight.setBrightness(i);
RgbDisplay(start, end, rgb);
basic.pause((i < 20) ? 80 : (255 / i));
}
break;
case ColorEffect.Rotate:
for (let i = 0; i < 4; i++) {
emRGBLight.setPixelColor(start, rgb);
emRGBLight.setPixelColor(start + 1, 0);
emRGBLight.setPixelColor(start + 2, 0);
if (index == RgbUltrasonics.All) {
emRGBLight.setPixelColor(end - 2, rgb);
emRGBLight.setPixelColor(end - 1, 0);
emRGBLight.setPixelColor(end, 0);
}
emRGBLight.show();
basic.pause(150);
emRGBLight.setPixelColor(start, 0);
emRGBLight.setPixelColor(start + 1, rgb);
emRGBLight.setPixelColor(start + 2, 0);
if (index == RgbUltrasonics.All) {
emRGBLight.setPixelColor(end - 2, 0);
emRGBLight.setPixelColor(end - 1, rgb);
emRGBLight.setPixelColor(end, 0);
}
emRGBLight.show();
basic.pause(150);
emRGBLight.setPixelColor(start, 0);
emRGBLight.setPixelColor(start + 1, 0);
emRGBLight.setPixelColor(start + 2, rgb);
if (index == RgbUltrasonics.All) {
emRGBLight.setPixelColor(end - 2, 0);
emRGBLight.setPixelColor(end - 1, 0);
emRGBLight.setPixelColor(end, rgb);
}
emRGBLight.show();
basic.pause(150);
}
RgbDisplay(4, 9, 0);
break;
case ColorEffect.Flash:
for (let i = 0; i < 6; i++) {
RgbDisplay(start, end, rgb);
basic.pause(150);
RgbDisplay(start, end, 0);
basic.pause(150);
}
break;
}
}
//% blockId="sensorbit_rus04" block="选择引脚%pin选择彩灯%index选择颜色%rgb选择效果%effect"
//% weight=75
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensorbit_rus04(pin: DigitalPin, index: RgbUltrasonics, rgb: RgbColors, effect: ColorEffect): void {
rus04_rgb(pin, 0, index, rgb, effect);
}
/**
* Send a ping and get the echo time (in microseconds) as a result
* @param trig tigger pin
* @param echo echo pin
* @param unit desired conversion unit
* @param maxCmDistance maximum distance in centimeters (default is 500)
*/
//% blockId="sensor_ping" block="trig引脚 %trig|echo引脚 %echo|单位 %unit" group="普通超声波"
//% weight=75
//% inlineInputMode=inline
//% subcategory="传感器"
export function ping(trig: DigitalPin, echo: DigitalPin, unit: PingUnit, maxCmDistance = 500): number {
// send pulse
pins.setPull(trig, PinPullMode.PullNone);
pins.digitalWritePin(trig, 0);
control.waitMicros(2);
pins.digitalWritePin(trig, 1);
control.waitMicros(10);
pins.digitalWritePin(trig, 0);
// read pulse
const d = pins.pulseIn(echo, PulseValue.High, maxCmDistance * 58);
switch (unit) {
case PingUnit.Centimeters: return Math.idiv(d, 58);
case PingUnit.Inches: return Math.idiv(d, 148);
default: return d;
}
}
//% blockId=actuator_buzzer0 block="有源蜂鸣器控制引脚 :%pin|状态 %status" group="有源蜂鸣器"
//% weight=70
//% subcategory="输出模块"
export function actuator_buzzer0(pin: DigitalPin, status: on_off): void {
pins.digitalWritePin(pin, status)
}
//% blockId=actuator_buzzer1 block="无源蜂鸣器控制引脚 :%pin|频率 %freq" group="无源蜂鸣器"
//% weight=70
//% subcategory="输出模块"
export function actuator_buzzer1(pin: AnalogPin, freq: number): void {
pins.analogWritePin(pin, freq)
}
//% blockId=actuator_relay block="继电器控制引脚 :%pin|状态 %status" group="继电器"
//% weight=70
//% subcategory="输出模块"
export function actuator_relay(pin: DigitalPin, status: on_off): void {
pins.digitalWritePin(pin, status)
}
//% blockId=actuator_motor_run block="微型直流电机转动 INA | %_INA | INB | %_INB | 方向 | %turn | 速度 %speed" group="直流电机"
//% weight=70
//% inlineInputMode=inline
//% speed.min=0 speed.max=255
//% subcategory="输出模块"
export function actuator_motor_run(_INA: AnalogPin, _INB: AnalogPin, turn: run_turn, speed: number): void {
if (turn == 0) {
pins.analogWritePin(_INA, 0)
pins.analogWritePin(_INB, speed)
} else if (turn == 1) {
pins.analogWritePin(_INA, speed)
pins.analogWritePin(_INB, 0)
}
}
/**
* 舵机
*/
//% blockId=actuator_servo block="180度微型舵机 %pin|转到角度 %angle" group="舵机"
//% angle.min=0 angle.max=180
//% weight=70
//% inlineInputMode=inline
//% subcategory="输出模块"
export function actuator_servo(pin: AnalogPin, angle: number): void {
let increment = 1
pins.servoWritePin(pin, angle)
angle = angle + increment
if (angle == 0)
increment = 1
else if (angle == 180)
increment = -1
basic.pause(100)
}
let _SDO = 0
let _SCL = 0
//% blockId=actuator_keyborad_pin block="触摸键盘初始化|SDA引脚 %SDO|SCL引脚 %SCL" group="触摸键盘"
//% weight=71
//% subcategory="基础输入模块"
export function actuator_keyborad_pin(SDA: DigitalPin, SCL: DigitalPin): void {
_SDO = SDA
_SCL = SCL
}
//% blockId=actuator_keyborad_read block="读取到的键盘值" group="触摸键盘"
//% weight=70
//% subcategory="基础输入模块"
export function actuator_keyborad_read(): string {
let DATA = 0
pins.digitalWritePin(_SDO, 1)
control.waitMicros(93)
pins.digitalWritePin(_SDO, 0)
control.waitMicros(10)
for (let i = 0; i < 16; i++) {
pins.digitalWritePin(_SCL, 1)
pins.digitalWritePin(_SCL, 0)
DATA |= pins.digitalReadPin(_SDO) << i
}
control.waitMicros(2 * 1000)
switch (DATA & 0xFFFF) {
case 0xFFFE: return "1"
case 0xFFFD: return "2"
case 0xFFFB: return "3"
case 0xFFEF: return "4"
case 0xFFDF: return "5"
case 0xFFBF: return "6"
case 0xFEFF: return "7"
case 0xFDFF: return "8"
case 0xFBFF: return "9"
case 0xDFFF: return "0"
case 0xFFF7: return "A"
case 0xFF7F: return "B"
case 0xF7FF: return "C"
case 0x7FFF: return "D"
case 0xEFFF: return "*"
case 0xBFFF: return "#"
default: return " "
}
}
//% blockId=setled block="设置LED灯引脚:%lpin|状态 %lstatus" group="LED灯"
//% weight=70
//% subcategory="输出模块"
export function setled(lpin: DigitalPin, lstatus: ledon_off): void {
pins.digitalWritePin(lpin, lstatus)
}
let _Rpins = 0
let _Gpins = 0
let _Bpins = 0
//% blockId=setrgbpin block="设置三色灯引脚|绿 %_GPin|蓝 %_BPin|红 %_RPin" group="三色灯"
//% weight=70
//% subcategory="输出模块"
export function setRGBpin(_GPin: DigitalPin, _BPin: DigitalPin, _RPin: DigitalPin): void {
_Gpins = _GPin
_Bpins = _BPin
_Rpins = _RPin
}
//% blockId=yledon block="设置颜色|红 %r_color|绿 %g_color|蓝 %b_color" group="三色灯"
//% r_color.min=0 r_color.max=255
//% g_color.min=0 g_color.max=255
//% b_color.min=0 b_color.max=255
//% weight=70
//% subcategory="输出模块"
export function selectcolor(r_color: number,g_color: number,b_color: number): void {
pins.analogWritePin(_Rpins,r_color)
pins.analogWritePin(_Gpins,g_color)
pins.analogWritePin(_Bpins,b_color)
}
let i2cAddr: number
let BK: number
let RS: number
function setreg(d: number) {
pins.i2cWriteNumber(i2cAddr, d, NumberFormat.Int8LE)
basic.pause(1)
}
function set(d: number) {
d = d & 0xF0
d = d + BK + RS
setreg(d)
setreg(d + 4)
setreg(d)
}
function lcdcmd(d: number) {
RS = 0
set(d)
set(d << 4)
}
function lcddat(d: number) {
RS = 1
set(d)
set(d << 4)
}
//% block="LCD1602显示屏初始化,地址 $addr" addr.defl="39" group="LCD1602显示屏"
//% subcategory="输出模块"
//% weight=70
export function i2cLcdInit(addr: number) {
i2cAddr = addr
BK = 8
RS = 0
lcdcmd(0x33)
basic.pause(5)
set(0x30)
basic.pause(5)
set(0x20)
basic.pause(5)
lcdcmd(0x28)
lcdcmd(0x0C)
lcdcmd(0x06)
lcdcmd(0x01)
}
//% block="第$y行第$x列显示字符$ch" group="LCD1602显示屏"
//% subcategory="输出模块"
//% weight=69
export function i2cLcdShowChar(y: number, x: number, ch: string): void {
let a: number
y = y - 1
if (y > 0)
a = 0xC0
else
a = 0x80
x = x - 1
a += x
lcdcmd(a)
lcddat(ch.charCodeAt(0))
}
//% block="第$y行第$x列显示数字$n" group="LCD1602显示屏"
//% subcategory="输出模块"
//% weight=68
export function i2cLcdShowNumber(y: number, x: number, n: number): void {
let s = n.toString()
i2cLcdShowString(y, x, s)
}
//% block="第$y行第$x列显示字符串$s" group="LCD1602显示屏"
//% subcategory="输出模块"
//% weight=67
export function i2cLcdShowString(y: number, x: number, s: string): void {
let a: number
y = y - 1
if (y > 0)
a = 0xC0
else
a = 0x80
x = x - 1
a += x
lcdcmd(a)
for (let i = 0; i < s.length; i++) {
lcddat(s.charCodeAt(i))
}
}
//% block="控制LCD1602显示屏 %item" group="LCD1602显示屏"
//% subcategory="输出模块"
//% weight=64
export function i2cLcdDisplay_Control(item: Item): void {
if (item == 1) {
lcdcmd(0x0C)
}
if (item == 2) {
lcdcmd(0x08)
}
if (item == 3) {
lcdcmd(0x01)
}
}
//% subcategory="输出模块" block="设置LCD1602显示屏背景光 %backlight" group="LCD1602显示屏"
//% blockId="seti2cLcdBacklight"
//% weight=79
export function seti2cLcdBacklight(backlight: LcdBacklight): void {
if (backlight == 1) {
BK = 8
lcdcmd(0)
}
if (backlight == 0) {
BK = 0
lcdcmd(0)
}
}
/**
* TM1637
*/
let TM1637_CMD1 = 0x40
let TM1637_CMD2 = 0xC0
let TM1637_CMD3 = 0x80
let _SEGMENTS = [0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71]
/**
* TM1637 LED display
*/
export class TM1637LEDs {
buf: Buffer
clk: DigitalPin
dio: DigitalPin
_ON: number
brightness: number
count: number // number of LEDs
/**
* initial TM1637
*/
init(): void {
pins.digitalWritePin(this.clk, 0)
pins.digitalWritePin(this.dio, 0)
this._ON = 8
this.buf = pins.createBuffer(this.count)
this.clear()
}
/**
* Start
*/
_start() {
pins.digitalWritePin(this.dio, 0)
pins.digitalWritePin(this.clk, 0)
}
/**
* Stop
*/
_stop() {
pins.digitalWritePin(this.dio, 0)
pins.digitalWritePin(this.clk, 1)
pins.digitalWritePin(this.dio, 1)
}
/**
* send command1
*/
_write_data_cmd() {
this._start()
this._write_byte(TM1637_CMD1)
this._stop()
}
/**
* send command3
*/
_write_dsp_ctrl() {
this._start()
this._write_byte(TM1637_CMD3 | this._ON | this.brightness)
this._stop()
}
/**
* send a byte to 2-wire interface
*/
_write_byte(b: number) {
for (let i = 0; i < 8; i++) {
pins.digitalWritePin(this.dio, (b >> i) & 1)
pins.digitalWritePin(this.clk, 1)
pins.digitalWritePin(this.clk, 0)
}
pins.digitalWritePin(this.clk, 1)
pins.digitalWritePin(this.clk, 0)
}
/**
* set TM1637 intensity, range is [0-8], 0 is off.
* @param val the brightness of the TM1637, eg: 7
*/
//% blockId="TM1637_set_intensity" block="%tm| 设置亮度 %val" group="TM1637数码管"
//% weight=88
//% parts="TM1637"
//% subcategory="输出模块"
//% val.max=8 val.min=0
intensity(val: number) {
if (val < 1) {
this.off()
return
}
if (val > 8) val = 8
this._ON = 8
this.brightness = val - 1
this._write_data_cmd()
this._write_dsp_ctrl()
}
/**
* set data to TM1637, with given bit
*/
_dat(bit: number, dat: number) {
this._write_data_cmd()
this._start()
this._write_byte(TM1637_CMD2 | (bit % this.count))
this._write_byte(dat)
this._stop()
this._write_dsp_ctrl()
}
/**
* show a number in given position.
* @param bit the position of the LED, eg: 0
* @param num number will show, eg: 5
*
*/
//% blockId="TM1637_showbit" block="%tm第 %bit 位显示数字 %num" group="TM1637数码管"
//% weight=90 blockGap=8
//% parts="TM1637"
//% bit.max=3 bit.min=0
//% subcategory="输出模块"
showbit(bit: number, num: number) {
this.buf[bit % this.count] = _SEGMENTS[num % 16]
this._dat(bit, _SEGMENTS[num % 16])
}
/**
* show a number.
* @param num is a number, eg: 0
*/
//% blockId="TM1637_shownum" block="%tm显示数字 %num" group="TM1637数码管"
//% weight=91 blockGap=8
//% parts="TM1637"
//% subcategory="输出模块"
showNumber(num: number) {
if (num < 0) {
this._dat(0, 0x40) // '-'
num = -num
}
else
this.showbit(0, (num / 1000) % 10)
this.showbit(3, num % 10)
this.showbit(2, (num / 10) % 10)
this.showbit(1, (num / 100) % 10)
}
/**
* show a hex number.
* @param num is a hex number, eg: 0
*/
//% blockId="TM1637_showhex" block="%tm显示十六进制数字%num" group="TM1637数码管"
//% weight=90 blockGap=8
//% parts="TM1637"
//% subcategory="输出模块"
showHex(num: number) {
if (num < 0) {
this._dat(0, 0x40) // '-'
num = -num
}
else
this.showbit(0, (num >> 12) % 16)
this.showbit(3, num % 16)
this.showbit(2, (num >> 4) % 16)
this.showbit(1, (num >> 8) % 16)
}
/**
* show or hide dot point.
* @param bit is the position,eg: 0
*
*/
//% blockId="TM1637_showDP" block="%tm| 点%bit|显示 %_status" group="TM1637数码管"
//% weight=70 blockGap=8
//% parts="TM1637"
//% subcategory="输出模块"
//% bit.max=3 bit.min=0
showDP(_status: ledon_off, bit: number) {
bit = bit % this.count
let show = _status == 1 ? true : false;
if (show) this._dat(bit, this.buf[bit] | 0x80)
else this._dat(bit, this.buf[bit] & 0x7F)
}
//% blockId="TM1637_clear" block="%tm清除显示" group="TM1637数码管"
//% weight=80 blockGap=8
//% parts="TM1637"
//% subcategory="输出模块"
clear() {
for (let i = 0; i < this.count; i++) {
this._dat(i, 0)
this.buf[i] = 0
}
}
//% blockId="TM1637_on" block="%tm打开显示" group="TM1637数码管"
//% weight=86 blockGap=8
//% parts="TM1637"
//% subcategory="输出模块"
on() {
this._ON = 8
this._write_data_cmd()
this._write_dsp_ctrl()
}
//% blockId="TM1637_off" block="%tm关闭显示" group="TM1637数码管"
//% weight=85 blockGap=8
//% parts="TM1637"
//% subcategory="输出模块"
off() {
this._ON = 0
this._write_data_cmd()
this._write_dsp_ctrl()
}
}
//% weight=99
//% blockId="TM1637_create" block="TM1637初始化CLK引脚%clk DIO引脚%dio亮度%intensityLED数量(1到4)%count" group="TM1637数码管"
//% inlineInputMode=inline
//% subcategory="输出模块"
//% intensity.max=8 intensity.min=0
//% bit.max=4 bit.min=1
export function TMcreate(clk: DigitalPin, dio: DigitalPin, intensity: number, count: number): TM1637LEDs {
let tm = new TM1637LEDs()
tm.clk = clk
tm.dio = dio
if ((count < 1) || (count > 5)) count = 4
tm.count = count
tm.brightness = intensity
tm.init()
return tm
}
let COMMAND_I2C_ADDRESS = 0x24
let DISPLAY_I2C_ADDRESS = 0x34
let _SEG = [0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71]
let _intensity = 3
let dbuf = [0, 0, 0, 0]
function cmd(c: number) {
pins.i2cWriteNumber(COMMAND_I2C_ADDRESS, c, NumberFormat.Int8BE)
}
function dat(bit: number, d: number) {
pins.i2cWriteNumber(DISPLAY_I2C_ADDRESS + (bit % 4), d, NumberFormat.Int8BE)
}
//% blockId="TM650_Control" block="%option显示" group="TM1650数码管"
//% weight=40 blockGap=8
//% subcategory="输出模块"
export function TM650_Control(option: Select) {
if (option == 0) {
cmd(_intensity * 16 + 1)
}
if (option == 1) {
_intensity = 0
cmd(0)
}
if (option == 2) {
dat(0, 0)
dat(1, 0)
dat(2, 0)
dat(3, 0)
dbuf = [0, 0, 0, 0]
}
}
//% blockId="TM650_DIGIT" block="第%bit位显示数据%num" group="TM1650数码管"
//% weight=80 blockGap=8
//% num.max=15 num.min=0
//% subcategory="输出模块"
//% bit.max=3 bit.min=0
export function digit(num: number, bit: number) {
dbuf[bit % 4] = _SEG[num % 16]
dat(bit, _SEG[num % 16])
}
//% blockId="TM650_SHOW_NUMBER" block="显示数据%num" group="TM1650数码管"
//% weight=100 blockGap=8
//% subcategory="输出模块"
export function showNumber(num: number) {
if (num < 0) {
dat(0, 0x40) // '-'
num = -num
}
else
digit(Math.idiv(num, 1000) % 10, 0)
digit(num % 10, 3)
digit(Math.idiv(num, 10) % 10, 2)
digit(Math.idiv(num, 100) % 10, 1)
}
//% blockId="TM650_SHOW_HEX_NUMBER" block="显示十六进制数据%num" group="TM1650数码管"
//% weight=90 blockGap=8
//% subcategory="输出模块"
export function showHex(num: number) {
if (num < 0) {
dat(0, 0x40) // '-'
num = -num
}
else
digit((num >> 12) % 16, 0)
digit(num % 16, 3)
digit((num >> 4) % 16, 2)
digit((num >> 8) % 16, 1)
}
//% blockId="TM650_SHOW_DP" block="设置点 %bit|show %status" group="TM1650数码管"
//% weight=80 blockGap=8
//% subcategory="输出模块"
//% bit.max=3 bit.min=0
export function showDpAt(status: ledon_off, bit: number) {
let show = status == 1 ? true : false;
if (show) dat(bit, dbuf[bit % 4] | 0x80)
else dat(bit, dbuf[bit % 4] & 0x7F)
}
//% blockId="TM650_INTENSITY" block="设置亮度 %dat" group="TM1650数码管"
//% weight=70 blockGap=8
//% subcategory="输出模块"
//% dat.max=7 dat.min=0
export function setIntensity(dat: number) {
if ((dat < 0) || (dat > 8)) {
return
}
if (dat == 0) {
_intensity = 0
cmd(0)
}
else {
_intensity = dat
cmd((dat << 4) | 0x01)
}
}
//% blockId=touchbutton block="引脚%pin检测到触摸?" group="触摸按键"
//% weight=70
//% subcategory="基础输入模块"
export function touchButton(pin: DigitalPin): boolean {
// pins.digitalWritePin(pin, 0)
if (pins.digitalReadPin(pin) == 1) {
return true;
} else {
return false;
}
}
//% blockId=button block="引脚%pin检测到按键被按下?" group="按键开关"
//% weight=70
//% subcategory="基础输入模块"
export function Button(pin: DigitalPin): boolean {
// pins.digitalWritePin(pin, 0)
if (pins.digitalReadPin(pin) == 1) {
return false;
} else {
return true;
}
}
//% blockId=crashbutton block="引脚%pin检测到碰撞?" group="碰撞开关"
//% weight=70
//% subcategory="基础输入模块"
export function crashButton(pin: DigitalPin): boolean {
// pins.digitalWritePin(pin, 0)
if (pins.digitalReadPin(pin) == 1) {
return false;
} else {
return true;
}
}
//% blockId=slideRheostat block="引脚%pin获取滑动变阻器的模拟值" group="滑动变阻器"
//% weight=70
//% subcategory="基础输入模块"
export function slideRheostat(pin: AnalogPin): number {
let row = pins.analogReadPin(pin)
return row
}
//% blockId=rotaryPotentiometer block="引脚%pin获取旋转电位器的模拟值" group="旋转电位器"
//% weight=70
//% subcategory="基础输入模块"
export function rotaryPotentiometer(pin: AnalogPin): number {
let row = pins.analogReadPin(pin)
return row
}
let Xpin = 0
let Ypin = 0
let Bpin = 0
//% blockId=rockerPin block="摇杆初始化引脚X%pinx引脚Y%piny引脚B%pinb" group="摇杆模块"
//% weight=70
//% subcategory="基础输入模块"
export function rockerPin(pinx: AnalogPin, piny: AnalogPin, pinb: DigitalPin): void {
Xpin = pinx
Ypin = piny
Bpin = pinb
}
//% blockId=_analogRead block=" %selectpin获取模拟值" group="摇杆模块"
//% weight=69
//% subcategory="基础输入模块"
export function _analogRead(selectpin: _rockerpin): number {
let a
if (selectpin == 0)
a = Xpin
else if (selectpin == 1)
a = Ypin
return pins.analogReadPin(a)
}
//% blockId=_digitalRead block="摇杆模块按键被按下?" group="摇杆模块"
//% weight=68
//% subcategory="基础输入模块"
export function _digitalRead(): boolean {
// pins.digitalWritePin(Bpin, 0)
if (pins.digitalReadPin(Bpin) == 1) {
return false;
} else {
return true;
}
}
let _DIO = 0
let _CLK = 0
//% blockId=basic_piano_pin block="钢琴模块初始化引脚 CLK %CLK DIO %DIO" group="钢琴模块"
//% weight=70
//% subcategory="基础输入模块"
export function basic_piano_pin(CLK: DigitalPin, DIO: DigitalPin): void {
_DIO = DIO
_CLK = CLK
}
//% blockId=basic_get_piano_key_number block="获取琴键编号" group="钢琴模块"
//% weight=70
//% subcategory="基础输入模块"
export function basic_get_piano_key_number(): number {
if (0 == pins.digitalReadPin(_DIO)) {
let list: number[] = []
for (let index = 0; index <= 15; index++) {
for (let index2 = 0; index2 < 4; index2++) {
pins.digitalWritePin(_CLK, 0)
}
for (let index2 = 0; index2 < 4; index2++) {
pins.digitalWritePin(_CLK, 1)
}
list[index] = pins.digitalReadPin(_DIO)
}
if (!(list[0])) {
return 1;
} else if (!(list[1])) {
return 2;
} else if (!(list[2])) {
return 3;
} else if (!(list[3])) {
return 4;
} else if (!(list[4])) {
return 5;
} else if (!(list[5])) {
return 6;
} else if (!(list[6])) {
return 7;
} else if (!(list[7])) {
return 8;
}
}
return 0
}
//% blockId=basic_piano_play block="弹奏钢琴" group="钢琴模块"
//% weight=69
//% subcategory="基础输入模块"
export function basic_piano_play(): void {
if (0 == pins.digitalReadPin(_DIO)) {
let list: number[] = []
for (let index = 0; index <= 15; index++) {
for (let index2 = 0; index2 < 4; index2++) {
pins.digitalWritePin(_CLK, 0)
}
for (let index2 = 0; index2 < 4; index2++) {
pins.digitalWritePin(_CLK, 1)
}
list[index] = pins.digitalReadPin(_DIO)
}
if (!(list[0])) {
music.playTone(262, music.beat(BeatFraction.Half))
} else if (!(list[1])) {
music.playTone(294, music.beat(BeatFraction.Half))
} else if (!(list[2])) {
music.playTone(330, music.beat(BeatFraction.Half))
} else if (!(list[3])) {
music.playTone(349, music.beat(BeatFraction.Half))
} else if (!(list[4])) {
music.playTone(392, music.beat(BeatFraction.Half))
} else if (!(list[5])) {
music.playTone(440, music.beat(BeatFraction.Half))
} else if (!(list[6])) {
music.playTone(494, music.beat(BeatFraction.Half))
} else if (!(list[7])) {
music.playTone(523, music.beat(BeatFraction.Half))
}
}
}
//% blockId=sensor_temperature block="引脚%pin获取环境温度" group="LM35温度传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_temperature(pin: AnalogPin): number {
let temp = (pins.analogReadPin(pin) / 1023) * 3.3 * 100;
return temp
}
//% blockId=sensor_flame block="引脚%pin检测到火焰?" group="火焰传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_flame(pin: DigitalPin): boolean {
if (pins.digitalReadPin(pin) == 1) {
return false;
} else {
return true;
}
}
//% blockId=sensor_flame_analog block="引脚%pin读取火焰的模拟值" group="火焰传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_flame_analog(pin: AnalogPin): number {
return pins.analogReadPin(pin)
}
//% blockId=sensor_infraredTracking block="引脚%pin检测到黑线?" group="红外寻迹传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_infraredTracking(pin: DigitalPin): boolean {
if (pins.digitalReadPin(pin) == 0) {
return true;
} else {
return false;
}
}
//% blockId=sensor_incline block="引脚%pin检测到倾斜?" group="倾斜传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_incline(pin: DigitalPin): boolean {
if (pins.digitalReadPin(pin) == 1) {
return false;
} else {
return true;
}
}
/**
* 光敏传感器
*/
//% blockId=sensor_illumination block="引脚%pin获取光照强度模拟值" group="光敏传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_illumination(pin: AnalogPin): number {
return pins.analogReadPin(pin)
}
/**
* 热敏传感器
*/
//% blockId=sensor_thermosensitive block="引脚%pin获取热度模拟值" group="热敏传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_thermosensitive(pin: AnalogPin): number {
return pins.analogReadPin(pin)
}
/**
* 水位传感器
*/
//% blockId=sensor_waterLevel block="引脚%pin获取水位模拟值" group="水位传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_waterLevel(pin: AnalogPin): number {
return pins.analogReadPin(pin)
}
/**
* 土壤湿度传感器
*/
//% blockId=sensor_soilMoisture block="引脚%pin获取湿度模拟值" group="土壤湿度传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_soilMoisture(pin: AnalogPin): number {
return pins.analogReadPin(pin)
}
/**
* 避障传感器
*/
//% blockId=sensor_obstacleAvoid block="引脚%pin检测到前方有障碍物?" group="避障传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_obstacleAvoid(pin: DigitalPin): boolean {
// pins.digitalWritePin(pin, 0)
if (pins.digitalReadPin(pin) == 1) {
return false;
} else {
return true;
}
// return pins.digitalReadPin(pin)
}
/**
* 磁簧开关传感器
*/
//% blockId=sensor_reedSwitch block="引脚%pin检测到磁场?" group="磁簧开关传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_reedSwitch(pin: DigitalPin): boolean {
// pins.digitalWritePin(pin, 0)
if (pins.digitalReadPin(pin) == 1) {
return false;
} else {
return true;
}
}
/**
* 人体热释电传感器
*/
//% blockId=sensor_humanBody block="引脚%pin检测到人体热源?" group="人体热释电传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_humanBody(pin: DigitalPin): boolean {
// pins.digitalWritePin(pin, 0)
if (pins.digitalReadPin(pin) == 1) {
return true;
} else {
return false;
}
}
/**
* 震动传感器
*/
//% blockId=sensor_quake block="引脚%pin检测到震动?" group="震动传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_quake(pin: DigitalPin): boolean {
// pins.digitalWritePin(pin, 0)
if (pins.digitalReadPin(pin) == 1) {
return false;
} else {
return true;
}
}
/**
* 震动传感器
*/
//% blockId=sensor_quake_analog block="引脚%pin获取震动模拟值" group="震动传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_quake_analog(pin: AnalogPin): number {
return pins.analogReadPin(pin)
}
/**
* 灰度传感器
*/
//% blockId=sensor_grayLevel block="引脚%pin获取颜色模拟值" group="灰度传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_grayLevel(pin: AnalogPin): number {
return pins.analogReadPin(pin)
}
/**
* 声音传感器
*/
//% blockId=sensor_sound_analogread block="引脚%pin获取声音的模拟值" group="声音传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_sound_analogread(pin: AnalogPin): number {
return pins.analogReadPin(pin)
}
//% blockId=sensor_sound_digitalread block="引脚%pin检测到声音?" group="声音传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_sound_digitalread(pin: DigitalPin): boolean {
if (pins.digitalReadPin(pin) == 1) {
return false;
} else {
return true;
}
}
/**
* 雨滴传感器
*/
//% blockId=sensor_rain_analogread block="引脚%pin获取雨滴的模拟值" group="雨滴传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_rain_analogread(pin: AnalogPin): number {
return pins.analogReadPin(pin)
}
//% blockId=sensor_rain_digitalread block="引脚%pin雨滴传感器检测到雨滴?" group="雨滴传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_rain_digitalread(pin: DigitalPin): boolean {
// pins.digitalWritePin(_DR, 0)
if (pins.digitalReadPin(pin) == 1) {
return false;
} else {
return true;
}
}
/**
* 气体传感器
*/
//% blockId=sensor_gas_analogread block="引脚%pin获取到气体的模拟值" group="气体传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_gas_analogread(pin: AnalogPin): number {
return pins.analogReadPin(pin)
}
//% blockId=sensor_gas_digitalread block="引脚%pin检测到气体?" group="气体传感器"
//% weight=70
//% inlineInputMode=inline
//% subcategory="传感器"
export function sensor_gas_digitalread(pin: DigitalPin): boolean {
// pins.digitalWritePin(_DG, 0)
if (pins.digitalReadPin(pin) == 1) {
return true;
} else {
return false;
}
}
//% blockId="readdht11" block="引脚 %dht11pin 获取温湿度传感器的 %dht11type" group="温湿度传感器"
//% subcategory="传感器"
//% inlineInputMode=inline
export function dht11value(dht11pin: DigitalPin, dht11type: DHT11Type): number {
pins.digitalWritePin(dht11pin, 0)
basic.pause(18)
let i = pins.digitalReadPin(dht11pin)
pins.setPull(dht11pin, PinPullMode.PullUp);
switch (dht11type) {
case 0:
let dhtvalue1 = 0;
let dhtcounter1 = 0;
while (pins.digitalReadPin(dht11pin) == 1);
while (pins.digitalReadPin(dht11pin) == 0);
while (pins.digitalReadPin(dht11pin) == 1);
for (let i = 0; i <= 32 - 1; i++) {
while (pins.digitalReadPin(dht11pin) == 0);
dhtcounter1 = 0
while (pins.digitalReadPin(dht11pin) == 1) {
dhtcounter1 += 1;
}
if (i > 15) {
if (dhtcounter1 > 2) {
dhtvalue1 = dhtvalue1 + (1 << (31 - i));
}
}
}
return ((dhtvalue1 & 0x0000ff00) >> 8);
break;
case 1:
while (pins.digitalReadPin(dht11pin) == 1);
while (pins.digitalReadPin(dht11pin) == 0);
while (pins.digitalReadPin(dht11pin) == 1);
let value = 0;
let counter = 0;
for (let i = 0; i <= 8 - 1; i++) {
while (pins.digitalReadPin(dht11pin) == 0);
counter = 0
while (pins.digitalReadPin(dht11pin) == 1) {
counter += 1;
}
if (counter > 3) {
value = value + (1 << (7 - i));
}
}
return value;
default:
return 0;
}
}
/**
* 循迹传感器
*/
//% blockId=sensor_tracking block="引脚 %pin 检测到黑线?" group="循迹传感器"
//% weight=74
//% subcategory="传感器"
//% inlineInputMode=inline
export function sensor_tracking(pin: DigitalPin): boolean {
//pins.digitalWritePin(pin, 0)
if (pins.digitalReadPin(pin) == 1) {
return false;
}else {
return true;
}
}
let outPin1 = 0;
let outPin2 = 0;
let outPin3 = 0;
let outPin4 = 0;
/**
* 四路循迹传感器初始化
*/
//% blockId=four_sensor_tracking block="四路循迹初始化引脚OUT0|%pin1|引脚OUT1|%pin2|引脚OUT2|%pin3|引脚OUT3|%pin4" group="循迹传感器"
//% inlineInputMode=inline
//% weight=73
//% subcategory="传感器"
export function four_sensor_tracking(pin1: DigitalPin, pin2: DigitalPin, pin3: DigitalPin, pin4: DigitalPin): void {
outPin1 = pin1;
outPin2 = pin2;
outPin3 = pin3;
outPin4 = pin4;
}
//% blockId=four_sensor_trackingValue block="四路循迹传感器获取的值" group="循迹传感器"
//% inlineInputMode=inline
//% weight=72
//% subcategory="传感器"
export function four_sensor_trackingValue(): number {
let result = 0;
// pins.digitalWritePin(outPin1, 0)
// pins.digitalWritePin(outPin2, 0)
// pins.digitalWritePin(outPin3, 0)
// pins.digitalWritePin(outPin4, 0)
if (pins.digitalReadPin(outPin1) == 1) {
result = 1 | result;
}else {
result = 0 | result;
}
if (pins.digitalReadPin(outPin2) == 1) {
result = 2 | result;
}else {
result = 0 | result;
}
if (pins.digitalReadPin(outPin3) == 1) {
result = 4 | result;
}else {
result = 0 | result;
}
if (pins.digitalReadPin(outPin4) == 1) {
result = 8 | result;
}else {
result = 0 | result;
}
return result;
}
//% blockId="dht11value_v2" block="引脚 %dht11pin 获取温湿度传感器的 %dht11type" group="温湿度传感器"
//% subcategory="micro:bit(V2)"
//% inlineInputMode=inline
export function dht11value_v2(dht11pin: DigitalPin, dht11type: DHT11Type): number {
pins.digitalWritePin(dht11pin, 0)
basic.pause(18)
let i = pins.digitalReadPin(dht11pin)
pins.setPull(dht11pin, PinPullMode.PullUp);
switch (dht11type) {
case 0:
let dhtvalue1 = 0;
let dhtcounter1 = 0;
while (pins.digitalReadPin(dht11pin) == 1);
while (pins.digitalReadPin(dht11pin) == 0);
while (pins.digitalReadPin(dht11pin) == 1);
for (let i = 0; i <= 32 - 1; i++) {
while (pins.digitalReadPin(dht11pin) == 0);
dhtcounter1 = 0
while (pins.digitalReadPin(dht11pin) == 1) {
dhtcounter1 += 1;
}
if (i > 15) {
if (dhtcounter1 > 10) {
dhtvalue1 = dhtvalue1 + (1 << (31 - i));
}
}
}
return ((dhtvalue1 & 0x0000ffff)>> 8);
break;
case 1:
while (pins.digitalReadPin(dht11pin) == 1);
while (pins.digitalReadPin(dht11pin) == 0);
while (pins.digitalReadPin(dht11pin) == 1);
let value = 0;
let counter = 0;
for (let i = 0; i <= 8 - 1; i++) {
while (pins.digitalReadPin(dht11pin) == 0);
counter = 0
while (pins.digitalReadPin(dht11pin) == 1) {
counter += 1;
}
if (counter > 10) {
value = value + (1 << (7 - i));
}
}
return value;
default:
return 0;
}
}
}
| 5640fef0eaae511c1ec3bd388c9ed62d7092d745 | [
"Markdown",
"TypeScript"
] | 2 | Markdown | skyerider/pxt-generic-sensors | 47b9520566918ac37f15cdcde2590ba0e3a66666 | 3bfa041459615a8aad838d60bf259483d6663728 |
refs/heads/master | <repo_name>qqwangxiaow/algorithm-basic<file_sep>/HeapSort.cpp
#include<iostream>
#include<vector>
using namespace std;
void adjust(vector<int>&arr,int len,int index)
{
int left=2*index+1;
int right=2*index+2;
int maxindex=index;
if(left<len&&arr[left]>arr[maxindex]) //maxindex not index
maxindex=left;
if(right<len&&arr[right]>arr[maxindex])
maxindex=right;
if(maxindex!=index)
{
swap(arr[maxindex],arr[index]);
adjust(arr,len,maxindex); //the 3rd variable=maxindex
}
}
void heapsort(vector<int>&arr,int size)
{
for(int i=size/2-1;i>=0;i--) //i=size/2-1
{
adjust(arr,size,i);
}
for(int i=size-1;i>=1;i--) //i>=1
{
swap(arr[i],arr[0]);
adjust(arr,i,0);
}
}
int main()
{
vector<int>arr{2,1,9,-1,6,0,22};
heapsort(arr,arr.size());
for(int i=0;i<arr.size();i++)
{
cout<<" "<<arr[i];
}
}<file_sep>/memcpy.c
//考虑内存对齐 并且一个字一个字的复制提高效率
//android内核版本
typedef long word;
#define lsize sizeof(word)
#define lmask (lsize-1)
void *memcpy(void *dest,const void *src,size_t count)
{
char *d=(char *)dest;
const char *s=(const char *)src;
int len;
if(count==0||dest==src)
return dest;
if(((long)d|(long)s)&lmask)
{
// src and/or dest do not align on word boundary
if((((long)d^(long)s)&lmask)||(count<lsize)) //第一个证明 两个指针对边界的差值不一样 所以只能一个个复制
{
len=count;// copy the rest of the buffer with the byte mover
}
else
{
len=lsize-((long)d&mask);// move the ptrs up to a word boundary
}
count-=len;
for(;len>0;len--)
*d++=*s++;
}
for(len=count/lsize;len>0;len--)
{
*(word *)d=*(word *)s;
d+=lsize;
s+=lsize;
}
for(len=count&lmask;len>0;len--)
{
*d++=*s++;
}
return dest;
}
<file_sep>/README.md
# alogrithm-basic
Implementing algorithms in C++
总结归纳基本的算法与数据结构实现
<file_sep>/KMP.c
int KMP(char *t,char *p)
{
int i=0;
int j=0;
while(i<strlen(t)&&j<strlen(p))
{
if(j=-1||t[i]==p[j])
{
i++;
j++;
}
else
{
j=next[j];
}
}
if(j=strlen(p))
return i-j;
else
return -1;
}
void next(char *p,int *next)
{
next[0]=-1;
int i=0,j=-1;
while(i<strlen(p))
{
if(j==-1||p[i]==p[j])
{
i++;
j++;
next[i]=j;
}
else
{
j=next[j];
}
}
}<file_sep>/string.cpp
class string
{
friend std::ostream& operator<<(osstrem &os,const string &str);
friend std::istream& operator>>(isstream &is,string &str);
public:
string(const char*=nullptr);
~string(void);
string(const string &str);
string &operator=(const string& str);
string operator+(const string& str);
bool operator==(const string& str);
char& operator[](unsigned int e);
int getlength();
private:
char *m_data;
}
string::string(const char *str)
{
if(str==nullptr)
{
m_data=new char[1];
*m_data='\0';
}
else
{
m_data=new char[strlen(str)+1];
strcpy(m_data,str);
}
}
string::~string()
{
if(m_data)
{
delete[] m_data;
m_data=nullptr;
}
}
string::string(const string& str)
{
if(str.m_data==nullptr)
{
m_data=nullptr;
}
else
{
m_data=new char[strlen(str.m_data)+1];
strcpy(m_data,str.m_data);
}
}
string &string::operator=(const string&str)
{
if(this!=str)
{
delete[] m_data;
m_data=nullptr;
if(str.m_data==nullptr)
m_data=nullptr;
else
{
m_data=new char[strlen(str.m_data)+1];
strcpy(m_data,str.m_data);
}
}
return *this;
}
string string::operator+(const string &str)
{
string newstring;
if(str==nullptr)
return *this;
else if(m_data==nullptr)
{
newstring=str;
}
else
{
newstring.m_data=new char[strlen(str.m_data)+1+strlen(m_data)+1];
strcpy(newstring.m_data,m_data);
strcpy(newstring,str.m_data);
}
return newstring;
}
bool string::operator==(const srtring &str)
{
if(strlen(m_data)!=strlen(str.m_data))
return false;
else
{
return strcmp(m_data,str.m_data)?false:true;
}
}
char &string::operator[](unsigned int e)
{
if(e>=0&&e<=strlen(m_data))
return m_data[e];
}
int string::getlength()
{
return strlen(m_data);
}
ostream &operator<<(ostream &os,const string &str)
{
os<<str.m_data;
return os;
}
istream &operator>>(istream &is,string &str)
{
char buff[4096];
is>>buff;
str.m_data=buff;
return is;
}
<file_sep>/KMP.cpp
int KMP(string s,string p)
{
int i=0,j=0;
vector<int>next=getnext(p);
while (i<s.size()&&j<(int)p.size())
{
if(j==-1||s[i]==p[j])
{
i++;
j++;
}
else
{
j=next[j];
}
}
if(j==p.size())
{
return i-j;
}
else
{
return -1;
}
}
vector<int>getnext(string p)
{
int i=0,j=-1;
vector<int>next(p.size(),0);
next[0]=-1;
while (i<(int)p.size()-1)
{
if(j==-1||p[i]==p[j])
{
i++;
j++;
next[i]=j;
}
else
{
j=next[j];
}
}
return next;
}
vector<int>getnextnext(string p)
{
vector<int>next(p.size());
next[0]=-1;
int i=0,j=-1;
while(i<p.size()-1)
{
if(j==-1||p[i]==p[j])
{
if(p[++i]==p[++j])
{
next[i]=next[j];
}
else
{
next[i]=j;
}
}
else
{
j=next[j];
}
}
return next;
}<file_sep>/BinarySearch.cpp
int binary_search(vector<int>& nums, int target) {
int lo = 0, hi = nums.size() - 1; // 在闭区间 [lo, hi] 中查找
// 退出查找的条件是:查找范围为空
while (lo <= hi) {
int mi = lo + (hi - lo) / 2;
if (nums[mi] < target) {
lo = mi + 1; // mi 不是可行解,范围变成 [mi+1, hi]
} else if (nums[mi] > target) {
hi = mi - 1; // mi 不是可行解,范围变成 [lo, mi-1]
} else {
return mi;
}
}
return -1;
}
//存在重复元素 找第一个
int binary_search(vector<int>& nums,int target) {
int lo = 0, hi = nums.size() - 1; // 在闭区间 [lo, hi] 中查找
// 退出查找的条件是:查找范围为1个元素
while (lo < hi) {
int mi = lo + (hi - lo) / 2;
if (nums[mi] == target) {
hi = mi; // mi 在可行解区间中,可行解区间范围缩小为 [lo, mi]
} else {
lo = mi + 1; // mi 不在可行解区间中,可行解区间范围缩小为 [mi+1, hi]
}
}
return lo;
}
//存在重复元素 找最后一个
int binary_search(vector<int>& nums,int target) {
int lo = 0, hi = nums.size() - 1; // 在闭区间 [lo, hi] 中查找
// 退出查找的条件是:查找范围为1个元素
while (lo < hi) {
int mi = lo + (hi - lo + 1) / 2; // +1 保证可行解区间范围缩小
if (nums[mi] == target) {
lo = mi; // mi 在可行解区间中,可行解区间范围缩小为 [mi, hi]
} else {
hi = mi - 1; // mi 不在可行解区间中,可行解区间范围缩小为 [lo, mi-1]
}
}
return lo;
}<file_sep>/QuickSort.cpp
//cpp version
#include<iostream>
#include<vector>
using namespace std;
int partition(vector<int>&arr,int l,int r)
{
int pivot=arr[r];
int ll=l-1;
for(int i=l;i<r;i++)
{
if(arr[i]<=pivot)
{
ll++;
swap(arr[ll],arr[i]);
}
}
swap(arr[++ll],arr[r]); //arr[r] not pivot
return ll;
}
void quicksort(vector<int>&arr,int l,int r)
{
if(l<r) //if(l<r) not while
{
int m=partition(arr,l,r);
quicksort(arr,l,m-1);
quicksort(arr,m+1,r);
}
}
int main()
{
vector<int>arr{2,1,9,-1,6,0,22};
quicksort(arr,0,arr.size()-1);
for(int i=0;i<arr.size();i++)
{
cout<<" "<<arr[i];
}
return 0;
}
//using first element as pivot
void QuickSort(int A[],int left,int right)
{
int l=left,r=right;
int pivot;
if(left<right)
{
pivot=A[left];
while(l<r)
{
while(l<r&&A[r]>=pivot)
r--;
if(l<r)
{
A[l]=A[r];
l++;
}
while(l<r&&A[l]<pivot)
l++;
if(l<r)
{
A[r]=A[l];
r--;
}
}
A[l]=pivot;
QuickSort(A,left,l-1);
QuickSort(A,l+1,right);
}
}
//partition
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[],int low,int high)
{
int pivot=arr[high];
int l=low-1;
for(int i=low;i<=high-1;i++)
{
if(arr[i]<=pivot)
{
l++;
swap(&arr[l],&arr[i]);
}
}
swap(&arr[l+1],&arr[high]);
return (l+1);
}
void QuickSort(int arr[],int low,int high)
{
if(low<high)
{
int m=partition(arr,low,high);
QuickSort(arr,low,m-1);
QuickSort(arr,m+1,high);
}
}
<file_sep>/MergeSort.cpp
#include<iostream>
#include<vector>
#include<unordered_map>
#include<string>
#include<bitset>
#include<stack>
#include<algorithm>
#include<set>
#include<unordered_set>
#include<map>
using namespace std;
void merge(vector<int>&arr,int l,int m,int r,vector<int>temp)
{
int i=l,j=m+1,k=0;
while(i<=m&&j<=r)
{
if(arr[i]<arr[j])
{
temp[k++]=arr[i++];
}
else
{
temp[k++]=arr[j++];
}
}
while(i<=m)
temp[k++]=arr[i++];
while(j<=r)
temp[k++]=arr[j++];
k=0;
while(l<=r)
{
arr[l++]=temp[k++];
}
}
void mergesort(vector<int>&arr,int l,int r,vector<int>temp)
{
if(l<r)
{
int m=(l+r)>>1;
mergesort(arr,l,m,temp);
mergesort(arr,m+1,r,temp);
merge(arr,l,m,r,temp);
}
}
void MergeSort(vector<int>&arr)
{
vector<int>temp(arr.size());
mergesort(arr,0,arr.size()-1,temp);
}
int main() {
vector<int>arr{2,1,9,-1,6,0,22};
MergeSort(arr);
for(int i=0;i<arr.size();i++)
cout<<arr[i]<<" ";
} | 2ad800b6558856c3e48da6c95341c24f49668ff2 | [
"Markdown",
"C",
"C++"
] | 9 | C++ | qqwangxiaow/algorithm-basic | 2ab53a8524e707fe5b14cebdb5bb2f3ab203747f | c19fffcd998223fa7e0280d34691096831b3d089 |
refs/heads/master | <repo_name>offmango/hashtag<file_sep>/features/support/env.rb
require 'rubygems'
require 'spork'
Spork.prefork do
require 'cucumber/rails'
require 'capybara/rspec'
Capybara.default_selector = :css
ActionController::Base.allow_rescue = false
end
Spork.each_run do
end
<file_sep>/features/step_definitions/search_steps.rb
require 'fake_twitter'
When /^I search for the term "(.*?)"$/ do |search_term|
visit root_path
fill_in 'Search Term', with: search_term
click_button 'Search'
end
Then /^I should see tweets with the hashtag "(.*?)"$/ do |search_term|
page.current_path.should == search_path(search_term)
within '[data-role="search-results"]' do
page.should have_css("li:contains('##{search_term}')")
end
end
Given /^Twitter returns the following tweets when searching for "(.*?)":$/ do |hashtag, tweets_table|
fake_twitter = FakeTwitter.new(hashtag, tweets_table.hashes)
# [{ text: 'whatever'}, {text: 'whatever'}]
Searcher.search_implementation = fake_twitter
end
Then /^I should see the tweet "(.*?)" authored by "(.*?)"$/ do |tweet_text, tweet_from_user|
within '[data-role="search-results"]' do
page.should have_css("li:contains('#{tweet_text}')")
page.should have_css("li:contains('#{tweet_from_user}')")
end
end
Around do |scenario, block|
old_search_immplementation = Searcher.search_implementation
block.call
Searcher.search_implementation = old_search_immplementation
end
| f73f45dfe7fe46d9171e6a212c83e2ac837cdf70 | [
"Ruby"
] | 2 | Ruby | offmango/hashtag | 1631ad157c0b4170dffd70f6ff1e9743f33f034e | 8b30b1a0f93cc6329b77ce5503f2b64c79818981 |
refs/heads/master | <file_sep>import sqlite3 as sqlite
import re
import math
class classifier:
def __init__(self,getfeatures,filename=None):
# Counts of feature/category combinations
self.fc={}
# Counts of documents in each category
self.cc={}
self.getfeatures=getfeatures
def setdb(self,db):
self.con=sqlite.connect(db)
self.con.execute('create table if not exists fc(feature,category,count)')
self.con.execute('create table if not exists cc(category,count)')
def incf(self,f,cat):
count=self.fcount(f,cat)
if count==0:
self.con.execute("insert into fc values ('%s','%s',1)"
% (f,cat))
else:
self.con.execute(
"update fc set count=%d where feature='%s' and category='%s'"
% (count+1,f,cat))
def fcount(self,f,cat):
res=self.con.execute(
'select count from fc where feature="%s" and category="%s"'
%(f,cat)).fetchone()
if res==None: return 0
else: return float(res[0])
def incc(self,cat):
count=self.catcount(cat)
if count==0:
self.con.execute("insert into cc values ('%s',1)" % (cat))
else:
self.con.execute("update cc set count=%d where category='%s'"
% (count+1,cat))
def catcount(self,cat):
res=self.con.execute('select count from cc where category="%s"'
%(cat)).fetchone()
if res==None: return 0
else: return float(res[0])
def categories(self):
cur=self.con.execute('select category from cc');
return [d[0] for d in cur]
def totalcount(self):
res=self.con.execute('select sum(count) from cc').fetchone();
if res==None: return 0
return res[0]
def train(self,item,cat):
features=item
# Increment the count for every feature with this category
for f in features:
self.incf(f,cat)
# Increment the count for this category
self.incc(cat)
self.con.commit()
def fprob(self,f,cat):
if self.catcount(cat)==0: return 0
# The total number of times this feature appeared in this
# category divided by the total number of items in this category
return self.fcount(f,cat)/self.catcount(cat)
def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):
# Calculate current probability
basicprob=prf(f,cat)
# Count the number of times this feature has appeared in
# all categories
totals=sum([self.fcount(f,c) for c in self.categories()])
# Calculate the weighted average
bp=((weight*ap)+(totals*basicprob))/(weight+totals)
return bp
<file_sep>import re
import math
import classifier
class naivebayes(classifier.classifier):
def __init__(self,getfeatures):
classifier.classifier.__init__(self,getfeatures)
self.thresholds={}
def docprob(self,item,cat):
features=item
# Multiply the probabilities of all the features together
p=1
for f in features: p*=self.weightedprob(f,cat,self.fprob)
return p
def prob(self,item,cat):
catprob=self.catcount(cat)/self.totalcount()
docprob=self.docprob(item,cat)
return docprob*catprob
def setthreshold(self,cat,t):
self.thresholds[cat]=t
def getthreshold(self,cat):
if cat not in self.thresholds: return 1.0
return self.thresholds[cat]
def classify(self,item,default=None):
probs={}
# Find the category with the highest probability
max=0.0
for cat in self.categories():
probs[cat]=self.prob(item,cat)
if probs[cat]>max:
max=probs[cat]
best=cat
# Make sure the probability exceeds threshold*next best
for cat in probs:
if cat==best: continue
if probs[cat]*self.getthreshold(best)>probs[best]: return default
return best
<file_sep>import re
import classifier
import naivebayes
import fisherclassifier
def main():
doc = open("fingerprintGender.txt",'r')
wordsDict = getwords(doc.read())
genericClassifier = classifier.classifier(wordsDict)
genericClassifier.setdb("generic.db")
sampletrain(genericClassifier)
print "---genericClassifier---"
print genericClassifier.weightedprob('quick rabbit','good', genericClassifier.fprob)
print "---Naive Bayes---"
bayesClassifier = naivebayes.naivebayes(wordsDict)
bayesClassifier.setdb("bayes.db")
sampletrain(bayesClassifier)
print bayesClassifier.prob('quick rabbit','good')
bayesClassifier.classify('quick money',default='unknown')
for i in range(10): sampletrain(bayesClassifier)
print bayesClassifier.classify('quick money',default='unknown')
print "---FISHER CLASSIFIER---"
fisher = fisherclassifier.fisherclassifier(wordsDict)
fisher.setdb("fisher.db")
sampletrain(fisher)
print fisher.fisherprob('quick rabbit','good')
print fisher.weightedprob('money','bad', fisher.cprob)
def getwords(doc):
splitter=re.compile('\\W*')
# Separa as palavras em caracteres que nao sejam alfabeticos
words=[s.lower() for s in splitter.split(doc)
if len(s)>2 and len(s)<20]
# Retorna um consjunto unico de palavras apenas
return dict([(w,1) for w in words])
def sampletrain(cl):
cl.train('Nobody owns the water.','good')
cl.train('the quick rabbit jumps fences','good')
cl.train('buy pharmaceuticals now','bad')
cl.train('make quick money at the online casino','bad')
cl.train('the quick brown fox jumps','good')
if __name__ == "__main__":
main()
<file_sep>import re
import math
import classifier
class fisherclassifier(classifier.classifier):
def cprob(self,f,cat):
# The frequency of this feature in this category
clf=self.fprob(f,cat)
if clf==0: return 0
# The frequency of this feature in all the categories
freqsum=sum([self.fprob(f,c) for c in self.categories()])
# The probability is the frequency in this category divided by
# the overall frequency
p=clf/(freqsum)
return p
def fisherprob(self,item,cat):
# Multiply all the probabilities together
p=1
features=item
for f in features:
p*=(self.weightedprob(f,cat,self.cprob))
# Take the natural log and multiply by -2
fscore=-2*math.log(p)
# Use the inverse chi2 function to get a probability
return self.invchi2(fscore,len(features)*2)
def invchi2(self,chi, df):
m = chi / 2.0
sum = term = math.exp(-m)
for i in range(1, df//2):
term *= m / i
sum += term
return min(sum, 1.0)
def __init__(self,getfeatures):
classifier.classifier.__init__(self,getfeatures)
self.minimums={}
def setminimum(self,cat,min):
self.minimums[cat]=min
def getminimum(self,cat):
if cat not in self.minimums: return 0
return self.minimums[cat]
def classify(self,item,default=None):
# Loop through looking for the best result
best=default
max=0.0
for c in self.categories():
p=self.fisherprob(item,c)
# Make sure it exceeds its minimum
if p>self.getminimum(c) and p>max:
best=c
max=p
return best
| ef6e525035474659f9d382d7ebf571f44e18462a | [
"Python"
] | 4 | Python | thaisviana/inteligenciaColetiva-cap6 | b7385cb7b5c20b8f61ae0671ba4f6ffe221b6ffe | ea72bc643a48135315b0c98d7c69325dba02de09 |
refs/heads/master | <file_sep># measure-text
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][depstat-image]][depstat-url] [![Download][dlcounter-image]][dlcounter-url] [![Coverage Status][coveralls-image]][coveralls-url]
> In-memory text measurement using canvas
## DEPRECATED
Use https://github.com/bezoerb/text-metrics instead
## Features
* Compute text width
* Compute max font-size to fit into element
## Installation
If you're using node, you can run `npm install bezoerb-measure-text`.
measure-text is also available via [Bower](https://github.com/bower/bower) (`bower install measure-text`)
Alternatively if you just want to grab the file yourself, you can download either the current stable [production version][min] or the [development version][max] directly.
[min]: https://raw.github.com/bezoerb/measure-text/master/dist/measure-text.min.js
[max]: https://raw.github.com/bezoerb/measure-text/master/dist/measure-text.js
## Setting it up
measure-text supports AMD (e.g. RequireJS), CommonJS (e.g. Node.js) and direct usage (e.g. loading globally with a <script> tag) loading methods.
You should be able to do nearly anything, and then skip to the next section anyway and have it work. Just in case though, here's some specific examples that definitely do the right thing:
### CommonsJS (e.g. Node)
measure-text needs some browser environment to run.
```javascript
import import * as measureText from 'bezoerb-measure-text';
measureText.width('unicorns',document.querySelector('h1'));
```
### AMD (e.g. RequireJS)
```javascript
define(['measure-text'], function(measureText) {
measureText.width('unicorns',document.querySelector('h1'));
});
```
### Directly in your web page:
```html
<script src="measure-text.min.js"></script>
<script>
measureText.width('unicorns',document.querySelector('h1'));
</script>
```
## API
#### measureText.width(text, [element | options])
Compute text width.
#### measureText.height(text, [element | options])
Compute text height.
#### measureText.maxFontSize(text, [element | options])
Compute max fontsize to fit element.
#### measureText.computeLinebreaks(text, [element | options])
Compute lines of text with automatic word wraparound
### text
Type: `string`<br>
Default: ''
Some text to measure
### options
##### element
Type: `Element`<br>
Default: `undefined`
The element used to fetch styles from.
##### font-weight
Type: `string`<br>
Default: `400`<br>
Allowed: `normal`, `bold`, `bolder`, `lighter`, `100`, `200`, `300`, `400`, `500`, `600`, `700`, `800`, `900`
Takes precedence over computed element style. Default value is set when no element is available.
##### font-style
Type: `string`<br>
Default: `normal`
Allowed: `normal`, `italic`, `oblique`
Takes precedence over computed element style. Default value is set when no element is available.
##### font-variant
Type: `string`<br>
Default: `normal`
Allowed: `normal`, `small-caps`
Takes precedence over computed element style. Default value is set when no element is available.
##### font-size
Type: `string`<br>
Default: `16px`
Takes precedence over computed element style. Default value is set when no element is available.
##### font-family
Type: `string`<br>
Default: `Helvetica, Arial, sans-serif`
Takes precedence over computed element style. Default value is set when no element is available.
##### width
Type: `string`<br>
Default: `undefined`
Used for `getMaxFontSize`, `height`, `computeLinebreaks` and `width` with multiline option.
Takes precedence over element offsetWidth.
## License
Copyright (c) 2016 <NAME>
Licensed under the [MIT license](http://bezoerb.mit-license.org/).
[npm-url]: https://npmjs.org/package/bezoerb-measure-text
[npm-image]: https://badge.fury.io/js/bezoerb-measure-text.svg
[travis-url]: https://travis-ci.org/bezoerb/measure-text
[travis-image]: https://secure.travis-ci.org/bezoerb/measure-text.svg?branch=master
[depstat-url]: https://david-dm.org/bezoerb/measure-text
[depstat-image]: https://david-dm.org/bezoerb/measure-text.svg
[dlcounter-url]: https://www.npmjs.com/package/bezoerb-measure-text
[dlcounter-image]: https://img.shields.io/npm/dm/bezoerb-measure-text.svg
[coveralls-url]: https://coveralls.io/github/bezoerb/measure-text?branch=master
[coveralls-image]: https://coveralls.io/repos/github/bezoerb/measure-text/badge.svg?branch=master
## Usage
```html
<h1></h1>
<script src="measure-text.js"></script>
<script>
var h1 = document.querySelector('h1');
measureText.width('unicorns',h1);
// -> 37.7978515625
</script>
```
## License
MIT © [<NAME>](http://sommerlaune.com)
<file_sep>/* eslint-env es6, browser */
// eslint-disable-next-line import/no-unassigned-import
import '../node_modules/babel-core/register';
import test from 'ava';
import {width, height, computeLinebreaks, maxFontSize} from '../src/index';
test('Compute with without element', t => {
let w = width('test', {
'font-size': '30px',
'font-weight': '400',
'font-family': 'Helvetica, Arial, sans-serif'
});
t.is(Math.floor(w), 48);
});
test('Compute width for h1', t => {
let el = document.querySelector('h1');
t.is(Math.floor(width('TEST', el)), 92);
});
test('Compute width for h2', t => {
let el = document.querySelector('h2');
t.is(Math.floor(width('TEST', el)), 48);
});
test('Computes width', t => {
let el = document.querySelector('h1');
let v1 = width('-', el);
let v2 = width('--', el);
let v3 = width('---', el);
t.true(v1 < v2 < v3);
});
test('Computes maxFontSize', t => {
let el = document.querySelector('#max-font-size');
t.is(maxFontSize('unicorn', el), '183px');
});
test('Computes lines', t => {
let el = document.querySelector('#height');
const text = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam atque cum dolor explicabo incidunt.';
const expected = [
'Lorem ipsum',
'dolor sit amet,',
'consectetur',
'adipisicing elit.',
'Aliquam atque',
'cum dolor',
'explicabo',
'incidunt.'
];
const value = computeLinebreaks(text, el);
t.is(value.length, expected.length);
for (let i = 0; i < value.length; i++) {
t.is(value[i], expected[i]);
}
});
test('Computes height', t => {
const text = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam atque cum dolor explicabo incidunt.';
const val = height(text, {
'font-size': '14px',
'line-height': '20px',
'font-family': 'Helvetica, Arial, sans-serif',
'font-weight': '400',
width: 100
});
t.is(val, 160);
});
<file_sep>/* eslint-env es6, browser */
const DEFAULTS = {
'font-size': '16px',
'font-weight': '400',
'font-family': 'Helvetica, Arial, sans-serif'
};
/**
* Map css styles to canvas font property
*
* font: font-style font-variant font-weight font-size/line-height font-family;
* http://www.w3schools.com/tags/canvas_font.asp
*
* @param {CSSStyleDeclaration} style
* @param {object} options
* @returns {string}
*/
function getFont(style, options) {
let font = [];
let fontWeight = prop(options, 'font-weight', style.getPropertyValue('font-weight'));
if (['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900'].indexOf(fontWeight.toString()) !== -1) {
font.push(fontWeight);
}
let fontStyle = prop(options, 'font-style', style.getPropertyValue('font-style'));
if (['normal', 'italic', 'oblique'].indexOf(fontStyle) !== -1) {
font.push(fontStyle);
}
let fontVariant = prop(options, 'font-variant', style.getPropertyValue('font-variant'));
if (['normal', 'small-caps'].indexOf(fontVariant) !== -1) {
font.push(fontVariant);
}
let fontSize = prop(options, 'font-size', style.getPropertyValue('font-size'));
let fontSizeValue = parseFloat(fontSize);
let fontSizeUnit = fontSize.replace(fontSizeValue, '');
// eslint-disable-next-line default-case
switch (fontSizeUnit) {
case 'rem':
case 'em':
fontSizeValue *= 16;
break;
case 'pt':
fontSizeValue /= 0.75;
break;
}
font.push(fontSizeValue + 'px');
let fontFamily = prop(options, 'font-family', style.getPropertyValue('font-family'));
font.push(fontFamily);
return font.join(' ');
}
/**
* check for CSSStyleDeclaration
*
* @param val
* @returns {bool}
*/
export function isCSSStyleDeclaration(val) {
return val && typeof val.getPropertyValue === 'function';
}
/**
* check wether we can get computed style
*
* @param el
* @returns {bool}
*/
export function canGetComputedStyle(el) {
return el && el.style && typeof window !== 'undefined' && typeof window.getComputedStyle === 'function';
}
/**
* check for DOM element
*
* @param el
* @retutns {bool}
*/
export function isElement(el) {
return (
typeof HTMLElement === 'object' ? el instanceof HTMLElement :
el && typeof el === 'object' && el !== null && el.nodeType === 1 && typeof el.nodeName === 'string'
);
}
/**
* Get style declaration if available
*
* @returns {CSSStyleDeclaration}
*/
export function getStyle(options) {
if (isCSSStyleDeclaration(options.style)) {
return options.style;
}
let el = options && isElement(options.element) && options.element;
if (canGetComputedStyle(el)) {
return window.getComputedStyle(el, prop(options, 'pseudoElt', null));
}
return {
getPropertyValue: key => prop(options, key)
};
}
/**
* get styled text
*
* @param {string} text
* @param {CSSStyleDeclaration} style
* @returns {string}
*/
export function getStyledText(text, style) {
switch (style.getPropertyValue('text-transform')) {
case 'uppercase':
return text.toUpperCase();
case 'lowercase':
return text.toLowerCase();
default:
return text;
}
}
/**
* Get property from src
*
* @param src
* @param attr
* @param defaultValue
* @returns {*}
*/
function prop(src, attr, defaultValue) {
return (src && typeof src[attr] !== 'undefined' && src[attr]) || defaultValue;
}
/**
* Normalize options
*
* @param options
* @returns {*}
*/
function parseOptions(options) {
// no option set
if (isElement(options)) {
return {element: options};
}
// normalize keys (fontSize => font-size)
if (typeof options === 'object') {
Object.keys(options).forEach(key => {
const dashedKey = key.replace(/([A-Z])/g, $1 => `-${$1.toLowerCase()}`);
options[dashedKey] = options[key];
});
}
// don't set defaults if we got an element
if (options && isElement(options.element)) {
return options;
}
return Object.assign({}, DEFAULTS, options || {});
}
/**
* Compute Text Metrics based for given text
*
* @param {string} text
* @param {object|Element} options
* @returns {function}
*/
export function width(text, options) {
options = parseOptions(options);
let style = getStyle(options);
let styledText = getStyledText(text, style);
let ctx;
try {
ctx = document.createElement('canvas').getContext('2d');
ctx.font = prop(options, 'font', null) || getFont(style, options);
} catch (err) {
throw new Error('Canvas support required');
}
if (options.multiline) {
return computeLinebreaks(styledText, Object.assign({}, options, {style})).reduce((res, text) => {
return Math.max(res, ctx.measureText(text).width);
}, 0);
}
return ctx.measureText(styledText).width;
}
/**
* compute lines of text with automatic word wraparound
* element styles
*
* @param text
* @param options
* @returns {*}
*/
export function computeLinebreaks(text, options) {
options = parseOptions(options);
const style = getStyle(options);
// get max width
const max = parseInt(
prop(options, 'width') ||
prop(options.element, 'offsetWidth', 0) ||
style.getPropertyValue('width')
, 10);
const delimiter = prop(options, 'delimiter', ' ');
const styledText = getStyledText(text, style);
const words = styledText.split(delimiter);
if (words.length === 0) {
return 0;
}
let ctx;
try {
ctx = document.createElement('canvas').getContext('2d');
ctx.font = prop(options, 'font', null) || getFont(style, options);
} catch (err) {
throw new Error('Canvas support required');
}
let lines = [];
let line = words.shift();
words.forEach((word, index) => {
const {width} = ctx.measureText(line + delimiter + word);
if (width <= max) {
line += (delimiter + word);
} else {
lines.push(line);
line = word;
}
if (index === words.length - 1) {
lines.push(line);
}
});
if (words.length === 0) {
lines.push(line);
}
return lines;
}
/**
* Compute height from textbox
*
* @param text
* @param options
* @returns {number}
*/
export function height(text, options) {
options = parseOptions(options);
const style = getStyle(options);
const lineHeight = parseInt(prop(options, 'line-height') || style.getPropertyValue('line-height'), 10);
return computeLinebreaks(text, Object.assign({}, options, {style})).length * lineHeight;
}
/**
* Compute Text Metrics based for given text
* @returns {function}
*/
export function maxFontSize(text, options) {
options = parseOptions(options);
// add computed style to options to prevent multiple expensive getComputedStyle calls
options.style = getStyle(options);
// simple compute function which adds the size and computes the with
let compute = size => {
options['font-size'] = size + 'px';
return width(text, options);
};
// get max width
// get max width
const max = parseInt(
prop(options, 'width') ||
prop(options.element, 'offsetWidth', 0) ||
options.style.getPropertyValue('width')
, 10);
// start with half the max size
let size = Math.floor(max / 2);
let cur = compute(size);
// compute next result based on first result
size = Math.floor(size / cur * max);
cur = compute(size);
// happy cause we got it already
if (Math.ceil(cur) === max) {
return size + 'px';
}
// go on by increase/decrease pixels
if (cur > max && size > 0) {
while (cur > max && size > 0) {
cur = compute(size--);
}
return size + 'px';
}
while (cur < max) {
cur = compute(size++);
}
size--;
return size + 'px';
}
| 078e6b2cdaf68e898b2e2e9d4a28792dc8879abc | [
"Markdown",
"JavaScript"
] | 3 | Markdown | bezoerb/measure-text.git | d1beb2f626017ca9f8bd447b087d663b8f501951 | 65f9cd4852110f713e90b89e202dbdaee2d4c006 |
refs/heads/master | <file_sep># bitfinex-polybar

Bitfinex module for Polybar. It shows your total Bitfinex deposit in dollars.
## Dependencies
- NodeJS 8.x.x
- polybar
## Installation
```bash
git clone https://github.com/BrunnerLivio/bitfinex-polybar.git
cd bitfinex-polybar
# Edit Keys. Get API keys from your Bitfinex Account
mv keys.json.template keys.json
vi keys.json
# Download NodeJS dependencies
npm install
# Install files
cat config >> $HOME/.config/polybar/config
cp package.json $HOME/.config/polybar/
cp index.js $HOME/.config/polybar/wallet-sum.js
cp -rf node_modules $HOME/.config/polybar/
cp -rf keys.json $HOME/.config/polybar/
```
Reload the polybar ($MOD + SHIFT + R).
## Run in shell
If you want to run it after the installation,
do not forget to run `cd $HOME/.config/polybar`.
Otherwise, if you want to run it inside the
development environment, only run the
following command. Do not forget to
edit the `keys.json`.
```bash
node index.js
```
<file_sep>const BFX = require('bitfinex-api-node');
const async = require('async');
const keys = require('./keys.json');
const API_KEY = keys.API_KEY;
const API_SECRET = keys.API_SECRET;
const UPDATE_INTERVAL = parseFloat(keys.UPDATE_INTERVAL) || 60;
const bfxRest = new BFX(API_KEY, API_SECRET, { version: 1 }).rest;
let lastSum;
/**
* Get a list of the users account wallet balances
* @returns {Promise<Object[]>} List of the users account wallet balances
*/
const loadWalletBalances = () => {
return new Promise((resolve, reject) => {
bfxRest.wallet_balances((err, res) => {
if (err) {
return reject(err);
}
resolve(res);
});
});
};
/**
* Returns the given Cryptobalance in USD
* @param {string} type The Cryptocoins type e.g. IOT
* @param {Number} balance The balance as number to convert the price
* @returns {Promise<Number>} The given balance converted in USD
*/
const getBalanceInUsd = (type, balance) => {
return new Promise((resolve, reject) => {
bfxRest.ticker(`${type.toUpperCase()}USD`, (err, res) => {
if (err) {
return reject(err);
}
resolve(res.last_price * balance);
});
});
};
/**
* Returns the sum of the given balances
* @param {Object[]} balances The balances you want to get the USD sum of
* @returns {Promise<Number>} The sum of the given balances in USD
*/
const convertBalancesToUSDSum = balances => {
return new Promise((resolve, reject) => {
const cryptoBalances = balances.filter(balance => balance.currency !== 'usd' && balance.currency !== 'eur')
async.reduce(cryptoBalances, 0, (sum, balance, callback) => {
getBalanceInUsd(balance.currency, balance.amount)
.then(conversion => callback(null, conversion + sum))
.catch(err => callback(err));
}, (err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
});
});
};
/**
* Get the current Balance of the set API Keys in USD
* @returns {Promise<Number>} The current Bitfinex balance in USD
*/
const getWalletSum = () => {
return new Promise((resolve, reject) => {
loadWalletBalances()
.then(balances => convertBalancesToUSDSum(balances)
.then(resolve)
.catch(reject))
.catch(reject);
});
};
/**
* Returns an ASCII icon, depending if the balance increased or decreased.
* @param {Number} sum The current sum
* @returns {String} The icon
*/
getIconFromSum = sum => {
let icon = '';
if (lastSum) {
icon = sum > lastSum ? '%{F#19b719}▲' : (sum < lastSum ? '%{F#f40707}▼' : '=');
}
lastSum = sum;
return icon;
};
/**
* Formats the sum by flooring it, and adding an icon
* @param {Number} sum The sum to format
* @returns {String} The formatted sum
*/
const formatSum = sum => {
const icon = getIconFromSum(sum);
return `${icon} ${sum.toFixed(2)}$`;
};
/**
* Runs the program
*/
const run = () => {
setInterval(() => {
getWalletSum()
.then(sum => console.log(formatSum(sum)))
.catch(console.err);
}, 1000 * UPDATE_INTERVAL);
};
run(); | adfd05a459b1ece171345a14498e92d995418d83 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | BrunnerLivio/bitfinex-polybar | 2637a24ab2b75cb531990097e30bf0185be83dff | bccd087ca110fbc8791f994f60f449cec6adc075 |
refs/heads/main | <file_sep># JNWGarage
A description of this package.
<file_sep>//
// JNWGarage+UIColor.swift
// JNWGarage
//
// Created by John on 2021/4/27.
//
#if os(iOS) || os(tvOS) //os(macOS)
import UIKit
#else
import AppKit
#endif
#if os(iOS) || os(tvOS) //os(macOS)
extension UIColor : JNWTypeAdaptor { }
extension JNWAdaptorTypeWrapper where Base == UIColor.Type {
public func hex(str: String) -> UIColor {
var colorStr = str
if colorStr.hasPrefix("0x") {
colorStr.removeFirst(2)
} else if colorStr.hasPrefix("#") {
colorStr.removeFirst()
}
var alpha: CGFloat = 1
if colorStr.count == 8 {
let index = colorStr.index(colorStr.startIndex, offsetBy: 1)
let alphaStr = String(colorStr[colorStr.startIndex...index])
alpha = CGFloat(alphaStr.jnw.fromHex() ?? 1)/CGFloat(255)
colorStr.removeFirst(2)
}
if colorStr.count != 6 {
return .clear
}
colorStr = colorStr.uppercased()
let validColorCharater = { (char: String.Element) -> Bool in
return ("0"..."9").contains(String(char)) || ("A"..."F").contains(String(char))
}
for char in colorStr {
if !validColorCharater(char) {
return .clear
}
}
let rEndIndex = colorStr.index(colorStr.startIndex, offsetBy: 1)
let gEndIndex = colorStr.index(rEndIndex, offsetBy: 1)
let bEndIndex = colorStr.index(gEndIndex, offsetBy: 1)
let r = String(colorStr[colorStr.startIndex...rEndIndex]).jnw.fromHex() ?? 0
let g = String(colorStr[rEndIndex...gEndIndex]).jnw.fromHex() ?? 0
let b = String(colorStr[gEndIndex...bEndIndex]).jnw.fromHex() ?? 0
return UIColor(red: CGFloat(Double(r)/255.0), green: CGFloat(Double(g)/255.0), blue: CGFloat(Double(b)/255.0), alpha: alpha)
}
}
#else
#endif
<file_sep>//
// JNWGarage+Data.swift
// JNWGarage
//
// Created by John on 2021/4/26.
//
#if os(iOS) || os(tvOS) //os(macOS)
import UIKit
#else
import AppKit
#endif
#if os(iOS) || os(tvOS) //os(macOS)
extension Data : JNWAdaptor { }
extension JNWAdaptorWrapper where Base == Data {
func tranferToJSONobject() -> [String: Any] {
let jsonObject = try? JSONSerialization.jsonObject(with: self.base, options: .allowFragments)
let dict = jsonObject as? [String: Any]
return dict ?? [:]
}
func transferToModel<T: Decodable>(modelType: T.Type) -> T? {
let decoder = JSONDecoder()
let model = try? decoder.decode(modelType, from: self.base)
return model
}
}
#else
#endif
<file_sep>//
// File.swift
//
//
// Created by John on 2021/5/14.
//
#if os(iOS) || os(tvOS) //os(macOS)
import UIKit
#else
import AppKit
#endif
@available(iOS 12.0, *)
func getCurrentAppearance() -> UIUserInterfaceStyle {
if #available(iOS 13.0, *) {
return UITraitCollection.current.userInterfaceStyle
} else {
return .unspecified
}
}
<file_sep>//
// JNWGarage+String.swift
// JNWGarage
//
// Created by John on 2021/4/26.
//
#if os(iOS) || os(tvOS) //os(macOS)
import UIKit
#else
import AppKit
#endif
#if os(iOS) || os(tvOS) //os(macOS)
extension String: JNWAdaptor { }
extension JNWAdaptorWrapper where Base == String {
func fromHex() -> UInt64? {
var result: UInt64 = 0
var hexStr = self.base
if hexStr.hasPrefix("0x") {
hexStr.removeFirst(2)
}
for (index, item) in hexStr.reversed().enumerated() {
var resInt: UInt64 = 0
let scanner = Scanner(string: String(item))
if (scanner.scanHexInt64(&resInt)) {
result += resInt * UInt64(pow(CGFloat(16), CGFloat(index)))
} else {
return nil
}
}
return result
}
}
#else
#endif
<file_sep>
import UIKit
public struct JNWAdaptorWrapper<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
public struct JNWAdaptorTypeWrapper<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
public protocol JNWAdaptor { }
public protocol JNWTypeAdaptor { }
extension JNWAdaptor {
public var jnw: JNWAdaptorWrapper<Self> {
get { return JNWAdaptorWrapper(self) }
set { }
}
}
extension JNWTypeAdaptor {
public static var jnw: JNWAdaptorTypeWrapper<Self.Type> {
get { return JNWAdaptorTypeWrapper(self) }
set { }
}
}
<file_sep>//
// JNWNetwork.swift
// JNWGarage
//
// Created by John on 2021/4/14.
//
#if os(iOS) || os(tvOS) //os(macOS)
import UIKit
#else
import AppKit
#endif
#if os(iOS) || os(tvOS) //os(macOS)
class JNWNetwork {
enum RequestMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
}
typealias SuccessResponseHandler = ((Data?, URLResponse?) -> ())
typealias FailureResponseHandler = ((Error?) -> ())
let networkQueueStr = "com.john.jnwnetwork.queue"
let networkQueue: DispatchQueue
let networkOperationQueue: OperationQueue
var callbackQueue: OperationQueue = .main
static let shared = JNWNetwork()
init() {
networkQueue = DispatchQueue(label: networkQueueStr,
qos: .background,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil)
networkOperationQueue = OperationQueue()
networkOperationQueue.maxConcurrentOperationCount = 1
networkOperationQueue.name = networkQueueStr
networkOperationQueue.qualityOfService = .background
}
public func callbackInQueue(queue: OperationQueue) -> Self {
callbackQueue = queue
return self
}
public func request<T: Decodable>(with url: String, method: JNWNetwork.RequestMethod, params: [String: Any]? = nil, successHandler: ((T?) -> ())?, failureHandler: FailureResponseHandler?) {
let callbackQueue = self.callbackQueue
request(with: url, method: method, params: params) { (data, response) in
let model = data?.jnw.transferToModel(modelType: T.self)
callbackQueue.addOperation {
successHandler?(model)
}
} failureHandler: { (error) in
callbackQueue.addOperation {
failureHandler?(error)
}
}
}
public func request(with url: String, method: JNWNetwork.RequestMethod, params: [String: Any]? = nil, successHandler: SuccessResponseHandler?, failureHandler: FailureResponseHandler?) {
var processedURL = url
var body: Data? = nil
switch method {
case .POST:
body = getData(from: params)
case .GET:
processedURL = makeupURL(with: url, params: params)
default:
print("not support")
}
guard let requestUrl = URL(string: processedURL) else { return }
let callbackQueue = self.callbackQueue
let op = JNWNetworkRequestOperation(url: requestUrl, method: method, body: body, callbackQueue: callbackQueue, successHandler: successHandler, failureHandler: failureHandler)
networkOperationQueue.addOperation(op)
}
func makeupURL(with urlString: String, params: [String: Any]?) -> String {
var resultUrl = urlString
guard let paramsTmp = params else { return urlString }
if resultUrl.contains("?") {
for item in paramsTmp {
resultUrl = "\(resultUrl)&\(item.key)=\(item.value)"
}
} else {
for item in paramsTmp.enumerated() {
if item.offset == 0 {
resultUrl = "\(resultUrl)?\(item.element.key)=\(item.element.value)"
} else {
resultUrl = "\(resultUrl)&\(item.element.key)=\(item.element.value)"
}
}
}
return resultUrl
}
func getData(from dict: [String: Any]?) -> Data? {
guard let dictTmp = dict else { return nil }
let data = try? JSONSerialization.data(withJSONObject: dictTmp, options: .fragmentsAllowed)
return data
}
}
class JNWNetworkRequestOperation: Operation {
let url: URL
let method: JNWNetwork.RequestMethod
let header: [String:String]?
let params: [String:String]?
let body: Data?
let cachePolicy: NSURLRequest.CachePolicy
let timeoutInterval: TimeInterval
let successHandler: JNWNetwork.SuccessResponseHandler?
let failureHandler: JNWNetwork.FailureResponseHandler?
var dataTask: URLSessionDataTask?
var callbackQueue: OperationQueue
init(url: URL,
method: JNWNetwork.RequestMethod,
header: [String:String]? = nil,
params: [String:String]? = nil,
body: Data? = nil,
cachePolicy: NSURLRequest.CachePolicy = .reloadIgnoringCacheData,
timeoutInterval: TimeInterval = 60.0,
callbackQueue: OperationQueue = .main,
successHandler: JNWNetwork.SuccessResponseHandler? = nil,
failureHandler: JNWNetwork.FailureResponseHandler? = nil) {
self.url = url
self.method = method
self.header = header
self.params = params
self.body = body
self.cachePolicy = cachePolicy
self.timeoutInterval = timeoutInterval
self.callbackQueue = callbackQueue
self.successHandler = successHandler
self.failureHandler = failureHandler
}
override func main() {
dataTask?.cancel()
dataTask = request()
dataTask?.resume()
}
func request() -> URLSessionDataTask {
var request = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
request.httpMethod = method.rawValue
request.httpBody = body
let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
// guard let sself = self else { return }
// let httpResponse = response as? HTTPURLResponse
// let statusCode = httpResponse?.statusCode
if let errorTmp = error {
self.callbackQueue.addOperation {
self.failureHandler?(errorTmp)
}
} else {
self.callbackQueue.addOperation {
self.successHandler?(data, response)
}
}
}
return dataTask
}
}
#else
#endif
| b2fe1df1ebf5835a02ba24b0fb14b1f32f46314b | [
"Markdown",
"Swift"
] | 7 | Markdown | JourneyJohn/JNWGarage | 5d11373f6b5ed8b99884dbe6e42e41488e6f779e | e7d3f4429e01b0d2b485baba1dc07370cc719754 |
refs/heads/master | <repo_name>nhemleben/Pendulum<file_sep>/TryODE.py
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
dt = 0.001
T= 5
t = np.arange(0.0, T, dt )
s = 1 + np.sin( 2*np.pi* t)
u = np.arange(0.0, T,dt)
u1 = np.arange(0.0, T,dt)
u11 = np.arange(0.0, T, dt)
#initial data
#u(0) =0
#u'(0) = 2 pi
#u''(0) = 0
#4 pi^2 u''(t) = - u(t)
u[0] = 0
u1[0] = 1
u11[0] = 0
for i in range(1,len(u)):
#standard Euler method
u1[i] = u1[i-1] + dt*u11[i-1]
u[i] = u[i-1] + dt*u1[i-1]
#Since ODE is cylical
#u11[i]= (-u[i]) /(4*np.pi*np.pi)
u11[i]= (4*np.pi*np.pi)*(-u[i])
fig, ax = plt.subplots()
ax.plot(t, s, 'y')
ax.plot(t, u, 'r')
ax.plot(t, u1, 'k')
ax.plot(t, u11, 'b')
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
plt.show()
<file_sep>/LargeAnglePendulum.py
%Solve the nonlinear pendulum equation
% -g \sin(\theta) = L \frac { d^2 \theta} {d t^2}
| 6e9c7724918cb23997e58b51d4168462c248b2d3 | [
"Python"
] | 2 | Python | nhemleben/Pendulum | 9424ae8ec5d46d4a044bf37dee0a387c96c662e6 | 6f78f1be8ed94a5763645767446133bed77f12cb |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Assignment___Chloe_Green
{
public class TransactionUI
{
private StockManager stockMgr;
public TransactionUI(StockManager sm)
{
this.stockMgr = sm;
}
public void addToStock(int itemCode, string itemName, int quantity, double price, DateTime date)
{
if (stockMgr.checkStock(itemCode) == true)
{
stockMgr.increaseStock(itemCode, quantity, price);
List<Stock> stocks = stockMgr.getStocks();
foreach (Stock stock in stocks)
{
if (stock.itemCode == itemCode)
{
itemName = stock.name;
}
}
}
else
{
stockMgr.addStock(new Stock(itemCode, itemName, price, quantity, date));
}
stockMgr.addTransaction(new TransactionLogAdd("Add", itemCode, itemName, price, date));
}
public void takeFromStock(int itemCode, string PersonName, DateTime date)
{
List<Stock> stocks = stockMgr.getStocks();
bool inStock = stockMgr.checkStock(itemCode);
string n = "";
int q = 0;
foreach (Stock stock in stocks)
{
if (stock.itemCode == itemCode)
{
q = stock.quantity;
}
}
if (inStock == false)
{
Console.WriteLine("Error. This item code doesn't exist");
}
else if ( q <= 0)
{
Console.WriteLine("Error. No more left in stock");
}
else
{
foreach (Stock stock in stocks)
{
if (stock.itemCode == itemCode)
{
stockMgr.removeStock(stock);
n = stock.name;
stockMgr.addPersonalUsage(new PersonalUsage(PersonName, itemCode, n, date));
stockMgr.addTransaction(new TransactionLogRemove("Take", itemCode, n, PersonName, date));
}
}
}
}
public List<Stock> viewInventoryReport()
{
List<Stock> stocks = stockMgr.getStocks();
List<Stock> stockList = new List<Stock>();
foreach (Stock stock in stocks)
{
if (stock.quantity > 0)
{
stockList.Add(stock);
}
}
return stockList;
}
public List<Stock> viewFinancialReport()
{
return stockMgr.getStocks();
}
public List<TransactionLog> viewtransactionLog()
{
return stockMgr.getTransactions();
}
public List<PersonalUsage> viewPersonalUsage(string PersonName)
{
return stockMgr.getUsage(PersonName);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Assignment___Chloe_Green
{
public class TransactionLogAdd : TransactionLog
{
public double price { get; }
public TransactionLogAdd(string type, int itemCode, string name, double price, DateTime d) : base(type, itemCode, name ,d)
{
this.price = price;
}
public override string ToString()
{
return Convert.ToString(price);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Assignment___Chloe_Green
{
public class PersonalUsage
{
public string personName { get; }
public int itemCode { get; }
public string name { get; }
public DateTime date { get; }
public PersonalUsage(string personName, int itemCode, string itemName, DateTime date)
{
this.personName = personName;
this.itemCode = itemCode;
this.name = itemName;
this.date = date;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Assignment___Chloe_Green
{
public abstract class TransactionLog
{
public string type { get; }
public int itemCode { get; }
public string name { get; }
public DateTime date { get; }
public TransactionLog(string type, int itemCode, string name, DateTime d)
{
this.type = type;
this.itemCode = itemCode;
this.name = name;
this.date = d;
}
public abstract override string ToString();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Assignment___Chloe_Green
{
public class Stock
{
public int itemCode { get; }
public string name { get; }
public double price { get; set; }
public int quantity { get; set; }
public DateTime date { get; }
public Stock(int itemCode, string itemName, double price, int quantity, DateTime date)
{
this.itemCode = itemCode;
this.name = itemName;
this.price = price;
this.quantity = quantity;
this.date = date;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace Assignment___Chloe_Green
{
class Program
{
private static TransactionUI trnUI;
private static StockManager stockMgr;
static void Main(string[] args)
{
stockMgr = new StockManager();
trnUI = new TransactionUI(stockMgr);
int option = DisplayMenu();
while (option != 7)
{
switch (option)
{
case 1:
AddToStock();
break;
case 2:
TakeFromStock();
break;
case 3:
InventoryReport();
break;
case 4:
FinancialReport();
break;
case 5:
TransactionLog();
break;
case 6:
PersonalUsage();
break;
}
option = DisplayMenu();
}
}
private static int DisplayMenu()
{
Console.WriteLine("\n1. Add to Stock");
Console.WriteLine("2. Take from Stock");
Console.WriteLine("3. Display Inventory Report");
Console.WriteLine("4. Display Financial Report");
Console.WriteLine("5. Display Transaction Log");
Console.WriteLine("6. Display Personal Usage Report");
Console.WriteLine("7. Exit");
Console.WriteLine("\n");
bool option_chosen = false;
int answer = 0;
while (option_chosen != true)
{
answer = ValidateInt("Option");
if (answer > 0 && answer < 8)
{
option_chosen = true;
}
else
{
Console.WriteLine("ERROR Option Invalid");
}
}
return answer;
}
private static int ValidateInt(string type)
{
bool valid = false;
int value = 0;
Console.Write("Enter " + type + " > ");
string answer = Console.ReadLine();
while (valid != true)
{
if (answer.Length > 0)
{
try
{
value = Convert.ToInt32(answer);
if (value >= 1)
{
valid = true;
}
else
{
Console.WriteLine("ERROR " + type + " invalid");
Console.Write("Enter " + type + " > ");
value = Convert.ToInt32(Console.ReadLine());
}
}
catch (OverflowException)
{
Console.WriteLine("ERROR " + type + " invalid");
Console.Write("Enter " + type + " > ");
answer = Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("ERROR " + type + " invalid");
Console.Write("Enter " + type + " > ");
answer = Console.ReadLine();
}
}
else
{
Console.WriteLine("ERROR " + type + " invalid");
Console.Write("Enter " + type + " > ");
answer = Console.ReadLine();
}
}
return value;
}
private static double ValidateDouble(string type)
{
bool valid = false;
double value = 0;
Console.Write("Enter " + type + " > ");
string answer = Console.ReadLine();
while (valid != true)
{
if (answer.Length > 0)
{
try
{
value = double.Parse(answer);
if (value > 0)
{
valid = true;
}
else
{
Console.WriteLine("ERROR " + type + " invalid");
Console.Write("Enter " + type + " > ");
value = double.Parse(Console.ReadLine());
}
}
catch (OverflowException)
{
Console.WriteLine("ERROR " + type + " invalid");
Console.Write("Enter " + type + " > ");
answer = Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("ERROR " + type + " invalid");
Console.Write("Enter " + type + " > ");
answer = Console.ReadLine();
}
}
else
{
Console.WriteLine("ERROR " + type + " invalid");
Console.Write("Enter " + type + " > ");
answer = Console.ReadLine();
}
}
return value;
}
private static string ValidateString(string type)
{
bool valid = false;
Console.Write("Enter " + type + " > ");
string value = Console.ReadLine();
while (valid != true)
{
if ((value.Length <= 30) && (value.Length >= 1))
{
valid = true;
}
else
{
Console.WriteLine("ERROR " + type + " invalid");
Console.Write("Enter " + type + " > ");
value = Console.ReadLine();
}
}
return value;
}
private static void AddToStock()
{
int itemcode = ValidateInt("Item Code");
string name = "";
int quantity = 0;
double price = 0;
if (stockMgr.checkStock(itemcode) == true)
{
Console.WriteLine("This item code already exists. Please enter the quantity and price to be added:");
quantity = ValidateInt("Quantity");
price = ValidateDouble("Price");
}
else
{
name = ValidateString("Name");
quantity = ValidateInt("Quantity");
price = ValidateDouble("Price");
}
trnUI.addToStock(itemcode, name, quantity, price, DateTime.Now);
}
private static void TakeFromStock()
{
int ic = ValidateInt("Item Code");
string pn = ValidateString("Name of Person Taking Item");
trnUI.takeFromStock(ic, pn, DateTime.Now);
}
private static void InventoryReport()
{
List<Stock> stocklist = trnUI.viewInventoryReport();
Console.WriteLine("\nInventory Report");
Console.WriteLine("\t{0, -12} {1, -18} {2, -12}","Item Code", "Item Name", "Quantity");
foreach (Stock stock in stocklist)
{
Console.WriteLine("\t{0, -12} {1, -18} {2, -12}",
stock.itemCode.ToString(),
stock.name,
stock.quantity);
}
}
private static void FinancialReport()
{
List<Stock> stocklist = trnUI.viewFinancialReport();
Console.WriteLine("\nFinancial Report");
Console.WriteLine("\t{0, -12} {1, -20} {2, -12}", "Item Code", "Item Name", "Total Cost");
double total_expenditure = 0;
foreach (Stock stock in stocklist)
{
Console.WriteLine("\t{0, -12} {1, -20} {2, -12}", stock.itemCode, stock.name, "£" + string.Format("{0:0.00}", stock.price));
total_expenditure += stock.price;
}
Console.WriteLine("\n\tTotal spent on items: £" + string.Format("{0:0.00}", total_expenditure));
}
private static void TransactionLog()
{
List<TransactionLog> transactions = trnUI.viewtransactionLog();
Console.WriteLine("\nTransaction Log");
Console.WriteLine("\t{0, -12} {1, -12} {2, -20} {3, -20} {4, -12} {5, -12}", "Type", "Item Code", "Item Name", "Person Name", "Price Paid", "Date");
foreach (TransactionLog transaction in transactions)
{
if (transaction.type == "Add")
{
Console.WriteLine("\t{0, -12} {1, -12} {2, -20} {3, -20} {4, -12} {5, -12}",
transaction.type,
transaction.itemCode,
transaction.name,
"--",
"£" + string.Format("{0:0.00}", double.Parse(transaction.ToString())),
transaction.date);
}
else
{
Console.WriteLine("\t{0, -12} {1, -12} {2, -20} {3, -20} {4, -12} {5, -12}",
transaction.type,
transaction.itemCode,
transaction.name,
transaction.ToString(),
"--",
transaction.date);
}
}
}
private static void PersonalUsage()
{
string n = ValidateString("your name");
int count = 0;
List<PersonalUsage> personalusage = trnUI.viewPersonalUsage(n);
foreach (PersonalUsage p in personalusage)
{
count += 1;
}
if (count == 0)
{
Console.WriteLine("ERROR Person doesn't exist");
}
else
{
Console.WriteLine("\nPersonal Usage");
Console.WriteLine("\t{0, -12} {1, -20} {2, -12}", "Item Code", "Person Name", "Date Taken");
foreach (PersonalUsage p in personalusage)
{
Console.WriteLine("\t{0, -12} {1, -20} {2, -12}",
p.itemCode,
p.personName,
p.date);
}
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Assignment___Chloe_Green
{
public class StockManager
{
private List<Stock> stocks = new List<Stock>();
private List<TransactionLog> tranLogs = new List<TransactionLog>();
private List<PersonalUsage> personUsgs = new List<PersonalUsage>();
public bool checkStock(int itemCode)
{
bool inStock = false;
foreach (Stock stock in stocks)
{
if (stock.itemCode == itemCode)
{
inStock = true;
}
}
return inStock;
}
public void increaseStock(int itemCode, int quantity, double price)
{
foreach (Stock stock in stocks)
{
if (stock.itemCode == itemCode)
{
stock.price += price;
stock.quantity += quantity;
}
}
}
public void addStock(Stock s)
{
stocks.Add(s);
}
public void removeStock(Stock s)
{
s.quantity--;
}
public void addTransaction(TransactionLog t)
{
tranLogs.Add(t);
}
public void addPersonalUsage(PersonalUsage p)
{
personUsgs.Add(p);
}
public List<TransactionLog> getTransactions()
{
return tranLogs;
}
public List<Stock> getStocks()
{
return stocks;
}
public List<PersonalUsage> getUsage(string personName)
{
List<PersonalUsage> pu = new List<PersonalUsage>();
foreach (PersonalUsage p in personUsgs)
{
if ((p.personName).ToLower() == personName.ToLower())
{
pu.Add(p);
}
}
return pu;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Assignment___Chloe_Green
{
public class TransactionLogRemove : TransactionLog
{
public string personName { get; }
public TransactionLogRemove(string type, int itemCode, string name, string personName, DateTime d) : base(type, itemCode, name, d)
{
this.personName = personName;
}
public override string ToString()
{
return personName;
}
}
}
| 7ea21eefca18eaa60cf7b86ecb68e91ca45f1149 | [
"C#"
] | 8 | C# | ChloeAGreen747/Stationary-Management-System | ca193d067ab553832d53e7d07ffa5f4a3156d0b4 | fb22e4244daa3031605fc1156b7fdb563a2fff13 |
refs/heads/master | <repo_name>Claudiazhaoya/Twitter<file_sep>/twitter_alamofire_demo/ComposeTweetViewController.swift
//
// ComposeTweetViewController.swift
// twitter_alamofire_demo
//
// Created by <NAME> on 12/29/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class ComposeTweetViewController: UIViewController{
var delegate: ComposeViewControllerDelegate?
@IBOutlet weak var tweetButton: UIBarButtonItem!
@IBOutlet weak var composeTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func closeButtonTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func tweetButtonTapped(_ sender: Any) {
APIManager.shared.composeTweet(with: composeTextView.text) { (tweet, error) in
if let error = error {
print(error.localizedDescription)
} else if let tweet = tweet {
self.delegate?.did(post: tweet)
}
}
}
}
protocol ComposeViewControllerDelegate {
func did(post: Tweet)
}
<file_sep>/twitter_alamofire_demo/TimelineViewController.swift
//
// TimelineViewController.swift
// twitter_alamofire_demo
//
// Created by <NAME> on 6/18/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class TimelineViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
@IBOutlet weak var tableView: UITableView!
var tweets: [Tweet] = []
var refreshControl: UIRefreshControl!
var tweetMaxId: Int?
private var isMoreTweetsLoading = false
var userForSegue: User?
@IBAction func logoutButtonTapped(_ sender: Any) {
APIManager.shared.logout()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 40
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(fetchTweets(forInfiniteScroll:)), for: .valueChanged)
refreshControl.backgroundColor = UIColor.groupTableViewBackground
tableView.addSubview(refreshControl)
setNavigationBarButtons()
let insets = tableView.contentInset;
tableView.contentInset = insets
fetchTweets(forInfiniteScroll: false)
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !isMoreTweetsLoading {
let ScrollViewContentHeight = self.tableView.contentSize.height
let scrollOffsetThreshold = ScrollViewContentHeight - self.tableView.bounds.size.height
if scrollView.contentOffset.y > scrollOffsetThreshold && self.tableView.isDragging && !tweets.isEmpty {
isMoreTweetsLoading = true
self.fetchTweets(forInfiniteScroll: true)
}
}
}
func fetchTweets(forInfiniteScroll: Bool) {
APIManager.shared.getHomeTimeLine { (tweets, error) in
if let tweets = tweets {
self.tweets = tweets
self.tableView.reloadData()
} else if let error = error {
print("Error getting home timeline: " + error.localizedDescription)
}
self.refreshControl.endRefreshing()
}
}
func setNavigationBarButtons() {
let composeImage = UIImage(named: "edit-icon")
let composeButton = UIBarButtonItem(image: composeImage, style: .plain, target: self, action: #selector(composeButtonTapped(sender:)))
self.navigationController?.navigationBar.barTintColor = UIColor.white
self.navigationController?.navigationBar.isTranslucent = false
self.navigationItem.leftBarButtonItem = composeButton
}
func composeButtonTapped(sender: UIBarButtonItem) {
performSegue(withIdentifier: "ComposeTweetSegue", sender: self)
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TweetCell") as! TweetCell
let tweet = tweets[indexPath.row]
if let url = tweet.profileUrl {
cell.profilePictureImageView.setImageWith(url)
}
cell.usernameLabel.text = tweet.user?.name
cell.userHandleLabel.text = "@\((tweet.user?.screenname)!)"
cell.tweetTextLabel.text = tweet.text
cell.favoriteCount.text = "\(tweet.favoriteCount)"
cell.retweetCount.text = "\(tweet.retweetCount)"
cell.tweet = tweet
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension TimelineViewController: ComposeViewControllerDelegate {
func did(post: Tweet) {
dismiss(animated: true, completion: nil)
}
}
<file_sep>/twitter_alamofire_demo/TweetCell.swift
//
// TweetCell.swift
// twitter_alamofire_demo
//
// Created by <NAME> on 6/18/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import Lottie
protocol ProfileViewSegueDelegate {
func profileImageTapped(user: User)
}
class TweetCell: UITableViewCell {
var delegate: ProfileViewSegueDelegate?
@IBOutlet weak var profilePictureImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var userHandleLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var retweetCount: UILabel!
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var favoriteCount: UILabel!
var tweet: Tweet! {
didSet {
tweetTextLabel.text = tweet.text
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
profilePictureImageView.layer.cornerRadius = 5
profilePictureImageView.clipsToBounds = true
retweetCount.text = "\(String(describing: tweet?.retweetCount))"
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
profilePictureImageView?.isUserInteractionEnabled = true
profilePictureImageView.addGestureRecognizer(tapGestureRecognizer)
}
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
delegate?.profileImageTapped(user: (tweet?.user)!)
}
@IBAction func onHeartTap(_ sender: Any) {
favoriteCount.text = "\(Int(favoriteCount.text!)! + 1)"
favoriteButton.setImage(UIImage(named: "favor-icon-red"), for: .normal)
}
@IBAction func onRetweetTap(_ sender: Any) {
retweetCount.text = "\(Int(retweetCount.text!)! + 1)"
retweetButton.setImage(UIImage(named: "retweet-icon-green"), for: .normal)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 882b52d911245672f8a2bb8822ec42d30e2522e4 | [
"Swift"
] | 3 | Swift | Claudiazhaoya/Twitter | bb6637d326f95a484eddb2b2a1fdef022d65c044 | d5d4889aa199ce32d3fb0f04e53e9d5b74830fb9 |
refs/heads/master | <repo_name>joncaneiro/ruby-enumerables-hash-practice-emoticon-translator-lab-dumbo-web-100719<file_sep>/lib/translator.rb
require 'pry'
require 'yaml'
def load_library(file_path)
emoticons = YAML.load_file(file_path)
new_hash = {
'get_meaning' => {},
'get_emoticon' => {}
}
emoticons.each do |keyvalue, emo|
english = emo[0]
japanese = emo[1]
new_hash['get_meaning'][japanese] = keyvalue
new_hash['get_emoticon'][english] = japanese
end
new_hash
end
def get_japanese_emoticon(file_path, emoticon)
emoticons = load_library(file_path)
message = "Sorry, that emoticon was not found"
translation = emoticons["get_emoticon"]
translation.each do |key, value|
if key == emoticon
return value
end
end
message
end
def get_english_meaning(file_path, emoticon)
emoticons = load_library(file_path)
message = "Sorry, that emoticon was not found"
translation = emoticons['get_meaning']
translation.each do |key, value|
if key == emoticon
return value
end
end
message
end
| 28e7fe00a4edc10e4c60d8547069ed65bc5df80e | [
"Ruby"
] | 1 | Ruby | joncaneiro/ruby-enumerables-hash-practice-emoticon-translator-lab-dumbo-web-100719 | eb40e63c4225313865770dd821a34eeede1323cc | 9be4c44b09dca605ce59a457575ee9a843d6ef95 |
refs/heads/master | <repo_name>jgam/django-todo<file_sep>/jgamdjango/jgamdjango/todo/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Todos(models.Model):
user = models.CharField(max_length=32)
todo = models.TextField(null=True) # Json- serialized version
| 5d5928ff5455bf836a2c2485956b8b6e884d6798 | [
"Python"
] | 1 | Python | jgam/django-todo | 617dfafc942670740eba91c0899ee99c606b809e | b644753e45454a65c60b5c2a43b8e8cee2fb9918 |
refs/heads/master | <repo_name>rcafalchio/nodejs-projects<file_sep>/casa-do-codigo/app/config/expressConfig.js
//CARRAGA OS MÓDULOS DA APPLICAÇÃO
var express = require('express');
var load = require('express-load');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
module.exports = function (){
console.log('carregando as congurações...')
var app = express();
app.use(express.static('./app/public'))
app.set('view engine','ejs');
app.set('views','./app/views');
//Em java script é chamado de middleware - é semelhante ao filtro do spring
//utilizado para recuperar os parametros do form
//fala que a app aceita o formato urlencoded
app.use(bodyParser.urlencoded({extended: true}));
//fala que a app aceita o formato json
app.use(bodyParser.json());
app.use(expressValidator());
load('routes', {cwd: 'app'}).then('infra').then('helpers').into(app);
//É importate que este middleware que eu criei esteja após o load das rotas
//, para que ele possa encontrar as rotas após ajustar o erro.
app.use(function(req,res,next){
res.status(404).render('erros/404');
});
app.use(function(error,req,res,next){
if(process.env.NODE_ENV == 'production'){
console.log("Erro inesperado!!!");
console.log(error);
res.status(500).render('erros/500');
return;
}else{
next(error);
}
});
console.log('Congurações carregadas com sucesso!')
return app;
}<file_sep>/casa-do-codigo/cadastra-livros-client.js
var http = require('http');
//Configura as informações para a chamada HTTP
var configuracoes = {
hostname:'localhost'
,port:3000
,path:'/produtos/salva'
,method: 'post'
//Coloca no header http, as informações do tipo de retorno que eu(client) aceito
,headers: {'Accept':'application/json'
,'Content-type':'application/json'
}
}
var client = http.request(configuracoes,
function(res){
console.log(res.statusCode);
res.on('data',
function(body){
console.log('Corpo'+body)
}
);
}
);
var produto = {
titulo : '',
descricao: 'node, javascript e um pouco sobre http',
preco: '100'
}
console.log('Antes da chamada - RICARDO');
client.end(JSON.stringify(produto));
console.log('Depois da chamada - RICARDO');<file_sep>/casa-do-codigo/app/infra/connectionFactory.js
var mysql = require('mysql');
function createDBConnection(){
if(!process.env.NODE_ENV || process.env.NODE_ENV == 'production'){
return mysql.createConnection({
host : 'localhost',
user : 'casadocodigo_user',
password : '<PASSWORD>',
database : 'casadocodigo'
});
}
if(process.env.NODE_ENV == 'test'){
console.log('Carregando conexão no banco de teste.');
return mysql.createConnection({
host : 'localhost',
user : 'root',
password : '<PASSWORD>',
database : 'casadocodigo_nodejs_test'
});
}
}
//Função Wrapper - embrulha a função acima
module.exports = function(){
return createDBConnection;
}
<file_sep>/README.md
# node-projects
My node projects.
<file_sep>/casa-do-codigo/app/routes/homeRotas.js
function validarErro(err,res){
if(err != null){
console.log('Ocorreu um erro!!!');
console.log('Erro = ' + err);
//res.render("error");
return next(erros);
}
}
module.exports = function(app){
app.get('/',function(req,res){
var connection = app.infra.connectionFactory();
var produtosDAO = new app.infra.ProdutosDAO(connection);
produtosDAO.lista(
function (err, result){
validarErro(err,res);
res.format({
//Caso o cliente informou no cabeçalho html - então retorna html
html: function(){
res.render("home/index",{livros:result});
},
//Caso o cliente informou no cabeçalho json - então retorna json
json: function(){
res.json(result);
}
});
});
connection.end();
});
}
<file_sep>/casa-do-codigo/app/infra/ProdutosDAO.js
function ProdutosDAO(connection){
this._connection = connection;
}
ProdutosDAO.prototype.lista = function(callback){
this._connection.query('SELECT * FROM TB_CASADOCODIGO_PRODUTOS', callback);
}
ProdutosDAO.prototype.salvar = function(produto, callback){
this._connection.query('SELECT MAX(COD_PRODUTO) "COD_PRODUTO" FROM TB_CASADOCODIGO_PRODUTOS'
, function(err, result){
var id = result[0].COD_PRODUTO + 1;
var query = `INSERT INTO TB_CASADOCODIGO_PRODUTOS
VALUES ( ${id}
,'${produto.titulo}'
,'${produto.descricao}'
,${produto.preco})
`;
console.log('QUERY = '+query);
this._connection.query(query,callback);
});
}
module.exports = function(){
return ProdutosDAO;
}<file_sep>/casa-do-codigo/app/routes/produtosRotas.js
function validarErro(err,res){
if(err != null){
console.log('Ocorreu um erro!!!');
console.log('Erro = ' + err);
//res.render("error");
return next(erros);
}
}
function carregarListaProdutos(app){
return function(req,res){
var connection = app.infra.connectionFactory();
var produtosDAO = new app.infra.ProdutosDAO(connection);
produtosDAO.lista(
function (err, result){
validarErro(err,res);
res.format({
//Caso o cliente informou no cabeçalho html - então retorna html
html: function(){
res.render("produtos/lista",{lista:result});
},
//Caso o cliente informou no cabeçalho json - então retorna json
json: function(){
res.json(result);
}
});
});
connection.end();
};
}
function carregarRotas(app){
app.get('/produtos/cadastro',function(req,res){
res.render('produtos/inclui',{errosValidacao:{},produto:{}});
});
app.post('/produtos/salva',
function(req,res){
var produto = req.body;
//Bloco de validação
req.assert('titulo','O titulo é obrigatório').notEmpty();
req.assert('preco','Formato inválido').isFloat();
var erros = req.validationErrors();
if(erros){
res.format({
//Caso o cliente informou no cabeçalho html - então retorna html
html: function(){
res.status(400).render('produtos/inclui',{errosValidacao:erros,produto:produto});
},
//Caso o cliente informou no cabeçalho json - então retorna json
json: function(){
res.status(400).json(erros);
}
});
return;
}
var connection = app.infra.connectionFactory();
var produtosDAO = new app.infra.ProdutosDAO(connection);
produtosDAO.salvar(produto,
function(err,result){
validarErro(err,res);
connection.end();
res.redirect('/produtos');
}
);
}
);
app.get('/produtos', carregarListaProdutos(app));
}
module.exports = function (app){
console.log('carregando rotas do produto...')
carregarRotas(app);
console.log('rotas carregadas com sucesso! ')
}<file_sep>/casa-do-codigo/app/helpers/requestHelper.js
/*function validarErro(err,res){
if(err != null){
console.log('Ocorreu um erro!!!');
console.log('Erro = ' + err);
//res.render("error");
}
}
//Função Wrapper - embrulha a função acima
module.exports = function(err,res){
return validarErro(err,res);
}*/
| 4bd3475a230dcce42e6c5caa8553f2d3f08b3cb9 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | rcafalchio/nodejs-projects | 3464cb8ea4077d8cb4d94a9ebe08b6b48e732821 | dfa3bcb9f3565db72a4f8f8dceda9ba2fe957bd4 |
refs/heads/master | <repo_name>HPavelS/tests<file_sep>/src/vstrFuncVP.kt
private data class Grocery(
val name: String, val category: String,
val unit: String, val unitPrice: Double,
val quantity: Int)
fun main() {
val groceries = listOf(
Grocery("Tomatoes", "Vegetable", "lb", 3.0, 3),
Grocery("Mushrooms", "Vegetable", "lb", 4.0, 1),
Grocery("Bagels", "Bakery", "Pack", 1.5, 2),
Grocery("Olive oil", "Pantry", "Bottle", 6.0, 1),
Grocery("Ice cream", "Frozen", "Pack", 3.0, 2)
)
val highestUnitPrice = groceries.maxByOrNull { it.unitPrice }
val sum = groceries.sumBy { it.quantity }
val sumDouble = groceries.sumByDouble { x:Grocery -> x.unitPrice }
val totalPrice = groceries.sumByDouble { it.quantity * it.unitPrice }
println(highestUnitPrice)
println(sum)
println(sumDouble)
println(totalPrice)
val vegetables = groceries.filter { it.category == "Vegetable" }
println(vegetables)
val unitPriceOver3 = groceries.filter { it.unitPrice > 3.0 }
println(unitPriceOver3)
val inst = listOf(1,2,3,4)
val mapInst = inst.map{it*2}
println(mapInst)
val groceryName = groceries.map { it.name }
println(groceryName)
val halfUnitPrice = groceries.map { it.unitPrice * 0.5 }
println(halfUnitPrice)
val newPrice = groceries.filter { it.unitPrice > 3}.map { it.unitPrice * 2 }
println(newPrice)
val categogies = groceries.groupBy { it.category }
println(categogies)
categogies.forEach{ (key, item) ->
// println(item)
println("$key is ${item.map { it.name }}")
}
val listArr = arrayOf(1,2,3)
val fold = listArr.fold(0){init, item -> init + item}
println(fold)
println(groceries.fold(""){string, it -> "$string ${it.name}" })
println(groceries.fold(100.0){init, it -> init - it.unitPrice * it.quantity})
}<file_sep>/src/01KotlinInActionStart.kt
fun main() {
val people = listOf(Person("Masha"), Person("Pasha", 37))
println("The oldest is: ${people.maxByOrNull { it.age ?: 0 }}")
println("The youngest is: ${people.minByOrNull { it.age ?: 0 }}")
println(people[0])
next()
}
private data class Person(val name: String = "", val age: Int? = null)
<file_sep>/src/lyambda.kt
fun main() {
println("-------Простые лямбда--------")
val l1 = {b:Int -> b + 5}
val l2 = {b:Int, c:String -> c + b}
val l3: (Int) -> Int = {it + 9}
val l4 = { println("Hello")}
val lText = {"Text"}
var result = l1.invoke(4)
println(result)
println(l2(1, "10"))// можно без invoke
println(lText.invoke())
println(l3(8))
l4()
next()
println("-------лямбда в функцию----------")
val x = 20.2
val y = 4.8
println("Периметр прямоугольника = " + lFun(x, y) {a, b ->
println("$a $b")
(a+b)*2})
println("площадь прямоугольника = " + lFun(x, y) {a, b -> a*b})
println("Периметр квадрата = " + lFun2{it*4} )
next()
println("-----------возврат лямбды из фукнции-----------")
val l5 = lReturn("toTons")
val mass = 10.2
println(l5(mass))
println(lReturn("toCentners")(20.0))
next()
println("-----------Определить два лямбда-выражения для преобразований-----------")
//Определить два лямбда-выражения для преобразований
val kgsToPounds = { x: Double -> x * 2.204623 }
val poundsToUSTons = { x: Double -> x / 2000.0 }
//Объединить два выражения
val kgsToUSTons = combine(kgsToPounds, poundsToUSTons)
//Выполнить лямбда-выражение kgsToUSTons
val usTons = kgsToUSTons(1000.0) //1.1023115
println(usTons)
next()
println(myFun1 (5){it*3})
next()
println(poundsToUSTons(2.0))
next()
}
private fun lFun(x: Double, y:Double, formula: (Double, Double) -> Double): Double {
return (formula(x,y))
}
private fun lFun2(formula: (Double) -> Double): Double {
return (formula(5.0))
}
private fun lReturn(param: String): (Double) -> Double{
when(param){
"toTons" -> return {it/1000}
"toCentners" -> return {x -> x/100}
else -> return {it}
}
}
private fun combine(lambda1: (Double) -> Double,
lambda2: (Double) -> Double): (Double) -> Double {
return { x: Double -> lambda2(lambda1(x)) }
}
private fun myFun1(x: Int = 6, y: (Int) -> Int = { it }): Int {
return y(x)
}
<file_sep>/src/collections.kt
fun main() {
val list = listOf("1","2",null)
list.forEach { print("$it ") }
next()
list.forEachIndexed { index, data -> println("| $index -> $data ") }
if (list.contains("2"))
println("index = ${list.indexOf("2")}")
println("element index 0 = ${list[0]}")
println("-------------------------------")
val mutList = mutableListOf("first", "second", "end")
mutList.add("plus")
mutList.forEach { print("$it ")}
next()
println("Находим элемен списка и меняем его")
if (mutList.contains("end"))
mutList[mutList.indexOf("end")] = "three"
mutList.forEach { print("$it ")}
next()
mutList.add(2, "newElement")
mutList.forEach { print("$it ")}
next()
if (mutList.contains("newElement"))
mutList.remove("newElement")
mutList.forEach { print("$it ")}
next()
if (mutList.size > 0)
mutList.removeAt(0)
mutList.forEach { print("$it ")}
next()
if (mutList.size > 0)
mutList[0] = "coffee"
mutList.forEach { print("$it ")}
next()
println("Сортировка")
val intMutList = mutableListOf(2,1,0,3,4,5,6,7,8)
intMutList.sort()
// intMutList.reverse()
intMutList.forEach {print("$it ")}
next()
var toAdd = listOf( 9, 10, 11)
intMutList.addAll(toAdd)
intMutList.forEach {print("$it ")}
next()
println ("сравниваем два списка и оставляем только те элементы которые совпадают")
val toRetain = listOf(2,1,0,3,4,5,6, 222)
intMutList.retainAll(toRetain)
intMutList.forEach {print("$it ")}
next()
println ("Перемешиваем все элементы")
intMutList.shuffle()
intMutList.forEach {print("$it ")}
next()
intMutList.sort()
println("уничтожаем все содержимое что бы размер был равен 0")
intMutList.clear()
intMutList.forEach {print("$it ")}
print("размер = ${intMutList.size}")
next()
toAdd = listOf(0,1,2,3,4,5,6,7,8)
intMutList.addAll(toAdd)
intMutList.forEach {print("$it ")}
next()
println("Копируем список но это будет List а не MutableList")
val copyList = intMutList.toList()
copyList.forEach { print("$it ") }
next()
println("Копируем список но это будет MutableList")
val copyList2 = intMutList.toMutableList()
copyList2.forEach { print("$it ") }
next()
println("Создаем коллекцию Set и видим что она убирает все дубликаты в момент создания списка")
val friendSet = setOf("Pavel", "Andrey", "Katya", "Katya", "Katya", "Pavel", "Andrey")
friendSet.forEach { println("$it ") }
next()
println("добавляем все элементы списка toAdd к списку MutableSet")
toAdd = listOf(0,1,2,0,4,4,6,2,8)
var setInt = mutableSetOf<Int>()
setInt.addAll(toAdd)
setInt.forEach { print("$it ") }
next()
println("копируем toAdd в MutableSet")
setInt = toAdd.toMutableSet()
setInt.forEach { print("$it ") }
next()
println("проверяем есть ли одинаковые элементы в toAdd")
if (toAdd.size != toAdd.toSet().size)
println("есть дубликаты")
else println("нет дубликатов")
next()
println("Создаем Map")
val r1 = Recipe("Chicken Soup")
val r2 = Recipe("Quinoa Salad")
val r3 = Recipe("Thai Curry")
val recipeMap = mapOf("Recipe1" to r1, "Recipe2" to r2, "Recipe3" to r3)
recipeMap.forEach { (key, item) -> print("$key -> $item ") }
println("")
print(recipeMap)
next()
println("Проверка ключа")
print("такой ключ = ${recipeMap.containsKey("Recipe1")}")
next()
println("Проверка значения")
val recipeToCheck = Recipe("Chicken Soup")
if (recipeMap.containsValue(recipeToCheck))
println("Такое значение существует")
next()
println("Получаем значение из ключа")
if (recipeMap.containsKey("Recipe1")) {
val value = recipeMap.getValue("Recipe1")
println(value)
}
next()
println("создаем и добавляем еще один элемент к mutableMafOf")
val mutMap = mutableMapOf("key1" to "1", "key2" to "2")
mutMap.put("key3", "3")
mutMap["key4"] = "4"
println(mutMap)
next()
println("добавляем несколько элементов к mutableMapOf")
val mutAdd = mapOf("key5" to "5", "key6" to "6")
mutMap.putAll(mutAdd)
println(mutMap)
next()
println("удаляем элеаменты mutableMapOf")
mutMap.remove("key6")
println(mutMap.remove("key5", "5")) //удалит только если есть ключ и в нем указанные данные
println(mutMap)
next()
println("копируем mutableMapOf в List и в Set")
val mapToList = mutMap.toList()
println(mapToList)
val mapToSet = mutMap.entries
println(mapToList)
next()
println("копируем только value значения и толко keys в разные списки")
val mapToListKeys = mutMap.keys.toList()
println(mapToListKeys)
val mapToListValues = mutMap.values.toList()
println(mapToListValues)
next()
println("проверяем нет ли одинаковых значений в Map")
mutMap["key5"] = "4"
if (mutMap.size > mutMap.values.toSet().size)
println(true)
else
println(false)
next()
}
fun next() {
println("")
println("-------------------------------")
}
private data class Recipe(val name:String = "")
<file_sep>/src/test1.kt
private class Solution {
fun reverse(x: Int): Int {
var y = x.toString()
y = y.reversed()
return y.toInt()
}
}
fun main() {
val solution = Solution()
println(solution.reverse(-123))
} | d2ce03d670cadc3a9b2345077d4f7c7e0f4deed6 | [
"Kotlin"
] | 5 | Kotlin | HPavelS/tests | d843cf32afc3f81e44ce4fd39d76fd3bcfb39023 | eae370ea3b31c948a3a62f4a25af3d0e54545c77 |
refs/heads/master | <repo_name>MDP-Internship/crossword<file_sep>/src/index.jsx
import ReactDOM from 'react-dom'
import React, { Component } from 'react'
import { Container, Row, Col } from 'reactstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
import Puzzle from "./puzzleArea.jsx"
import Questions from "./questionArea.jsx"
export default class CrosswordPage extends Component {
render() {
return (
<Container className="mt-5 p-0">
<Row>
<Col md="6 " className="">
<Puzzle />
</Col>
<Col md="4" className="">
<Questions />
</Col>
</Row>
</Container>
)
}
}
ReactDOM.render(
<CrosswordPage />,
document.getElementById("root")
)
<file_sep>/src/data/word.js
const data = [
{
"clue": "<NAME>",
"answer": "C\u0130MR\u0130",
"position": 1,
"orientation": "across",
"startx": 1,
"starty": 1
},
{
"clue": "Beddua",
"answer": "AH",
"position": 2,
"orientation": "across",
"startx": 7,
"starty": 1
},
{
"clue": "Solunumun bir s\u00fcre durmas\u0131",
"answer": "APNE",
"position": 3,
"orientation": "across",
"startx": 1,
"starty": 2
},
{
"clue": "Y\u00fcce, y\u00fcksek",
"answer": "AL\u0130",
"position": 4,
"orientation": "across",
"startx": 6,
"starty": 2
},
{
"clue": "Bizmut\u2019un simgesi",
"answer": "B\u0130",
"position": 5,
"orientation": "across",
"startx": 1,
"starty": 3
},
{
"clue": "Havadar",
"answer": "YELE\u00c7",
"position": 6,
"orientation": "across",
"startx": 4,
"starty": 3
},
{
"clue": "Su yosunu",
"answer": "ALG",
"position": 7,
"orientation": "across",
"startx": 1,
"starty": 4
},
{
"clue": "Uluslararas\u0131 karayolu",
"answer": "TEM",
"position": 8,
"orientation": "across",
"startx": 5,
"starty": 4
},
{
"clue": "Cilt bak\u0131m losyonu",
"answer": "TON\u0130K",
"position": 9,
"orientation": "across",
"startx": 2,
"starty": 5
},
{
"clue": "Yap\u0131",
"answer": "B\u0130NA",
"position": 10,
"orientation": "across",
"startx": 1,
"starty": 6
},
{
"clue": "Masif, i\u00e7i dolu olan",
"answer": "SOM",
"position": 11,
"orientation": "across",
"startx": 6,
"starty": 6
},
{
"clue": "\u00c7ekicilik",
"answer": "CAZ\u0130BE",
"position": 12,
"orientation": "across",
"startx": 3,
"starty": 7
},
{
"clue": "Torbal\u0131 bal\u0131k a\u011f\u0131",
"answer": "TRATA",
"position": 13,
"orientation": "across",
"startx": 1,
"starty": 8
},
{
"clue": "En k\u0131sa zaman",
"answer": "AN",
"position": 14,
"orientation": "across",
"startx": 7,
"starty": 8
},
{
"clue": "Fazladan",
"answer": "CABA",
"position": 1,
"orientation": "down",
"startx": 1,
"starty": 1
},
{
"clue": "H<NAME>i",
"answer": "\u0130P\u0130LT\u0130",
"position": 16,
"orientation": "down",
"startx": 2,
"starty": 1
},
{
"clue": "<NAME>",
"answer": "MN",
"position": 17,
"orientation": "down",
"startx": 3,
"starty": 1
},
{
"clue": "Oy",
"answer": "REY",
"position": 18,
"orientation": "down",
"startx": 4,
"starty": 1
},
{
"clue": "Bayrak",
"answer": "ALEM",
"position": 2,
"orientation": "down",
"startx": 7,
"starty": 1
},
{
"clue": "Bo\u015f, de\u011fersiz",
"answer": "H\u0130\u00c7",
"position": 20,
"orientation": "down",
"startx": 8,
"starty": 1
},
{
"clue": "<NAME>",
"answer": "ALEKS\u0130",
"position": 4,
"orientation": "down",
"startx": 6,
"starty": 2
},
{
"clue": "Hitit",
"answer": "ET\u0130",
"position": 22,
"orientation": "down",
"startx": 5,
"starty": 3
},
{
"clue": "Tam a\u00e7\u0131lmam\u0131\u015f \u00e7i\u00e7ek",
"answer": "GONCA",
"position": 23,
"orientation": "down",
"startx": 3,
"starty": 4
},
{
"clue": "Niteliklerini \u00f6vme",
"answer": "NAAT",
"position": 24,
"orientation": "down",
"startx": 4,
"starty": 5
},
{
"clue": "Ba\u011f \u00e7ubu\u011fu \u00e7ukuru",
"answer": "EMEN",
"position": 25,
"orientation": "down",
"startx": 8,
"starty": 5
},
{
"clue": "Y\u00fcz, \u00e7ehre, beniz",
"answer": "BET",
"position": 10,
"orientation": "down",
"startx": 1,
"starty": 6
},
{
"clue": "B\u00f6lmeli g\u00f6\u00e7ebe \u00e7ad\u0131r\u0131",
"answer": "OBA",
"position": 27,
"orientation": "down",
"startx": 7,
"starty": 6
},
{
"clue": "G\u00fcney <NAME>\u0131",
"answer": "ZA",
"position": 28,
"orientation": "down",
"startx": 5,
"starty": 7
}
]
export default data;
<file_sep>/src/puzzleArea.jsx
import React, { Component } from 'react'
import { Container, Row, Col, CardColumns } from 'reactstrap'
import data from "./data/word"
import MatrisConvert from './matrisConvert';
class PuzzleArea extends Component {
constructor(props) {
super(props);
this.state = {
clueMatris: []
}
}
componentDidMount() {
this.setState({ clueMatris: MatrisConvert.result(data) })
}
render() {
return <Container>
{
this.state.clueMatris.map(item => {
return <Row>
{
item.map(element => <Square letter={element.letter} clueX={element.clueX} clueY={element.clueY}></Square>)
}
</Row>
})
}
</Container>
}
}
class Square extends Component {
constructor(props) {
super(props);
this.state = {
black: ""
};
}
componentDidMount() {
// isBlack(this.props.letter)
}
isBlack = (letter) => letter === 0 ? "bg-dark" : "bg-white"
render() {
return <Col className="embed-responsive embed-responsive-1by1 text-center">
<div className={"embed-responsive-item cell " + this.isBlack(this.props.letter)}>
{this.props.letter}
</div>
</Col>
}
}
export default PuzzleArea;
<file_sep>/README.md
# CrossWord App
## Example
https://www.haberturk.com/bulmaca/gunluk/2020/11/20
https://jaredreisinger.github.io/react-crossword/
https://github.com/JaredReisinger/react-crossword/blob/master/src/Cell.js
https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index-javascript | 9efd2599429c199ee924d12b60b91f0fd965cb3b | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | MDP-Internship/crossword | 850e6346e412eb06d7aa446d8ef8b56d4828c042 | 6766606a13d9e4b3d7cf4d117d54ca945fc0070c |
refs/heads/master | <file_sep>{"ogrenciler":[
{
"ogrenciNo":1,
"grenciAdi":"davut",
"ogrenciSoyad":"öner",
"bolumAdi":"böte",
"okulAdi":"çukurova",
"ogrenciSinif":2,
"ogrenciResim":""
},
{
"ogrenciNo":2,
"grenciAdi":"davut",
"ogrenciSoyad":"öner",
"bolumAdi":"böte",
"okulAdi":"çukurova",
"ogrenciSinif":3,
"ogrenciResim":""
},
{
"ogrenciNo":3,
"grenciAdi":"belgin",
"ogrenciSoyad":"öner",
"bolumAdi":"böte",
"okulAdi":"çukurova",
"ogrenciSinif":2,
"ogrenciResim":""
}
]}
| bfcff940ed5116c516d7bb2f0987b2cb9670c6a3 | [
"JavaScript"
] | 1 | JavaScript | Vezir2701/test3 | cc94349992bea83d606a73e47f90ff6f41640a48 | 80f615486e7ccc392c33de96012766e763ff6145 |
refs/heads/master | <file_sep>
<?php
require_once "conexion.php";
/*
Pasos para conectarme a MySQL con PHP
1)Objeto de conexión : $MYSQL = conexionMySQL();
2)Consulta SQL: $SQL = "SELECT * FROM venta ORDER BY folio_venta DESC";
3)Ejecutar la consulta: $resultado = $mysql->query($sql)
4) Mostrar los resultados: $fila = $resultado->fetch_assoc()
*/
function editarArticulo($id){
$mysql = conexionMySQL();
$sql = "SELECT * FROM articulo WHERE clave_articulo=$id";
if($resultado = $mysql->query($sql)){
$fila = $resultado->fetch_assoc();
$form = "<form id='editar-articulo' class='formulario' data-editar>";
$form .= "<fieldset>";
$form .= "<legend>Edición de Artículos</legend>";
$form .="<div id='folio'name='folios'>Folio: 000".$fila["clave_articulo"]."</div>";
$form .= "<input type='hidden' id='clave' name='clave' name='' value='".$fila["clave_articulo"]."'/>";
$form .= "<div>";
$form .= "<label for='descripcion'>Descripción</label>";
$form .= "<textarea type='text' id='descripcion' name='descripcion' placeholder='Descripción' required >".$fila["descripcion_articulo"]."</textarea>";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='precio'>Precio</label>";
$form .= "<input type='text' id='precio-articulos' name='precio' placeholder='Precio' value='".$fila["precio"]."' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='modelo'>Modelo</label>";
$form .= "<input type='text' id='modelo' name='modelo' placeholder='Modelo' value='".$fila["modelo"]."' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<br>";
$form .= "<hr>";
$form .= "<input type='submit' id='actualizar-btn' name='insertar_btn' value='actualizar'/>";
$form .= "<input type='hidden' id='transaccion' name='transaccion' value='actualizararticulo'/>";
$form .= "<input type='hidden' id='clave_articulo' name='clave_articulo' value='".$fila["clave_articulo"]."'/>";
$form .= "</fieldset>";
$form .= "</form>";
$resultado->free();
}else{
$form = "<div class='error'>Error: No se ejecutó la consulta a la Base de Datos</div>";
}
$mysql->close();
return printf($form);
}
function editarCliente($id){
$mysql = conexionMySQL();
$sql = "SELECT * FROM clientes WHERE clave_cliente=$id";
if($resultado = $mysql->query($sql)){
$fila = $resultado->fetch_assoc();
$form = "<form id='editar-cliente' class='formulario' data-editar>";
$form .= "<fieldset>";
$form .= "<legend>Edición de Clientes</legend>";
$form .="<div id='folio'name='folios'>Folio: 000".$fila["clave_cliente"]."</div>";
$form .= "<input type='hidden' id='clave' name='clave' value='".$fila["clave_cliente"]."'/>";
$form .= "<div>";
$form .= "<label for='nombre'>Nombre</label>";
$form .= "<input type='text' id='nombre' name='nombre' placeholder='Nombre(s)' value='".$fila["nombre"]."' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='apaterno'>Apellido Paterno</label>";
$form .= "<input type='text' id='apaterno' name='apaterno' placeholder='<NAME>' value='".$fila["apaterno"]."' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='amaterno'>Apellido Materno</label>";
$form .= "<input type='text' id='amaterno' name='amaterno' placeholder='<NAME>' value='".$fila["amaterno"]."' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='rfc'>RFC</label>";
$form .= "<input type='text' id='rfc' name='rfc' placeholder='RFC' value='".$fila["rfc"]."' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<hr>";
$form .= "<input type='submit' id='insertar-btn' name='insertar_btn' value='Actualizar'/>";
$form .= "<input type='hidden' id='transaccion' name='transaccion' value='actualizarcliente'/>";
$form .= "<input type='hidden' id='clave_cliente' name='clave-cliente' value='".$fila["clave_cliente"]."'/>";
$form .= "</fieldset>";
$form .= "</form>";
$resultado->free();
}else{
$form = "<div class='error'>Error: No se ejecutó la consulta a la Base de Datos</div>";
}
$mysql->close();
return printf($form);
}
function altaVenta(){
$mysql = conexionMySQL();
$sql = "SELECT * FROM venta";
$sql2 = "SELECT * FROM articulo";
$resultadoArticulo = $mysql->query($sql2);
$folioventa = $mysql->query($sql);
$resultfolio = $folioventa->fetch_assoc();
$tamaño = 0;
if($folioventa = $mysql->query($sql)){
while($fila = $folioventa->fetch_assoc()){
$tamaño++;
}
}
$folioAMostrar = ($resultfolio["folio_venta"]+$tamaño);
$claveAMostrar = ($resultfolio["clave_cliente"]+$tamaño);
$form = "<form id='alta-venta' class='formulario' data-insertar>";
$form .= "<fieldset>";
$form .= "<legend>Registro de Ventas</legend>";
$form .="<div id='folio'name='folios'>Folio: 000".$folioAMostrar."</div>";
$form .= "<input type='hidden' id='folio' name='folio' value='".$folioAMostrar."'/>";
$form .= "<input type='hidden' id='clave' name='clave' value='".$claveAMostrar."'/>";
$form .= "<div>";
$form .= "<label for='cliente'>Cliente</label>";
$form .= listaClientes();
$form .= "</div>";
$form .= "<hr>";
$precio = "";
$form .= "<input type='hidden' id='fecha' name='fecha' value='2016-08-17'/>";
$form .= "<div>";
$form .= "<label for='articulo'>Artículo</label>";
if($fila = $resultadoArticulo->fetch_assoc()){
$form .= "<select id='articuloz' name='articulo_txt' required>";
$precioU= $fila["precio"];
$form .= "<option value='".$fila["descripcion_articulo"]."' >".$fila["descripcion_articulo"]."</option>";
while ($fila = $resultadoArticulo->fetch_assoc()) {
$form .= "<option value='".$fila["descripcion_articulo"]."'>".$fila["descripcion_articulo"]."</option>";
}
$form .= "</select>";
$form .= "</div>";
$form .= "<div>";
$form .= "<br>";
$enganche = .20;
$tasa = 2.8;
$plazo = 12;
$precio = $precioU * (1+($tasa*$plazo)/100);
$importe = $precio*1;
$form .= "<div>";
$form .= "<label for='articulo'>Precio</label>";
$form .= "<input type='text' id='preci' name='total' value='".$precio."'/>";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='articulo'>Importe</label>";
$form .= "<input type='text' id='preci' name='total' value='".$importe."'/>";
$form .= "</div>";
$form .= "<br>";
$enganchetotal = $enganche*$importe;
$form .= "<div>";
$form .= "<label for='articulo'>Enganche</label>";
$form .= "<input type='text' id='preci' name='total' value='".$enganchetotal."'/>";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$bonificacion = $enganchetotal * (($tasa*$plazo)/100);
$form .= "<label for='articulo'>Bonificación Enganche</label>";
$form .= "<input type='text' id='preci' name='total' value='".$bonificacion."'/>";
$form .= "</div>";
$form .= "<br>";
$form .= "<label for='articulo'>Plazo</label>";
$form .= "<input type='text' id='plazo' name='total' value='".$plazo." meses'/>";
$form .= "</div>";
$form .= "<br>";
$total = $importe - $enganchetotal - $bonificacion;
$form .= "<div>";
$form .= "<label for='articulo'>Total</label>";
$form .= "<input type='text' id='precio' name='total' value='".$total."'/>";
$form .= "<input type='hidden' id='total' name='total' value='".$total."'/>";
$form .= "</div>";
}
$form .= "<hr>";
$form .= "<input type='submit' id='insertar-btn' name='insertar_btn' value='Guardar'/>";
$form .= "<input type='hidden' id='transaccion' name='transaccion' value='insertarventa'/>";
$form .= "</fieldset>";
$form .= "</form>";
return printf($form);
}
function altaCliente(){
$mysql = conexionMySQL();
$sql = "SELECT * FROM clientes";
$foliocliente = $mysql->query($sql);
$resultfolioCliente = $foliocliente->fetch_assoc();
$tamañoCliente = 0;
if($foliocliente = $mysql->query($sql)){
while($fila = $foliocliente->fetch_assoc()){
$tamañoCliente++;
}
}
$claveAMostrar = ($resultfolioCliente["clave_cliente"]+$tamañoCliente);
$form = "<form id='alta-cliente' class='formulario' data-insertar>";
$form .= "<fieldset>";
$form .= "<legend>Registro de Clientes</legend>";
$form .="<div id='folio'name='folios'>Folio: 000".$claveAMostrar."</div>";
$form .= "<input type='hidden' id='clave' name='clave' value='".$claveAMostrar."'/>";
$form .= "<div>";
$form .= "<label for='nombre'>Nombre</label>";
$form .= "<input type='text' id='nombre' name='nombre' placeholder='Nombre(s)' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='apaterno'>Apellido Paterno</label>";
$form .= "<input type='text' id='apaterno' name='apaterno' placeholder='Apellido Paterno' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='amaterno'>Apellido Materno</label>";
$form .= "<input type='text' id='amaterno' name='amaterno' placeholder='<NAME>' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='rfc'>RFC</label>";
$form .= "<input type='text' id='rfc' name='rfc' placeholder='RFC' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<hr>";
$form .= "<input type='submit' id='insertar-btn' name='insertar_btn' value='Guardar'/>";
$form .= "<input type='hidden' id='transaccion' name='transaccion' value='insertarcliente'/>";
$form .= "</fieldset>";
$form .= "</form>";
return printf($form);
}
function altaArticulo(){
$mysql = conexionMySQL();
$sql = "SELECT * FROM articulo";
$folioarticulo = $mysql->query($sql);
$resultfolioCliente = $folioarticulo->fetch_assoc();
$tamañoArticulo = 0;
if($folioarticulo = $mysql->query($sql)){
while($fila = $folioarticulo->fetch_assoc()){
$tamañoArticulo++;
}
}
$claveAMostrar = ($resultfolioCliente["clave_articulo"]+$tamañoArticulo);
$form = "<form id='alta-articulo' class='formulario' data-insertar>";
$form .= "<fieldset>";
$form .= "<legend>Registro de Artículos</legend>";
$form .="<div id='folio'name='folios'>Folio: 000".$claveAMostrar."</div>";
$form .= "<input type='hidden' id='clave' name='clave' value='".$claveAMostrar."'/>";
$form .= "<div>";
$form .= "<label for='descripcion'>Descripción</label>";
$form .= "<input type='text' id='descripcion' name='descripcion' placeholder='Descripción' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='precio-'>Precio</label>";
$form .= "<input type='text' id='precio-articulos' name='precio' placeholder='Precio' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='modelo'>Modelo</label>";
$form .= "<input type='text' id='modelo' name='modelo' placeholder='Modelo' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<div>";
$form .= "<label for='existencia'>Existencia</label>";
$form .= "<input type='text' id='existencia' name='existencia' placeholder='Existencia' required />";
$form .= "</div>";
$form .= "<br>";
$form .= "<hr>";
$form .= "<input type='submit' id='insertar-btn' name='insertar_btn' value='Guardar'/>";
$form .= "<input type='hidden' id='transaccion' name='transaccion' value='insertararticulo'/>";
$form .= "</fieldset>";
$form .= "<script src='js/funcionesArticulo'></script>";
$form .= "</form>";
return printf($form);
}
function listaClientes(){
$mysql = conexionMySQL();
$sql = "SELECT * FROM clientes";
$resultado = $mysql->query($sql);
$lista = "<select id='cliente' name='cliente_txt' required>";
$lista .= "<option value=''>- - - - -</option>";
while ($fila = $resultado->fetch_assoc()) {
$lista .= "<option value='".($fila["nombre"]." ".$fila["apaterno"]." ".$fila["amaterno"])."'>".($fila["nombre"]." ".$fila["apaterno"]." ".$fila["amaterno"])."</option>";
}
$lista .= "</select>";
$resultado->free();
$mysql->close();
return $lista;
}
function listaArticulos(){
$mysql = conexionMySQL();
$sql = "SELECT * FROM articulo";
$resultado = $mysql->query($sql);
$lista = "<select id='articulo' name='articulo_txt' required>";
$lista .= "<option value=''>- - - - -</option>";
while ($fila = $resultado->fetch_assoc()) {
$lista .= "<option value='".$fila["descripcion_articulo"]."'>".$fila["descripcion_articulo"]."</option>";
}
$lista .= "</select>";
$resultado->free();
$mysql->close();
return $lista;
}
function mostrarVentas(){
$mysql = conexionMySQL();
$sql = "SELECT * FROM venta ORDER BY folio_venta DESC";
if ($resultado = $mysql->query($sql)) {
//echo "wiiii";
$tabla = "<table id='tabla-ventas' class='tabla'>";
$tabla .= "<caption>Ventas Activas</caption>";
$tabla .= "<thead>";
$tabla .= "<tr>";
$tabla .= "<th><strong>Folio Venta</strong></th>";
$tabla .= "<th><strong>Clave Cliente</strong></th>";
$tabla .= "<th><strong>Nombre</strong></th>";
$tabla .= "<th><strong>Total</strong></th>";
$tabla .= "<th><strong>Fecha</strong></th>";
$tabla .= "<th></th>";
$tabla .= "</tr>";
$tabla .= "</thead>";
$tabla .= "<tbody>";
while($fila = $resultado->fetch_assoc()){
$tabla .="<tr>";
$tabla .="<td>000".$fila["folio_venta"]."</td>";
$tabla .="<td>000".$fila["clave_cliente"]."</td>";
$tabla .="<td>".$fila["nombre"]."</td>";
$tabla .="<td>".$fila["total"]."</td>";
$tabla .="<td>".$fila["fecha"]."</td>";
$tabla .="<td><a href='#' class='eliminar' data-id='".$fila["folio_venta"]."'><img src='imagenes/eliminar.PNG' class='eliminars' data-id='".$fila["folio_venta"]."'/></a></td>";
$tabla .="</tr>";
}
$resultado->free();
$tabla .= "</tbody>";
$tabla .= "</table>";
$tabla .= "<div id='werty'>";
$tabla .= "</div>";
printf($tabla);
}else{
//echo "noooo";
$mysql->close();
$respuesta = "<div class='error'>Error: No se ejecutó la consulta a la Base de Datos</div>";
printf($respuesta);
}
}
function mostrarClientes(){
$mysql = conexionMySQL();
$sql = "SELECT * FROM clientes ORDER BY clave_cliente DESC";
if ($resultado = $mysql->query($sql)) {
$tabla = "<table id='tabla-clientes' class='tabla'>";
$tabla .= "<caption>Clientes Registrados</caption>";
$tabla .= "<thead>";
$tabla .= "<tr>";
$tabla .= "<th><strong>Clave Cliente</strong></th>";
$tabla .= "<th><strong>Nombre</strong></th>";
$tabla .= "<th></th>";
$tabla .= "</tr>";
$tabla .= "</thead>";
$tabla .= "<tbody>";
while($fila = $resultado->fetch_assoc()){
$tabla .="<tr>";
$tabla .="<td>000".$fila["clave_cliente"]."</td>";
$tabla .="<td>".$fila["nombre"]." ".$fila["apaterno"]." ".$fila["amaterno"]."</td>";
$tabla .="<td><a href='#' class='editar' data-id='".$fila["clave_cliente"]."'>
<img src='imagenes/editar.PNG' class='editars' data-id='".$fila["clave_cliente"]."'/>
</a></td>";
$tabla .="<td>
<a href='#' class='eliminar' data-id='".$fila["clave_cliente"]."'>
<img src='imagenes/eliminar.PNG' class='eliminars' data-id='".$fila["clave_cliente"]."'/>
</a>
</td>";
$tabla .="</tr>";
}
$resultado->free();
$tabla .= "</tbody>";
$tabla .= "</table>";
printf($tabla);
}else{
$mysql->close();
$respuesta = "<div class='error'>Error: No se ejecutó la consulta a la Base de Datos</div>";
printf($respuesta);
}
}
function mostrarArticulos(){
$mysql = conexionMySQL();
$sql = "SELECT * FROM articulo ORDER BY clave_articulo DESC";
if ($resultado = $mysql->query($sql)) {
$tabla = "<table id='tabla-articulos' class='tabla'>";
$tabla .= "<caption>Artículos Registrados</caption>";
$tabla .= "<thead>";
$tabla .= "<tr>";
$tabla .= "<th><strong>Clave Artículo</strong></th>";
$tabla .= "<th><strong>Descripción</strong></th>";
$tabla .= "<th></th>";
$tabla .= "</tr>";
$tabla .= "</thead>";
$tabla .= "<tbody>";
while($fila = $resultado->fetch_assoc()){
$tabla .="<tr>";
$tabla .="<td>000".$fila["clave_articulo"]."</td>";
$tabla .="<td>".$fila["descripcion_articulo"]."</td>";
$tabla .="<td><a href='#' class='editar' data-id='".$fila["clave_articulo"]."'><img src='imagenes/editar.PNG' class='editars' data-id='".$fila["clave_articulo"]."'/></a></td>";
$tabla .="<td><a href='#' class='eliminar' data-id='".$fila["clave_articulo"]."'><img src='imagenes/eliminar.PNG' class='eliminars' data-id='".$fila["clave_articulo"]."'/></a></td>";
$tabla .="</tr>";
}
$resultado->free();
$tabla .= "</tbody>";
$tabla .= "</table>";
printf($tabla);
}else{
$mysql->close();
$respuesta = "<div class='error'>Error: No se ejecutó la consulta a la Base de Datos</div>";
printf($respuesta);
}
}
$tasaU = 0;
$engancheU = 0;
$plazoU = 0;
function configuracion(){
$forma = "<form id='configuracion-form' data-insertar>";
$forma .= "<div>";
$forma .= "<label for='tasa'>Tasa de financiamiento:</label>";
$forma .= "<input type='text' id='tasa' required>";
$forma .= "</div>";
$forma .= "<br>";
$forma .= "<div>";
$forma .= "<label for='enganche'> Enganche</label>";
$forma .= "<input type='text' id='enganche' required>";
$forma .= "</div>";
$forma .= "<br>";
$forma .= "<div>";
$forma .= "<label for='plazo'>Plazo Máximo</label>";
$forma .= "<input type='text' id='plazo' required>";
$forma .= "</div>";
$forma .= "<br>";
$forma .= "<input type='submit' id='btn-config' name='btn-config' value='Guardar'/>";
$forma .= "<input type='hidden' id='transaccion' name='transaccion' value='insertarconfiguracion'/>";
$forma .= "<br>";
$forma .= "</form>";
printf($forma);
}
function actualizarConfiguracion($tasa,$enganche,$plazo){
$tasaU=$tasa;
$engancheU=$enganche;
$plazoU=$plazo;
}
?>
<file_sep>//constante
//4 = peticion completa
var READY_STATE_COMPLETE = 4;
var OK = 200;
//variables
var fech = new Date();
var respuestafecha = document.getElementById("fecha-respuesta");
//Es null para dar soporte a los distintos navegadores
var ajax = null;
var btnsEliminar = document.querySelectorAll(".eliminar");
var btonInsertar = document.querySelector("#imagen-ventas");
var precarga = document.querySelector("#precarga");
var respuesta = document.querySelector("#respuesta");
//funciones
function objetoAJAX(){
if(window.XMLHttpRequest){
//soporte para chrome
return new XMLHttpRequest();
}else if(window.activeXObject){
//soporte para internet explorer
return new activeXObject("Microsoft.XMLHTTP");
}
}
function ejecutarAJAX(datosVenta){
ajax = objetoAJAX();
//Cuando un cambio de estado esté listo se ejecutará
ajax.onreadystatechange = enviarDatos;
//request abre el archivo controlador.php por el metodo POST
ajax.open("POST","controlador.php");
//mime http://eswikipedia.org/wiki/Multipurpose_Internet_Mail_Extensions#MIME-Version
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(datosVenta);
}
function altaVenta(evento){
evento.preventDefault();
//alert("funciona");
//Toda operacion que interactua con la BD es transaccion
var datosVenta = "transaccion=altaventa";
ejecutarAJAX(datosVenta);
}
function enviarDatos(){
precarga.style.display = "block";
precarga.innerHTML = "<img src='imagenes/loader.gif' />";
//codigo HTTP de estado de carga listo
if (ajax.readyState == READY_STATE_COMPLETE) {
//peticion 200=ok
if(ajax.status == OK){
//alert(ajax.responseText);
precarga.innerHTML = null;
precarga.style.display = "none";
respuesta.style.display = "block";
respuesta.innerHTML = ajax.responseText;
//evaluar que la cadena de texto encuentre el dato mientras sea mayor a -1
if(ajax.responseText.indexOf("data-insertar")>-1){
document.querySelector("#alta-venta").addEventListener("submit",insertarVenta);
//alert("Venta registrada con exito!");
}
if(ajax.responseText.indexOf("data-recarga")>-1){
setTimeout(window.location.reload(),6000);
}
}else{
alert("El servidor no contestó\nError: "+ajax.status+": "+ajax.statusText);
}
}
}
//Funcionará para las 4 operaciones CRUD
function insertarVenta(evento){
//alert("procesa formulario");
evento.preventDefault();
//var datos = "transaccion=insertar";
//ejecutarAJAX(datos);
var nombre = new Array();
var valor = new Array();
var hijosForm = evento.target;
var datosVenta = "";
for(var i = 1; i<hijosForm.length;i++){
nombre[i] = hijosForm[i].name;
valor[i] = hijosForm[i].value;
datosVenta += nombre[i]+"="+valor[i]+"&";
//console.log(datos);
}
ejecutarAJAX(datosVenta);
}
//Función que ejecutará AJAX
function fecha(){
var dia = (fech.getDate()<=9)?"0"+fech.getDate():""+fech.getDate();
var mes = (fech.getMonth()<=9)?"0"+(fech.getMonth()+1):""+(fech.getMonth()+1);
respuestafecha.innerHTML= "Fecha: "+dia+"/"+mes+"/"+fech.getFullYear();
}
function eliminarVenta(evento){
evento.preventDefault();
//alert(evento.target.dataset.precio);
//los elementosdata del backend se guardan endataset
//alert(evento.target.dataset.id);
var idVenta = evento.target.dataset.id;
//var precio = evento.target.dataset.precio;
var eliminar = confirm("¿Seguro que deseas eliminar la venta No. "+idVenta+" ?");
if(eliminar){
var datos = "folio_venta="+idVenta+"&transaccion=eliminarventa";
ejecutarAJAX(datos);
}
}
function cargaDocumento(){
btonInsertar.addEventListener("click",altaVenta);
for (var i = 0;i<btnsEliminar.length; i++) {
btnsEliminar[i].addEventListener("click",eliminarVenta);
}
}
//asignacion de eventos
window.addEventListener("load",fecha);
window.addEventListener("load",cargaDocumento);
<file_sep>var form = document.getElementById("configuracion-form");
var r = document.getElementById("valores");
var plazo = document.getElementById("plazo");
var fech = new Date();
var respuestafecha = document.getElementById("fecha-respuesta");
function objetoAJAX(){
if(window.XMLHttpRequest){
//soporte para chrome
return new XMLHttpRequest();
}else if(window.activeXObject){
//soporte para internet explorer
return new activeXObject("Microsoft.XMLHTTP");
}
}
function ejecutarAJAX(datosVenta){
ajax = objetoAJAX();
//Cuando un cambio de estado esté listo se ejecutará
ajax.onreadystatechange = enviarDatos;
//request abre el archivo controlador.php por el metodo POST
ajax.open("POST","controlador.php");
//mime http://eswikipedia.org/wiki/Multipurpose_Internet_Mail_Extensions#MIME-Version
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(datosVenta);
}
function enviarDatos(){
//codigo HTTP de estado de carga listo
if (ajax.readyState == READY_STATE_COMPLETE) {
//peticion 200=ok
if(ajax.status == OK){
//alert(ajax.responseText);
//evaluar que la cadena de texto encuentre el dato mientras sea mayor a -1
if(ajax.responseText.indexOf("data-insertar")>-1){
document.querySelector("#configuracion-form").addEventListener("submit",insertarConf);
//alert("Venta registrada con exito!");
}
}else{
alert("El servidor no contestó\nError: "+ajax.status+": "+ajax.statusText);
}
}
}
function insertarConf(evento){
//alert("procesa formulario");
evento.preventDefault();
//var datos = "transaccion=insertar";
//ejecutarAJAX(datos);
var nombre = new Array();
var valor = new Array();
var hijosForm = evento.target;
var datos = "";
for(var i = 1; i<hijosForm.length;i++){
nombre[i] = hijosForm[i].name;
valor[i] = hijosForm[i].value;
datos += nombre[i]+"="+valor[i]+"&";
console.log(datos);
}
ejecutarAJAX(datos);
}
function altaConf(evento){
evento.preventDefault();
//alert("funciona");
//Toda operacion que interactua con la BD es transaccion
var datosVenta = "transaccion=insertarconfiguracion";
ejecutarAJAX(datos);
}
function eshio(){
r.innerHTML = "Plazo: "+plazo.value;
}
function fecha(){
var dia = (fech.getDate()<=9)?"0"+fech.getDate():""+fech.getDate();
var mes = (fech.getMonth()<=9)?"0"+(fech.getMonth()+1):""+(fech.getMonth()+1);
respuestafecha.innerHTML= "Fecha: "+dia+"/"+mes+"/"+fech.getFullYear();
}
form.addEventListener("submit",eshio);
window.addEventListener("load",fecha);
<file_sep><?php
require "vistas.php";
require "modelo.php";
/*
Aplicacion CreateReadUpdateDelete
PHP TIENE 2 METODOS DE ENVIO DE DATOS: GET Y POST
C AFECTA BD INSERT(SQL) POST Modelo
R NO AFECTA BD SELECT(SQL) GET Vista
U AFECTA BD UPDATE(SQL) POST Modelo
D AFECTA BD DELETE(SQL) POST Modelo
*/
//METODOS DE ENVIO DE FORMULARIOS GET Y POST
$transaccion = $_POST["transaccion"];
//echo $transaccion;
function ejecutarTransaccion($transaccion){
if($transaccion=="altaventa"){
//mostrar formulario alta
altaVenta();
}else if($transaccion=="altacliente"){
//mostrar formulario alta
altaCliente();
}else if($transaccion=="altaarticulo"){
//mostrar formulario alta
altaArticulo();
}else if($transaccion=="insertarventa"){
//procesar los datos del formulario de alta e insertarlos en mysql
//echo "gogog";
insertarVenta($_POST["folio"],$_POST["clave"],$_POST["cliente_txt"],$_POST["total"],$_POST["fecha"]);
}else if($transaccion=="insertarcliente"){
//procesar los datos del formulario de alta e insertarlos en mysql
//echo "gogog";
insertarCliente($_POST["clave"],$_POST["nombre"],$_POST["apaterno"],$_POST["amaterno"],$_POST["rfc"]);
}else if($transaccion=="insertararticulo"){
//procesar los datos del formulario de alta e insertarlos en mysql
//echo "gogog";
insertarArticulo($_POST["clave"],$_POST["descripcion"],$_POST["precio"],$_POST["modelo"]);
}else if($transaccion=="eliminarventa"){
//eliminar de mysql el registro solicitado
eliminarVenta($_POST["folio_venta"]);
}else if($transaccion=="eliminarcliente"){
//eliminar de mysql el registro solicitado
eliminarCliente($_POST["clave_cliente"]);
}else if($transaccion=="eliminararticulo"){
//eliminar de mysql el registro solicitado
eliminarArticulo($_POST["clave_articulo"]);
}else if ($transaccion=="editararticulo") {
//traer los datos del registro a modificar en un formulario
editarArticulo($_POST["clave_articulo"]);
}else if ($transaccion=="editarcliente") {
//traer los datos del registro a modificar en un formulario
editarCliente($_POST["clave_cliente"]);
}else if ($transaccion=="actualizarcliente") {
//modificar en mysql los datos del registro modificado
ActualizarCliente($_POST["clave"],$_POST["nombre"],$_POST["apaterno"],$_POST["amaterno"],$_POST["rfc"]);
}else if ($transaccion=="actualizararticulo") {
//modificar en mysql los datos del registro modificado
ActualizarArticulo($_POST["clave"],$_POST["descripcion"],$_POST["precio"],$_POST["modelo"]);
}else if($transaccion=="insertarconfiguracion"){
actualizarConfiguracion($_POST["tasa"],$_POST["enganche"],$_POST["plazo"]);
}
}
ejecutarTransaccion($transaccion);
?><file_sep><?php require "vistas.php"; ?>
<!DOCTYPE html>
<html lang="es-MX">
<head>
<meta charset="UTF-8">
<title>Artículos</title>
<meta name="description" content="Aplicación web para la venta de articulos vendimia">
<link rel="stylesheet" href="css/estilos.css">
</head>
<body>
<div id="contenedor">
<div class="dropdown">
<button class="dropbtn">Inicio</button>
<div class="dropdown-contenido">
<a href="ventas.php">Ventas</a>
<a href="clientes.php">Clientes</a>
<a href="articulos.php">Articulos</a>
<a href="configuracion.php">Configuración</a>
</div>
</div>
<div id="fecha-respuesta"></div>
</div>
<section id="contenedor-principal">
<div id="blanco">
</div>
<div id="contenido">
<div id="respuesta-articulo"></div>
<div id="precarga-articulo"></div>
<a href="#"><img id="imagen-articulos" src="imagenes/newarticulo.PNG"></a>
<br>
<br>
<?php mostrarArticulos()?>
</div>
</section>
<div id="respuesta"></div>
<div id="precarga"></div>
<script src="js/funcionesArticulo.js"></script>
</body>
</html>
<file_sep># miVendimia
Mini sistema para alta, consulta y baja de productos, clientes y artículos
<file_sep><?php require "vistas.php"; ?>
<!DOCTYPE html>
<html lang="es-MX">
<head>
<meta charset="UTF-8">
<title>Configuración</title>
<meta name="description" content="Aplicación web para la venta de articulos vendimia">
<link rel="stylesheet" href="css/estilos.css">
</head>
<body>
<div id="contenedor">
<div class="dropdown">
<button class="dropbtn">Inicio</button>
<div></div>
<div class="dropdown-contenido">
<a href="ventas.php">Ventas</a>
<a href="clientes.php">Clientes</a>
<a href="articulos.php">Articulos</a>
<a href="configuracion.php">Configuración</a>
</div>
</div>
<div id="fecha-respuesta"></div>
</div>
<section id="contenedor-principal">
<div id="blanco"></div>
<div id="contenido">
<div id="titulo-contenido">Configuración General</div>
<br>
<br>
<?php configuracion() ?>
</div>
<br>
<br>
<div id="valores"></div>
<script src="js/funcionesConf.js"></script>
</section>
</body>
</html><file_sep><?php
require_once "conexion.php";
function insertarVenta($folio,$clave,$nombre,$total,$fecha){
$mysql = conexionMySQL();
$sql = "INSERT INTO venta(folio_venta,clave_cliente,nombre,total,fecha) VALUES ('$folio','$clave','$nombre','$total','$fecha')";
if($resultado = $mysql->query($sql)){
$respuesta = "<div class='exito' data-recarga>Se ingresó con exito la venta</div>";
}else{
$respuesta = "<div class='error' data-recarga >Ocurrió un error no se registró la venta</div>";
}
$mysql->close();
return printf($respuesta);
}
function eliminarVenta($folio_venta){
$mysql = conexionMySQL();
$sql = "DELETE FROM venta WHERE folio_venta=$folio_venta";
//ejecutar conexion y guardarla en una variable
if($resultado = $mysql->query($sql)){
$respuesta = "<div class='exito' data-recarga>Se eliminó con exito la venta</div>";
}else{
$respuesta = "<div class='error' data-recarga>Ocurrió un error no se eliminó la venta</div>";
}
$mysql->close();
return printf($respuesta);
}
function insertarCliente($clave,$nombre,$apaterno,$amaterno,$rfc){
$mysql = conexionMySQL();
$sql = "INSERT INTO clientes(clave_cliente,nombre,apaterno,amaterno,rfc) VALUES ('$clave','$nombre','$apaterno','$amaterno','$rfc')";
if($resultado = $mysql->query($sql)){
$respuesta = "<div class='exito' data-recarga>Se ingresó con exito el cliente</div>";
}else{
$respuesta = "<div class='error' data-recarga>Ocurrió un error no se registró elcliente</div>";
}
$mysql->close();
return printf($respuesta);
}
function ActualizarCliente($clave,$nombre,$apaterno,$amaterno,$rfc){
$mysql = conexionMySQL();
$sql = "UPDATE clientes SET clave_cliente='$clave',nombre='$nombre',apaterno='$apaterno',amaterno='$amaterno',rfc='$rfc' WHERE clave_cliente='$clave'";
if($resultado = $mysql->query($sql)){
$respuesta = "<div class='exito' data-recarga>Se actualizó con exito el cliente</div>";
}else{
$respuesta = "<div class='error' data-recarga>Ocurrió un error no se actualizó el cliente</div>";
}
$mysql->close();
return printf($respuesta);
}
function eliminarCliente($clave){
$mysql = conexionMySQL();
$sql = "DELETE FROM clientes WHERE clave_cliente=$clave";
//ejecutar conexion y guardarla en una variable
if($resultado = $mysql->query($sql)){
$respuesta = "<div class='exito' data-recarga>Se eliminó con exito el cliente</div>";
}else{
$respuesta = "<div class='error' data-recarga>Ocurrió un error no se eliminó el cliente</div>";
}
$mysql->close();
return printf($respuesta);
}
function insertarArticulo($clave,$descripcion,$precio,$modelo){
$mysql = conexionMySQL();
$sql = "INSERT INTO articulo(clave_articulo,descripcion_articulo,precio,modelo) VALUES ('$clave','$descripcion','$precio','$modelo')";
if($resultado = $mysql->query($sql)){
$respuesta = "<div class='exito' data-recarga>Se ingresó con exito el articulo</div>";
}else{
$respuesta = "<div class='error' data-recarga>Ocurrió un error no se registró el articulo</div>";
}
$mysql->close();
return printf($respuesta);
}
function ActualizarArticulo($clave,$descripcion,$precio,$modelo){
$mysql = conexionMySQL();
$sql = "UPDATE articulo SET descripcion_articulo='$descripcion', precio='$precio',modelo='$modelo' WHERE clave_articulo='$clave'";
if($resultado = $mysql->query($sql)){
$respuesta = "<div class='exito' data-recarga>Se actualizó con exito el articulo</div>";
}else{
$respuesta = "<div class='error' data-recarga>Ocurrió un error no se actualizó el articulo</div>";
}
$mysql->close();
return printf($respuesta);
}
function eliminarArticulo($clave_articulo){
$mysql = conexionMySQL();
$sql = "DELETE FROM articulo WHERE clave_articulo=$clave_articulo";
//ejecutar conexion y guardarla en una variable
if($resultado = $mysql->query($sql)){
$respuesta = "<div class='exito' data-recarga>Se eliminó con exito el artículo</div>";
}else{
$respuesta = "<div class='error' data-recarga>Ocurrió un error no se eliminó el artículo</div>";
}
$mysql->close();
return printf($respuesta);
}
?>
<file_sep>//constante
//4 = peticion completa
var READY_STATE_COMPLETE = 4;
var OK = 200;
//variables
var fech = new Date();
var respuestafecha = document.getElementById("fecha-respuesta");
//Es null para dar soporte a los distintos navegadores
var ajax = null;
var btnsEliminar = document.querySelectorAll(".eliminar");
var btnsEditar = document.querySelectorAll(".editar");
var btnInsertar = document.querySelector("#imagen-cliente");
var precargaCliente = document.querySelector("#precarga-cliente");
var respuestaCliente = document.querySelector("#respuesta-cliente");
//funciones
function objetoAJAX(){
if(window.XMLHttpRequest){
//soporte para chrome
return new XMLHttpRequest();
}else if(window.activeXObject){
//soporte para internet explorer
return new activeXObject("Microsoft.XMLHTTP");
}
}
function enviarDatosCliente(){
precargaCliente.style.display = "block";
precargaCliente.innerHTML = "<img src='imagenes/loader.gif' />";
//codigo HTTP de estado de carga listo
if (ajax.readyState == READY_STATE_COMPLETE) {
//peticion 200=ok
if(ajax.status == OK){
//alert(ajax.responseText);
precargaCliente.innerHTML = null;
precargaCliente.style.display = "none";
respuestaCliente.style.display = "block";
respuestaCliente.innerHTML = ajax.responseText;
//evaluar que la cadena de texto encuentre el dato mientras sea mayor a -1
if(ajax.responseText.indexOf("data-insertar")>-1){
document.querySelector("#alta-cliente").addEventListener("submit",insertarEditarCliente);
//alert("Cliente guardado con exito!");
}
if(ajax.responseText.indexOf("data-editar")>-1){
document.querySelector("#editar-cliente").addEventListener("submit",insertarEditarCliente);
//alert("Cliente guardado con exito!");
}
if(ajax.responseText.indexOf("data-recarga")>-1){
setTimeout(window.location.reload(),6000);
}
}else{
alert("El servidor no contestó\nError: "+ajax.status+": "+ajax.statusText);
}
}
}
//Funcionará para las 4 operaciones CRUD
function ejecutarAJAXCliente(datosCliente){
ajax = objetoAJAX();
//Cuando un cambio de estado esté listo se ejecutará
ajax.onreadystatechange = enviarDatosCliente;
//request abre el archivo controlador.php por el metodo POST
ajax.open("POST","controlador.php");
//mime http://eswikipedia.org/wiki/Multipurpose_Internet_Mail_Extensions#MIME-Version
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(datosCliente);
}
function insertarEditarCliente(evento){
//alert("procesa formulario");
evento.preventDefault();
//var datos = "transaccion=insertar";
//ejecutarAJAX(datos);
var nombre = new Array();
var valor = new Array();
var hijosForm = evento.target;
var datosCliente = "";
for(var i = 1; i<hijosForm.length;i++){
nombre[i] = hijosForm[i].name;
valor[i] = hijosForm[i].value;
datosCliente += nombre[i]+"="+valor[i]+"&";
//console.log(datos);
}
ejecutarAJAXCliente(datosCliente);
}
//Función que ejecutará AJAX
function altaCliente(evento){
evento.preventDefault();
//alert("funciona");
//Toda operacion que interactua con la BD es transaccion
var datosCliente = "transaccion=altacliente";
ejecutarAJAXCliente(datosCliente);
}
function fecha(){
var dia = (fech.getDate()<=9)?"0"+fech.getDate():""+fech.getDate();
var mes = (fech.getMonth()<=9)?"0"+(fech.getMonth()+1):""+(fech.getMonth()+1);
respuestafecha.innerHTML= "Fecha: "+dia+"/"+mes+"/"+fech.getFullYear();
}
function eliminarCliente(evento){
evento.preventDefault();
//los elementosdata del backend se guardan endataset
//alert(evento.target.dataset.id);
var idCliente = evento.target.dataset.id;
var eliminar = confirm("¿Seguro que deseas eliminar al cliente No. "+idCliente+" ?");
if(eliminar){
var datos = "clave_cliente="+idCliente+"&transaccion=eliminarcliente";
ejecutarAJAXCliente(datos);
}
}
function editarCliente(evento){
evento.preventDefault();
//alert(evento.target.dataset.id);
var idCliente = evento.target.dataset.id;
var datos = "clave_cliente="+idCliente+"&transaccion=editarcliente";
//solicitud al backend
ejecutarAJAXCliente(datos);
}
function cargaDocumento(){
btnInsertar.addEventListener("click",altaCliente);
for (var i = 0;i<btnsEliminar.length; i++) {
btnsEliminar[i].addEventListener("click",eliminarCliente);
}
for (var i = 0;i<btnsEditar.length; i++) {
btnsEditar[i].addEventListener("click",editarCliente);
}
}
//asignacion de eventos
window.addEventListener("load",fecha);
window.addEventListener("load",cargaDocumento);
<file_sep><?php
//servidor
define("SERVER","localhost");
//usuario
define("USER","root");
//contraseña
define("PASS", "");
//base de datos a usae
define("BD","vendimia");
?><file_sep>CREATE DATABASE vendimia;
USE vendimia;
/*Tabla de datos*/
/*motores engine, inodb*/
CREATE TABLE clientes(
clave_cliente INT NOT NULL AUTO_INCREMENT,
nombre VARCHAR(30) NOT NULL,
apaterno VARCHAR(20) NOT NULL,
amaterno VARCHAR(20) NOT NULL,
rfc VARCHAR(13) NOT NULL,
PRIMARY KEY(clave_cliente)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE articulo(
clave_articulo INT NOT NULL AUTO_INCREMENT,
descripcion_articulo TEXT NOT NULL,
precio INT NOT NULL,
modelo VARCHAR(20) NOT NULL,
PRIMARY KEY(clave_articulo)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE venta(
folio_venta INT NOT NULL AUTO_INCREMENT,
clave_cliente INT NOT NULL,
nombre VARCHAR(20) NOT NULL,
total FLOAT NOT NULL,
fecha DATE NOT NULL,
PRIMARY KEY(folio_venta)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO clientes (clave_cliente,nombre,apaterno,amaterno,rfc) VALUES
(0001,"Hector","Ceja","Gomez", "CEGH960227WEQ");
INSERT INTO venta (folio_venta,clave_cliente,nombre,total,fecha) VALUES
(0001,0001,"<NAME>",1234.2,'2016-08-11'); | 53cbb3b7bcf2dc7e4483ad99e61dd89b4e4d7926 | [
"JavaScript",
"SQL",
"Markdown",
"PHP"
] | 11 | PHP | HectorCeja/miVendimia | bca6fb7b7a7bb5599feae55cd279af1fdd18058a | 058a810ad866f213e425c040da2c0efbe34d0450 |
refs/heads/master | <file_sep>package com.dreamworks.sms.course.service;
import java.util.List;
import com.dreamworks.sms.course.dto.CourseInfoDto;
public interface CourseInfoService {
public List<CourseInfoDto> getCourseInfo();
}
<file_sep>package com.dreamworks.sms.score.dto;
import java.io.Serializable;
import java.util.Date;
import com.dreamworks.sms.classInfo.dto.ClassInfoDto;
import com.dreamworks.sms.course.dto.CourseInfoDto;
import com.dreamworks.sms.educationalStaff.dto.EducationalStaffInfoDto;
import com.dreamworks.sms.educationalStaff.dto.EducationalStaffInfoDto.EducationalStaffInfoDtoBuilder;
import com.dreamworks.sms.student.dto.StudentInfoDto;
import com.dreamworks.sms.teacher.dto.TeacherInfoDto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@SuppressWarnings("serial")
@AllArgsConstructor
@Data
@NoArgsConstructor
@Builder
@Accessors(chain = true)
public class ScoreInfoDto implements Serializable{
private Integer scoreId;
private Integer studentId;
private Integer teacherId;
private Integer classId;
private Integer scoreNum;
private Integer courseId;
private Integer rowNum;
private int examinationName;
private Integer schoolRowNum;
private StudentInfoDto studentInfoDto;
private CourseInfoDto courseInfoDto;
private TeacherInfoDto teacherInfoDto;
private ClassInfoDto classInfoDto;
}<file_sep>package com.dreamworks.sms.student.service.imp;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dreamworks.sms.classInfo.dto.ClassInfoDto;
import com.dreamworks.sms.student.dao.StudentLoginMapper;
import com.dreamworks.sms.student.dto.StudentDto;
import com.dreamworks.sms.student.dto.StudentInfoDto;
import com.dreamworks.sms.student.dto.StudentQueryDto;
import com.dreamworks.sms.student.po.StudentInfoPo;
import com.dreamworks.sms.student.po.StudentPo;
import com.dreamworks.sms.student.service.StudentLoginService;
import com.dreamworks.sms.teacher.dto.TeacherDto;
@Service
public class StudentLoginServiceImpl implements StudentLoginService{
@Autowired
private StudentLoginMapper studentLoginDao;
@Override
public StudentInfoDto findStudentByStudentId(StudentQueryDto studentQueryDto) {
// TODO Auto-generated method stub
StudentInfoPo studentInfoPo = studentLoginDao.findStudentByStudentId(studentQueryDto);
if(studentInfoPo != null) {
ModelMapper modelMapper = new ModelMapper();
StudentInfoDto sDto = modelMapper.map(studentInfoPo,StudentInfoDto.class);
ClassInfoDto classInfoDto = modelMapper.map(studentInfoPo.getClassInfoPo(), ClassInfoDto.class);
sDto.setClassInfoDto(classInfoDto);
System.out.println("执行认证逻辑"+"=========++++++++++++"+sDto);
return sDto;
} else {
return null;
}
}
}
<file_sep>package com.dreamworks.sms.classInfo.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dreamworks.sms.classInfo.dao.ClassInfoMapper;
import com.dreamworks.sms.classInfo.dto.ClassInfoDto;
import com.dreamworks.sms.classInfo.po.ClassInfoPo;
import com.dreamworks.sms.classInfo.service.ClassInfoService;
import com.dreamworks.sms.educationalStaff.dto.EducationalStaffInfoDto;
@Service
public class ClassInfoServiceImpl implements ClassInfoService{
@Autowired
private ClassInfoMapper classInfoMapper;
@Override
public List<ClassInfoDto> getClassInfo() {
// TODO Auto-generated method stub
List<ClassInfoPo> list1 = classInfoMapper.getClassInfo();
ModelMapper modelMapper = new ModelMapper();
List<ClassInfoDto> list2 = new ArrayList<ClassInfoDto>();
for(ClassInfoPo classInfoPo : list1) {
ClassInfoDto classInfoDto = modelMapper.map(classInfoPo,ClassInfoDto.class);
list2.add(classInfoDto);
}
return list2;
}
}
<file_sep>package com.dreamworks.sms.resouce;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.dreamworks.sms.student.dto.StudentInfoDto;
import com.dreamworks.sms.student.dto.StudentQueryDto;
import com.dreamworks.sms.teacher.dto.TeacherInfoDto;
import com.dreamworks.sms.teacher.dto.TeacherQueryDto;
import com.dreamworks.sms.teacher.service.TeacherLoginService;
public class TeacherRealm extends AuthorizingRealm{
@Autowired
private TeacherLoginService teacherLoginService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
UserToken token1 = (UserToken)token;
TeacherQueryDto teacherQueryDto = new TeacherQueryDto();
teacherQueryDto.setTeacherId(token1.getUsername());
// User user = new User();
// user.setUsername(token1.getUsername());
TeacherInfoDto t = teacherLoginService.findTeacherByTeacherId(teacherQueryDto);
if(t==null) {
return null;
}
return new SimpleAuthenticationInfo(teacherQueryDto,t.getPassword(),getName());
}
}
<file_sep>package com.dreamworks.sms.teacher.po;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import com.dreamworks.sms.classInfo.dto.ClassInfoDto;
import com.dreamworks.sms.classInfo.po.ClassInfoPo;
import com.dreamworks.sms.course.dto.CourseInfoDto;
import com.dreamworks.sms.course.po.CourseInfoPo;
import com.dreamworks.sms.teacher.dto.TeacherInfoDto;
import com.dreamworks.sms.teacher.dto.TeacherInfoDto.TeacherInfoDtoBuilder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@SuppressWarnings("serial")
@AllArgsConstructor
@Data
@NoArgsConstructor
@Builder
@Accessors(chain = true)
public class TeacherInfoPo implements Serializable{
private Integer teacherId;
private String teahcerName;
private Date birth;
private String adress;
private Integer classId;
private Short isHeadmaster;
private Integer courseId;
private String password;
private List<ClassInfoPo> list;
private CourseInfoPo courseInfoPo;
}
<file_sep>package com.dreamworks.sms.teacher.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* @ClassName: TeacherQueryDto
* @Description: TODO
* @Author: Jzxxxxx
* @Date: Created in 2019/7/12 0012下午 4:36
*/
@Data
@AllArgsConstructor
@Builder
@NoArgsConstructor
@Accessors(chain = true)
public class TeacherQueryDto implements Serializable {
private String teacherId;
private String password;
private String loginType;
private Integer classId;
private Integer courseId;
}
<file_sep>import Vue from 'vue'
import XLSX from 'xlsx';
Vue.use(XLSX);
<file_sep>package com.dreamworks.sms.educationalStaff.service.impl;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dreamworks.sms.educationalStaff.dao.EducationalStaffLoginMapper;
import com.dreamworks.sms.educationalStaff.dto.EducationalStaffInfoDto;
import com.dreamworks.sms.educationalStaff.dto.EducationalStaffQueryDto;
import com.dreamworks.sms.educationalStaff.po.EducationalStaffInfoPo;
import com.dreamworks.sms.educationalStaff.service.EducationalStaffLoginService;
import com.dreamworks.sms.student.dto.StudentInfoDto;
@Service
public class EducationalStaffLoginServiceImpl implements EducationalStaffLoginService{
@Autowired
private EducationalStaffLoginMapper educationalStaffLoginMapper;
@Override
public EducationalStaffInfoDto findStaffByEducationalStaffId(EducationalStaffQueryDto educationalStaffQueryDto) {
// TODO Auto-generated method stub
EducationalStaffInfoPo educationalStaffInfoPo = educationalStaffLoginMapper.findStaffByEducationalStaffId(educationalStaffQueryDto);
if(educationalStaffInfoPo != null) {
ModelMapper modelMapper = new ModelMapper();
EducationalStaffInfoDto educationalStaffInfoDto = modelMapper.map(educationalStaffInfoPo,EducationalStaffInfoDto.class);
return educationalStaffInfoDto;
} else {
return null;
}
}
}
<file_sep>package com.dreamworks.sms.student.dto;
import java.io.Serializable;
import java.util.Date;
import com.dreamworks.sms.student.dto.StudentQueryDto.StudentQueryDtoBuilder;
import com.dreamworks.sms.teacher.dto.TeacherDto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@SuppressWarnings("serial")
@AllArgsConstructor
@Data
@NoArgsConstructor
@Builder
@Accessors(chain = true)
public class StudentDto implements Serializable{
private String sno;
private String spwd;
private String sname;
private String ssex;
private Date sbirthday;
private String saddress;
private int tno;
private int pno;
private String sclass;
private int studentId;
private String ptel;
private TeacherDto teacherDto;
}
<file_sep>package com.dreamworks.sms.educationalStaff.service;
import org.springframework.stereotype.Service;
import com.dreamworks.sms.educationalStaff.dto.EducationalStaffInfoDto;
import com.dreamworks.sms.educationalStaff.dto.EducationalStaffQueryDto;
public interface EducationalStaffLoginService {
public EducationalStaffInfoDto findStaffByEducationalStaffId(EducationalStaffQueryDto educationalStaffQueryDto);
}
<file_sep>package com.dreamworks.sms.teacher.dto;
import java.io.Serializable;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@SuppressWarnings("serial")
@AllArgsConstructor
@Data
@NoArgsConstructor
@Builder
@Accessors(chain = true)
public class TeacherDto implements Serializable{
private int tno;
private String tpwd;
//身份识别
private int ttag;
private int radio;
}
<file_sep>package com.dreamworks.sms.student.dto;
import java.io.Serializable;
import java.util.Date;
import com.dreamworks.sms.classInfo.dto.ClassInfoDto;
import com.dreamworks.sms.student.dto.StudentQueryDto.StudentQueryDtoBuilder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@SuppressWarnings("serial")
@AllArgsConstructor
@Data
@NoArgsConstructor
@Builder
@Accessors(chain = true)
public class StudentInfoDto implements Serializable{
private Integer studentId;
private String studnetName;
private boolean sex;
private Date birth;
private String adress;
private Integer classId;
private Integer grade;
private String password;
private ClassInfoDto classInfoDto;
}<file_sep>package com.dreamworks.sms.teacher.dao;
import org.apache.ibatis.annotations.Mapper;
import com.dreamworks.sms.student.dto.StudentQueryDto;
import com.dreamworks.sms.student.po.StudentPo;
import com.dreamworks.sms.teacher.dto.TeacherQueryDto;
import com.dreamworks.sms.teacher.po.TeacherInfoPo;
import com.dreamworks.sms.teacher.po.TeacherPo;
@Mapper
public interface TeacherLoginMapper {
public TeacherInfoPo findTeacherByTeacherId(TeacherQueryDto teacherQueryDto);
public TeacherInfoPo getTeacherInfo(TeacherQueryDto teacherQueryDto);
}
<file_sep>package com.dreamworks.sms.score.dto;
import java.io.Serializable;
import java.util.List;
import com.dreamworks.sms.score.dto.ScoreInfoQueryDto.ScoreInfoQueryDtoBuilder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@SuppressWarnings("serial")
@AllArgsConstructor
@Data
@NoArgsConstructor
@Builder
@Accessors(chain = true)
public class ScoreInfoListDto implements Serializable{
private List<ScoreInfoDto> list;
}
<file_sep>package com.dreamworks.sms.score.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dreamworks.sms.course.dto.CourseInfoDto;
import com.dreamworks.sms.score.dao.ScoreInfoMapper;
import com.dreamworks.sms.score.dto.ScoreInfoDto;
import com.dreamworks.sms.score.dto.ScoreInfoQueryDto;
import com.dreamworks.sms.score.dto.ScoreInfoReDto;
import com.dreamworks.sms.score.po.ScoreInfoPo;
import com.dreamworks.sms.score.po.SumScoreInfoPo;
import com.dreamworks.sms.score.service.ScorInfoService;
import com.dreamworks.sms.student.dto.StudentInfoDto;
import com.dreamworks.sms.teacher.dao.TeacherLoginMapper;
import com.dreamworks.sms.teacher.dto.TeacherQueryDto;
import com.dreamworks.sms.teacher.po.TeacherInfoPo;
@Service
public class ScoreInfoServiceImpl implements ScorInfoService{
@Autowired
private ScoreInfoMapper scoreInfoMapper;
@Autowired
private TeacherLoginMapper teacherLoginMapper;
@Override
public List<ScoreInfoDto> getScoreInfoByStudentId(ScoreInfoQueryDto scoreInfoQueryDto) {
// TODO Auto-generated method stub
List<ScoreInfoPo> list = scoreInfoMapper.getScoreInfoByStudentId(scoreInfoQueryDto);
ScoreInfoReDto scoreInfoReDto3 = new ScoreInfoReDto(scoreInfoQueryDto.getStudentId(), null, null,scoreInfoQueryDto.getExaminationName());
System.out.println(scoreInfoReDto3.getStudentId()+"================");
SumScoreInfoPo sumScoreInfoPo1 = scoreInfoMapper.getSumScoreInfo(scoreInfoReDto3);
scoreInfoReDto3.setClassId(list.get(0).getClassId());
SumScoreInfoPo sumScoreInfoPo2 = scoreInfoMapper.getSumScoreInfo(scoreInfoReDto3);
ScoreInfoPo sumScoreInfoPo = new ScoreInfoPo();
sumScoreInfoPo.setRowNum(sumScoreInfoPo2.getRowNum());
sumScoreInfoPo.setSchoolRowNum(sumScoreInfoPo1.getRowNum());
sumScoreInfoPo.setScoreNum(sumScoreInfoPo2.getSumScore());
List<ScoreInfoDto> l = new ArrayList<ScoreInfoDto>();
ModelMapper modelMapper = new ModelMapper();
for(ScoreInfoPo scoreInfoPo : list) {
ScoreInfoReDto scoreInfoReDto1 = new ScoreInfoReDto(scoreInfoPo.getStudentId(), scoreInfoPo.getClassId(), scoreInfoPo.getCourseId(),scoreInfoQueryDto.getExaminationName());
System.out.println(scoreInfoReDto1.getStudentId()+"================");
ScoreInfoPo scoreInfoPo1 = scoreInfoMapper.getScoreInfoRowNum(scoreInfoReDto1);
scoreInfoPo.setRowNum(scoreInfoPo1.getRowNum());
System.out.println(scoreInfoPo.getStudentId()+"================");
ScoreInfoReDto scoreInfoReDto2 = new ScoreInfoReDto(scoreInfoPo.getStudentId(), null, scoreInfoPo.getCourseId(),scoreInfoQueryDto.getExaminationName());
System.out.println(scoreInfoReDto2.getStudentId()+"================");
ScoreInfoPo scoreInfoPo2 = scoreInfoMapper.getScoreInfoRowNum(scoreInfoReDto2);
scoreInfoPo.setSchoolRowNum(scoreInfoPo2.getRowNum());
StudentInfoDto studentInfoDto = modelMapper.map(scoreInfoPo.getStudentInfoPo(),StudentInfoDto.class);
CourseInfoDto courseInfoDto = modelMapper.map(scoreInfoPo.getCourseInfoPo(),CourseInfoDto.class);
ScoreInfoDto sDto = modelMapper.map(scoreInfoPo,ScoreInfoDto.class);
sDto.setStudentInfoDto(studentInfoDto);
sDto.setCourseInfoDto(courseInfoDto);
l.add(sDto);
}
ScoreInfoDto scoreInfoDto = modelMapper.map(sumScoreInfoPo,ScoreInfoDto.class);
CourseInfoDto c = new CourseInfoDto();
c.setCourseName("总分");
scoreInfoDto.setCourseInfoDto(c);
l.add(scoreInfoDto);
return l;
}
@Override
public List<ScoreInfoDto> getListScoreInfo(ScoreInfoQueryDto scoreInfoQueryDto) {
// TODO Auto-generated method stub
List<ScoreInfoPo> list = scoreInfoMapper.getScoreInfoByStudentId(scoreInfoQueryDto);
List<ScoreInfoDto> l = new ArrayList<ScoreInfoDto>();
ModelMapper modelMapper = new ModelMapper();
for(ScoreInfoPo scoreInfoPo : list) {
StudentInfoDto studentInfoDto = modelMapper.map(scoreInfoPo.getStudentInfoPo(),StudentInfoDto.class);
CourseInfoDto courseInfoDto = modelMapper.map(scoreInfoPo.getCourseInfoPo(),CourseInfoDto.class);
ScoreInfoDto sDto = modelMapper.map(scoreInfoPo,ScoreInfoDto.class);
sDto.setStudentInfoDto(studentInfoDto);
sDto.setCourseInfoDto(courseInfoDto);
l.add(sDto);
}
return l;
}
@Override
public int InsertListScoreInfo(List<ScoreInfoDto> list) {
// TODO Auto-generated method stub
List<ScoreInfoDto> l = new ArrayList<ScoreInfoDto>();
TeacherQueryDto teacherQueryDto = new TeacherQueryDto();
teacherQueryDto.setClassId(list.get(0).getClassId());
teacherQueryDto.setCourseId(list.get(0).getCourseId());
System.out.println("======================="+teacherQueryDto);
TeacherInfoPo teacherInfoPo = teacherLoginMapper.getTeacherInfo(teacherQueryDto);
System.out.println("=======================");
for(ScoreInfoDto scoreInfoDto : list) {
scoreInfoDto.setTeacherId(teacherInfoPo.getTeacherId());
l.add(scoreInfoDto);
}
int i = scoreInfoMapper.InsertListScoreInfo(l);
return i;
}
@Override
public Map<Integer, List<ScoreInfoDto>> getClassScoreInfo(ScoreInfoQueryDto scoreInfoQueryDto) {
// TODO Auto-generated method stub
List<ScoreInfoPo> list = scoreInfoMapper.getClassScoreInfo(scoreInfoQueryDto);
List<ScoreInfoDto> l = new ArrayList<ScoreInfoDto>();
ModelMapper modelMapper = new ModelMapper();
for(ScoreInfoPo scoreInfoPo : list) {
StudentInfoDto studentInfoDto = modelMapper.map(scoreInfoPo.getStudentInfoPo(),StudentInfoDto.class);
CourseInfoDto courseInfoDto = modelMapper.map(scoreInfoPo.getCourseInfoPo(),CourseInfoDto.class);
ScoreInfoDto sDto = modelMapper.map(scoreInfoPo,ScoreInfoDto.class);
sDto.setStudentInfoDto(studentInfoDto);
sDto.setCourseInfoDto(courseInfoDto);
l.add(sDto);
}
Map<Integer, List<ScoreInfoDto>> map = new HashMap<Integer, List<ScoreInfoDto>>();
for(ScoreInfoDto src : l) {
if(map.containsKey(src.getStudentId())) {
map.get(src.getStudentId()).add(src);
} else {
List<ScoreInfoDto> newList = new ArrayList<ScoreInfoDto>();
newList.add(src);
map.put(src.getStudentId(),newList);
}
}
return map;
}
@Override
public List<ScoreInfoDto> getClassOneScoreInfo(ScoreInfoQueryDto scoreInfoQueryDto) {
// TODO Auto-generated method stub
List<ScoreInfoPo> list = scoreInfoMapper.getClassScoreInfo(scoreInfoQueryDto);
List<ScoreInfoDto> l = new ArrayList<ScoreInfoDto>();
ModelMapper modelMapper = new ModelMapper();
for(ScoreInfoPo scoreInfoPo : list) {
StudentInfoDto studentInfoDto = modelMapper.map(scoreInfoPo.getStudentInfoPo(),StudentInfoDto.class);
CourseInfoDto courseInfoDto = modelMapper.map(scoreInfoPo.getCourseInfoPo(),CourseInfoDto.class);
ScoreInfoDto sDto = modelMapper.map(scoreInfoPo,ScoreInfoDto.class);
sDto.setStudentInfoDto(studentInfoDto);
sDto.setCourseInfoDto(courseInfoDto);
l.add(sDto);
}
return l;
}
}
<file_sep>package com.dreamworks.sms.score.dto;
import java.io.Serializable;
import java.util.List;
import com.dreamworks.sms.score.dto.ScoreInfoQueryDto.ScoreInfoQueryDtoBuilder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@SuppressWarnings("serial")
@AllArgsConstructor
@Data
@NoArgsConstructor
@Builder
@Accessors(chain = true)
public class ScoreInfoReDto implements Serializable{
private Integer studentId;
private Integer classId;
private Integer courseId;
private Integer examinationName;
}
<file_sep>package com.dreamworks.sms.teacher.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.dreamworks.sms.resouce.JsonResult;
import com.dreamworks.sms.resouce.ResultCode;
import com.dreamworks.sms.resouce.UserToken;
import com.dreamworks.sms.student.dto.StudentInfoDto;
import com.dreamworks.sms.teacher.dto.TeacherDto;
import com.dreamworks.sms.teacher.dto.TeacherInfoDto;
import com.dreamworks.sms.teacher.dto.TeacherQueryDto;
import com.dreamworks.sms.teacher.service.TeacherLoginService;
@RestController
@RequestMapping("/teacher")
@CrossOrigin
public class TeacherLoginController {
@Autowired
private TeacherLoginService teacherLoginService;
@RequestMapping(value = "/findTeacherByTeacherId" , method = RequestMethod.GET)
public JsonResult findTeacherByTno(TeacherQueryDto teacherQueryDto){
TeacherInfoDto teacherInfoDto=teacherLoginService.findTeacherByTeacherId((teacherQueryDto));
Subject subject = SecurityUtils.getSubject();
UserToken token = new UserToken(teacherQueryDto.getTeacherId(),teacherQueryDto.getPassword(),"teacher");
try {
subject.login(token);
return new JsonResult(ResultCode.SUCCESS, "登录成功", teacherInfoDto);
} catch (UnknownAccountException e) {
return new JsonResult(ResultCode.NOT_DATA, "用户名不存在");
} catch (IncorrectCredentialsException e) {
return new JsonResult(ResultCode.FAIL, "密码错误");
}
}
}
<file_sep>package com.dreamworks.sms.student.po;
import java.io.Serializable;
import java.util.Date;
import com.dreamworks.sms.classInfo.dto.ClassInfoDto;
import com.dreamworks.sms.classInfo.po.ClassInfoPo;
import com.dreamworks.sms.student.dto.StudentInfoDto;
import com.dreamworks.sms.student.dto.StudentInfoDto.StudentInfoDtoBuilder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@SuppressWarnings("serial")
@AllArgsConstructor
@Data
@NoArgsConstructor
@Builder
@Accessors(chain = true)
public class StudentInfoPo implements Serializable{
private Integer studentId;
private String studnetName;
private boolean sex;
private Date birth;
private String adress;
private Integer classId;
private Integer grade;
private String password;
private ClassInfoPo classInfoPo;
}
| 759639683163a8bd75d6609c27499db38a178ea9 | [
"JavaScript",
"Java"
] | 19 | Java | godofkey/StusentManagerSystem | 4a4e6a93e037a8e785b211cfc74acdc749186ed7 | 686d01c8ff188168b82e5e2e05f02639e8762490 |
refs/heads/master | <file_sep>#define FILEVER 2,14,0,149
#define PRODUCTVER 2,14,0,149
#define STRFILEVER "2.14.0.149+-jp-149"
#define STRPRODUCTVER "2.14.0.149+-jp-149"
| ecd641528e083fd9e30511956260557ad4d9c725 | [
"C"
] | 1 | C | damiankaczkowski/winmerge-v2-jp | 575bdb0244131571aec8acaed23f1941774aaa30 | 9a5d9f0c1e150388b84974d50b18ab3da1649b37 |
refs/heads/master | <file_sep># simple-IAM
A simple implementation of Learning Instance Activation Maps for Weakly Supervised Instance Segmentation, in CVPR 2019 (Spotlight)
A simple implementation as my homework, modified based on [ultra-thin-PRM](https://github.com/chuchienshu/ultra-thin-PRM).
Implementation details With my own understanding of the paper, it may be different from the author.
This implementation performs better when training demo and other datasets with fewer samples, but when I use VOC2012 training, the loss cannot be reduced. :(
If you have any good suggestions, please let me know. Thank you !
### Reference
```markdown
@article{Zhu2019IAM,
title={{Learning Instance Activation Maps for Weakly Supervised Instance Segmentation}},
author = {<NAME> <NAME> <NAME> <NAME> <NAME> <NAME>.},
booktitle = {CVPR},
year = {2019}
}
```
<file_sep>import torch.nn as nn
class EncodeModule(nn.Module):
def __init__(self, channel_num=16, pool_multiple=None):
super(EncodeModule, self).__init__()
if pool_multiple is None:
pool_multiple = [2, 2]
self.pool_multiple = pool_multiple
# encode modules
self.encode1 = nn.Sequential(
nn.Conv2d(1, channel_num, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(channel_num, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=self.pool_multiple[0], stride=self.pool_multiple[0]),
)
self.encode2 = nn.Sequential(
nn.Conv2d(channel_num, channel_num, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(channel_num, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=self.pool_multiple[1], stride=self.pool_multiple[1]),
)
def forward(self, x):
x = self.encode1(x)
x = self.encode2(x)
return x
<file_sep>from functools import reduce
import torch
import torch.nn as nn
from iam.models.decode_module import DecodeModule
from iam.models.encode_module import EncodeModule
from iam.models.feature_pyramid import FeaturePyramid
class InstanceExtentFilling(nn.Sequential):
def __init__(self, channel_num=16, kernel=3, iterate_num=10,
pool_multiple=None, image_size=448, feature_map_channel=2048):
super(InstanceExtentFilling, self).__init__()
if pool_multiple is None:
pool_multiple = [2, 2]
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.iterate_num = iterate_num
self.channel_num = channel_num
self.pool_multiple = pool_multiple
self.kernel = kernel
self.W = self.H = image_size // reduce(lambda x, y: x * y, self.pool_multiple)
self.encode = EncodeModule(self.channel_num, self.pool_multiple)
self.decode = DecodeModule(self.channel_num, self.pool_multiple)
self.feature_pyramid = FeaturePyramid(self.channel_num, self.kernel, feature_map_channel, self.H, self.W)
def _iterate_filling(self, inp, peak_list, weight):
batch_num = weight.size(0)
offset = (self.kernel - 1) // 2
padding = torch.nn.ConstantPad2d(offset, 0)
padding_inp = padding(inp)
repeat_inp = padding_inp.unsqueeze(4)
repeat_inp = repeat_inp.unsqueeze(5)
repeat_inp = repeat_inp.repeat(1, 1, 1, 1, self.kernel, self.kernel)
ret = torch.zeros_like(repeat_inp[:, :, offset:-offset, offset:-offset])
for x_offset in range(-offset, offset + 1):
for y_offset in range(-offset, offset + 1):
mat_x_offset = offset + x_offset
mat_y_offset = offset + y_offset
ret[:, :, :, :, mat_x_offset, mat_y_offset] = repeat_inp[
:, :,
mat_x_offset:mat_x_offset + self.W,
mat_y_offset:mat_y_offset + self.H,
offset, offset]
result = torch.zeros_like(ret)
for batch_idx in range(batch_num):
mask = peak_list[:, 0] == batch_idx
if mask.sum().item() == 0:
continue
result[mask] = ret[mask] * weight[batch_idx]
result = result.view(result.size(0), result.size(1),
result.size(2), result.size(3), -1
)
result = result.sum(4)
return result
@staticmethod
def _norm_weight(weight):
weight_size = weight.size()
weight_kernel = weight.view(weight.size(0), weight.size(1),
weight.size(2), weight.size(3), -1)
weight_kernel_sum = weight_kernel.sum(4)
weight_kernel_sum = weight_kernel_sum.unsqueeze(4)
mask = weight_kernel_sum[:, :, :, :] == 0
weight_kernel_sum[mask] = 1
norm_weight = weight_kernel / weight_kernel_sum
norm_weight = norm_weight.view(weight_size)
return norm_weight
def forward(self, peak_response_maps, peak_list, feature_maps):
pyramid = self.feature_pyramid(feature_maps)
weight = pyramid.permute(0, 2, 3, 1)
weight = weight.view(feature_maps.shape[0], self.H, self.W,
self.channel_num, self.kernel, self.kernel)
weight = weight.permute(0, 3, 1, 2, 4, 5)
norm_weight = self._norm_weight(weight)
inp = peak_response_maps.unsqueeze(1)
x = self.encode(inp)
for i in range(self.iterate_num):
x = self._iterate_filling(x, peak_list, norm_weight)
decode_out = self.decode(x)
decode_out = decode_out.squeeze(1)
return decode_out
<file_sep>import torch.nn as nn
import torch.nn.functional as F
class DecodeModule(nn.Module):
def __init__(self, channel_num=16, pool_multiple=None):
super(DecodeModule, self).__init__()
if pool_multiple is None:
pool_multiple = [2, 2]
self.pool_multiple = pool_multiple
# decode modules
self.decode1 = nn.Sequential(
nn.ConvTranspose2d(channel_num, channel_num, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(channel_num, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
)
self.decode2 = nn.Sequential(
nn.ConvTranspose2d(channel_num, channel_num, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(channel_num, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
)
self.decode3 = nn.Sequential(
nn.ConvTranspose2d(channel_num, 1, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(1, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
nn.Sigmoid(),
)
def forward(self, x):
x = self.decode1(x)
upsampling_size = [x.size(2), x.size(3)]
upsampling_size = [item * self.pool_multiple[-1] for item in upsampling_size]
x = F.interpolate(x, size=upsampling_size, mode='bilinear', align_corners=True)
x = self.decode2(x)
upsampling_size = [x.size(2), x.size(3)]
upsampling_size = [item * self.pool_multiple[-2] for item in upsampling_size]
x = F.interpolate(x, size=upsampling_size, mode='bilinear', align_corners=True)
x = self.decode3(x)
return x
<file_sep>import torch.nn as nn
import torch.nn.functional as F
class FeaturePyramid(nn.Module):
def __init__(self, channel_num=16, kernel=3, input_feature=2048, H=112, W=112):
super(FeaturePyramid, self).__init__()
self.H = H
self.W = W
self.r = kernel
self.C = channel_num
feature_num = self.r * self.r * self.C
intermediate_feature = input_feature // 4
self.feature1 = nn.Sequential(
nn.Conv2d(input_feature, intermediate_feature, kernel_size=(1, 1), stride=1),
nn.BatchNorm2d(intermediate_feature, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
# nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False),
)
self.feature2 = nn.Sequential(
nn.Conv2d(intermediate_feature, feature_num, kernel_size=1, stride=1),
nn.BatchNorm2d(feature_num, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
# nn.ReLU(inplace=True),
)
self.lateral_layer1 = nn.Sequential(
nn.Conv2d(input_feature, feature_num, kernel_size=1, stride=1),
nn.BatchNorm2d(feature_num, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
)
self.lateral_layer2 = nn.Sequential(
nn.Conv2d(intermediate_feature, feature_num, kernel_size=1, stride=1),
nn.BatchNorm2d(feature_num, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
)
self.smooth1 = nn.Sequential(
nn.Conv2d(feature_num, feature_num, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(feature_num, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
)
self.smooth2 = nn.Sequential(
nn.Conv2d(feature_num, feature_num, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(feature_num, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
)
self.smooth_out = nn.Sequential(
nn.Conv2d(feature_num, feature_num, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(feature_num, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
)
def forward(self, c1):
c2 = self.feature1(c1)
p3 = self.feature2(c2)
p2_size = (c2.size(2), c2.size(3))
p3 = F.interpolate(p3, size=p2_size, mode='bilinear', align_corners=True)
p2 = p3 + self.lateral_layer2(c2)
p2 = self.smooth2(p2)
p1_size = (c1.size(2), c1.size(3))
p3 = F.interpolate(p3, size=p1_size, mode='bilinear', align_corners=True)
p2 = F.interpolate(p2, size=p1_size, mode='bilinear', align_corners=True)
p1 = p2 + self.lateral_layer1(c1)
p1 = self.smooth1(p1)
out = p1 + p2 + p3
out = F.interpolate(out, size=(self.H, self.W), mode='bilinear', align_corners=True)
out = self.smooth_out(out)
return out
| d16f3bfc94a49f20b2bde59420977f9d92b60878 | [
"Markdown",
"Python"
] | 5 | Markdown | bityangke/simple-IAM | 5cd5bb0ab4a0eb1ecef3f382256705211c7270ce | b6c0faa74d538f8e6e574ef1a551a6c5ec43bb64 |
refs/heads/master | <repo_name>wealiar/ztm-robofriends-v2<file_sep>/src/containers/App.test.js
import { shallow } from 'enzyme';
import React from 'react';
import App from './App';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const mockStore = configureMockStore([thunk]);
const storeStateMock = {
searchRobots: {
searchField: 'D'
},
requestRobots: {
isPending: false,
robots: [],
error: ''
}
};
let store;
let wrapper;
beforeEach(() => {
store = mockStore(storeStateMock);
wrapper = shallow(<App store={store} />).shallow();
});
describe('App smart component', () => {
it('expect to render App component', () => {
expect(wrapper).toMatchSnapshot();
});
});<file_sep>/src/actions.test.js
import * as constants from './constants';
import * as actions from './actions';
import configureMockStore from 'redux-mock-store';
import thunkMiddleware from 'redux-thunk';
import { apiCall } from './api/api';
const nock = require('nock');
let mockStore = configureMockStore([thunkMiddleware]);
describe('setSearchField action', () => {
it('should create an action to search robots', () => {
const text = 'wooo';
const expectedAction = {
type: constants.CHANGE_SEARCH_FIELD,
payload: text,
};
expect(actions.setSearchField(text)).toEqual(expectedAction);
});
});
describe('requestRobots action', () => {
mockStore = mockStore();
it('handles requesting robots API - pending', () => {
mockStore.dispatch(actions.requestRobots());
const action = mockStore.getActions();
// console.log('action is', action);
const expectedAction = {
type: constants.REQUEST_ROBOTS_PENDING
};
expect(action[0]).toEqual(expectedAction);
});
it('handles requesting robots API - success', async () => {
expect.assertions(1);
const scope = nock('https://jsonplaceholder.typicode.com')
.persist()
.get('/users')
.reply(200, {
data: [{
id: 1,
name: "<NAME>",
username: "Bret",
email: "<EMAIL>",
address: {
street: "Kulas Light",
suite: "Apt. 556",
city: "Gwenborough",
zipcode: "92998-3874",
geo: {
lat: "-37.3159",
lng: "81.1496"
}
},
phone: "1-770-736-8031 x56442",
website: "hildegard.org",
company: {
name: "Romaguera-Crona",
catchPhrase: "Multi-layered client-server neural-net",
bs: "harness real-time e-markets"
}
}],
}, {
'Access-Control-Allow-Origin': '*',
'Content-type': 'application/json',
}
);
return apiCall('https://jsonplaceholder.typicode.com/users').then(data => {
mockStore.dispatch(actions.requestRobots());
const action = mockStore.getActions();
// console.log('action is', action);
const expectedAction = {
type: constants.REQUEST_ROBOTS_SUCCESS,
payload: data
};
expect(action[1]).toEqual(expectedAction);
});
});
// it('handles requesting robots API - error', async () => {
// expect.assertions(1);
// const scope = nock('https://test.com')
// .persist()
// .get('/test')
// .replyWithError('test');
// try {
// return apiCall('https://test.com/test');
// } catch (error) {
// mockStore.dispatch(actions.requestRobots());
// const action = mockStore.getActions();
// console.log('action is', action);
// const expectedAction = {
// type: constants.REQUEST_ROBOTS_FAILED,
// payload: error
// };
// expect(action[2]).toEqual(expectedAction);
// }
// });
}); | f9061270cbfa5595cf52cd48302dca6652e8fb4f | [
"JavaScript"
] | 2 | JavaScript | wealiar/ztm-robofriends-v2 | a21044773a47f0a8f823f23bc4693092234c7b1d | e457f3004694abae2e5910d844b1815de4c4eefc |
refs/heads/master | <repo_name>ztran/xtrie<file_sep>/xtrie_pf.c
/*
* xtrie_pf.c
*
* Created on: Aug 11, 2015
* Author: <NAME>
*/
#include <stdio.h>
#include <sys/time.h>
#include <math.h>
#include <unistd.h>
#include "xtrie.h"
#include <ck_rwlock.h>
#include <urcu.h>
#include <getopt.h>
#define LINE_MAX_LENGTH 100
/**
* Define called_data_t type
*/
typedef struct __called_data_t {
int call_prefix_id; /* Id of called_data_t in 16 bits */
int dn_set; /* Set of dialed number */
int route_id; /* Routing id */
int min_len; /* Min length of prefix number from 1 to 32*/
int max_len; /* Max length of prefix number */
int nai; /* Called number address nature */
int call_type; /* Call type i.e normal, cfu, cfnry, cfnr */
int number_type; /* Called number type */
int emergency_call; /* 113, 114 or 115 */
int dn_processing; /* flag for processing dialed number */
int caller_analysis_flag; /* boolean 0 or 1 */
} called_data_t;
typedef struct __rf_data_t {
void* data;
LIST_ENTRY(__rf_data_t) link;
}rf_data_t;
/* nai type */
enum{
NAI_UNKNOWN_NUMBER = 0,
NAI_INTERNATIONAL_NUMBER,
NAI_NATIONAL_SIGNIFICANT_NUMBER,
NAI_NETWORK_SPECIFIC_NUMBER,
NAI_SUBSCRIBER_NUMBER,
NAI_ABBREVIATED_NUMBER,
NAI_RESERVED_NUMBER, /* for defining later */
NAI_ALL_NUMBER
};
enum{
CT_CFB = 1,//!< CFB
CT_CFU, //!< CFU
CT_CFNRY, //!< CFNRY
CT_CFNRC, //!< CFNRC
CT_ALL, //!< ALL
CT_NORMAL //!< NORMAL
};
typedef LIST_HEAD(__rf_data_list_t,__rf_data_t) rf_data_list_t;
int insert_called_cb(rf_data_list_t** root,xtrie_data_t* arg,int* size, unsigned int* ecode) {
rf_data_t* item = NULL;
rf_data_t* i = NULL;
called_data_t* data = NULL;
data = (called_data_t*)arg->data;
if(data == NULL) {
*ecode = XTRIE_BAD_STRUCT;
return XTRIE_FALSE;
}
if((*root) == NULL) {
*root = XTRIE_ALLOC(sizeof(rf_data_list_t));
if(*root == NULL) {
*ecode = XTRIE_OUT_OF_MEMORY;
return XTRIE_FALSE;
}
*size += sizeof(rf_data_list_t);
LIST_INIT((*root));
}
/* check for duplicate */
LIST_FOREACH(i,(*root),link) {
if(i->data && (memcmp(data,i->data,sizeof(called_data_t)) == 0)) {
*ecode = XTRIE_STRUCT_EXISTED;
return XTRIE_FALSE;
}
}
item = XTRIE_ALLOC(sizeof(rf_data_t));
if(item == NULL) {
*ecode = XTRIE_OUT_OF_MEMORY;
return XTRIE_FALSE;
}
*size += (sizeof(rf_data_t) + arg->size);
memset(item,0,sizeof(rf_data_t));
item->data = data;
LIST_INSERT_HEAD((*root),item,link);
return XTRIE_SUCCESS;
}
void* search_called_cb(rf_data_list_t* root, xtrie_data_t* arg, int plen) {
rf_data_t* i = NULL;
called_data_t* p = NULL;
called_data_t* cond = NULL;
cond = (called_data_t*)arg->data;
if(root == NULL || cond == NULL) {
return NULL;
}
LIST_FOREACH(i,root,link) {
p = (called_data_t*)i->data;
if(((p->nai == cond->nai) || (p->nai == NAI_ALL_NUMBER))
&& ((p->call_type == cond->call_type) || (p->call_type == CT_ALL))
&& (p->min_len <= plen) && (p->max_len >= plen)) {
break;
}else {
p = NULL;
}
}
return p;
}
int delete_called_cb(rf_data_list_t** root,xtrie_data_t* arg,int* size) {
rf_data_t* i = NULL;
rf_data_t* j = NULL;
called_data_t* p = NULL;
called_data_t* cond = NULL;
printf("pp = %p \n",root);
if(root != NULL) printf("p = %p \n",*root);
if(root == NULL || *root == NULL) {
return XTRIE_SUCCESS;
}
if(arg == NULL || arg->data == NULL) {
/* delete all */
i = (*root)->lh_first;
while(i != NULL) {
printf(">>>>>>>>>>> i = %p\n",i);
j = i;
i = j->link.le_next;
XTRIE_FREE(j->data);
XTRIE_FREE(j);
}
XTRIE_FREE((*root));
}else {
cond = (called_data_t*)arg->data;
/* search and delete */
LIST_FOREACH(i,(*root),link) {
p = (called_data_t*)i->data;
printf("%d >>>>>>>>>>> i = %p\n",__LINE__,i);
if(p != NULL && p->call_prefix_id == cond->call_prefix_id) {
printf(">>>>>>>>>>>>>>>>> free i->data %p\n",i->data);
XTRIE_FREE(p);
LIST_REMOVE(i,link);
XTRIE_FREE(i);
break;
}
}
if((*root)->lh_first == NULL) {
printf(">>>>>>>>>>>> free root \n");
XTRIE_FREE((*root));
}
}
return XTRIE_SUCCESS;
}
/**
* walk_called_cb: walk callback for called xtrie
* @param root
* @param p
* @param env
*/
void walk_called_cb(rf_data_list_t* root,xtrie_prefix_t* p,void* env) {
rf_data_t* i = NULL;
called_data_t* d = NULL;
if(root != NULL) {
printf("%s=>",p->prefix);
}
LIST_FOREACH(i,root,link) {
// printf("DBG i=%p\n",i);
d = (called_data_t*)i->data;
if(d) {
printf(",%p",d);
}
}
printf("\n");
}
void do_insert(xtrie_t* x, const char* fn) {
FILE* f = NULL;
char line[LINE_MAX_LENGTH];
xtrie_prefix_t prefix;
int xval = 0;
called_data_t* xdata = NULL;
xtrie_data_t data;
unsigned int ecode = 0;
f = fopen(fn, "rt");
if (f == NULL) {
fprintf(stderr, "error when opening %s\n", fn);
}
memset(line, 0, LINE_MAX_LENGTH);
memset(&prefix, 0, sizeof(xtrie_prefix_t));
while (fgets(line, LINE_MAX_LENGTH, f) != NULL) {
memset(&prefix, 0, sizeof(xtrie_prefix_t));
sscanf(line, "%d:%s", &xval, prefix.prefix);
prefix.end = strlen(prefix.prefix) - 1;
prefix.ptr = 0;
xdata = (called_data_t*) malloc(sizeof(called_data_t));
xdata->route_id = xval;
xdata->call_prefix_id = 1;
xdata->call_type = CT_ALL;
xdata->nai = 7;
xdata->min_len = 1;
xdata->max_len = 20;
xdata->dn_set = 1;
xdata->number_type = 0;
xdata->emergency_call = 0;
xdata->dn_processing = 0;
xdata->caller_analysis_flag = 0;
ecode = 0;
data.data = xdata;
data.size = sizeof(called_data_t);
if (xtrie_insert(x,&prefix,&data,&ecode) != XTRIE_SUCCESS) {
fprintf(stderr, "xtrie_insert %s=>%d : fail %u\n", prefix.prefix,xval, ecode);
free(xdata);
xdata = NULL;
}else {
printf("xtrie_insert %s=>%d : pass %u\n",prefix.prefix,xval, x->size);
}
memset(&prefix, 0, sizeof(xtrie_prefix_t));
}
fclose(f);
f = NULL;
}
void do_search(xtrie_t* x, const char* fn) {
FILE* f = NULL;
char line[LINE_MAX_LENGTH];
xtrie_prefix_t prefix;
int xval = 0;
called_data_t* xdata = NULL;
called_data_t cond;
xtrie_data_t data;
f = fopen(fn, "rt");
if (f == NULL) {
fprintf(stderr, "error when opening %s\n", fn);
}
memset(line, 0, LINE_MAX_LENGTH);
memset(&prefix, 0, sizeof(xtrie_prefix_t));
memset(&cond,0,sizeof(called_data_t));
while (fgets(line, LINE_MAX_LENGTH, f) != NULL) {
memset(&prefix, 0, sizeof(xtrie_prefix_t));
sscanf(line, "%d:%s", &xval, prefix.prefix);
prefix.end = strlen(prefix.prefix) - 1;
prefix.ptr = 0;
xdata = NULL;
cond.call_type = 0;
cond.nai = 1;
data.data = &cond;
data.size = sizeof(called_data_t);
xdata = (called_data_t*)xtrie_search(x, &prefix, &data);
if (xdata != NULL) {
if (xval == xdata->route_id) {
printf("xtrie_search %s=>%d : pass\n", prefix.prefix, xval);
} else {
fprintf(stderr, "xtrie_search => not equal\n");
}
} else {
fprintf(stderr, "xtrie_search => NULL\n");
}
}
fclose(f);
f = NULL;
}
void do_delete(xtrie_t* x, const char* fn) {
FILE* f = NULL;
char line[LINE_MAX_LENGTH];
xtrie_prefix_t prefix;
int xval = 0;
called_data_t cond;
xtrie_data_t data;
f = fopen(fn, "rt");
if (f == NULL) {
fprintf(stderr, "error when opening %s\n", fn);
}
memset(line, 0, LINE_MAX_LENGTH);
memset(&prefix, 0, sizeof(xtrie_prefix_t));
memset(&cond,0,sizeof(called_data_t));
while (fgets(line, LINE_MAX_LENGTH, f) != NULL) {
memset(&prefix, 0, sizeof(xtrie_prefix_t));
sscanf(line, "%d:%s", &xval, prefix.prefix);
prefix.end = strlen(prefix.prefix) - 1;
prefix.ptr = 0;
cond.call_prefix_id = 1;
cond.call_type = 0;
cond.nai = 1;
cond.route_id = xval;
data.data = &cond;
data.size = sizeof(called_data_t);
if (xtrie_delete(x,&prefix,&data) != XTRIE_SUCCESS) {
fprintf(stderr, "xtrie_delete: is failed\n");
}else {
printf("xtrie_delete: is successful \n");
}
// xtrie_walk(x);
}
fclose(f);
f = NULL;
}
double time_diff(struct timeval* x, struct timeval* y) {
double x_ms, y_ms, diff;
x_ms = (double) x->tv_sec * 1000000 + (double) x->tv_usec;
y_ms = (double) y->tv_sec * 1000000 + (double) y->tv_usec;
diff = (double) y_ms - (double) x_ms;
return diff;
}
#define XTRIE_PF_WORKER 4
#define XTRIE_BENCHMARK0 2
#define XTRIE_BENCHMARK1 100000000
#define LCK_R_FLAG 1
#define LCK_W_FLAG 2
pthread_mutex_t g_pf_mut;
ck_rwlock_t g_ck_lock;
pthread_rwlock_t g_pthread_lock;
pthread_key_t g_pk;
long double g_tps = 0;
int g_workers = 0;
int g_pf_test = 1;
typedef struct __xtrie_scheduler_t {
volatile unsigned int lck;
volatile unsigned int pending;
}xtrie_scheduler_t;
extern void pf_pthreadlck_worker(xtrie_t* x);
extern void pf_cklck_worker(xtrie_t* x);
extern void pf_nolck_worker(xtrie_t* x);
extern void pf_atomic_worker(xtrie_t* x);
int main(int argc, char **argv) {
int i = 0, j = 0, c = 0, t = 0,w = XTRIE_PF_WORKER;
char fn[200];
char* ptr = NULL;
xtrie_t x;
pthread_t tworker[XTRIE_PF_WORKER];
pthread_rwlockattr_t lckattr;
/* ARGS */
memset(fn, 0, 200);
while ((c = getopt(argc, argv, "w:t:f:")) != -1) {
switch (c) {
case 't':
t = (int)(strtol(optarg,&ptr,10));
break;
case 'w':
w = (int)(strtol(optarg,&ptr,10));
break;
case 'f':
ptr = NULL;
memcpy(fn,optarg,strlen(optarg));
break;
default:
break;
}
}
/* LOCK */
pthread_mutex_init(&g_pf_mut, NULL);
ck_rwlock_init(&g_ck_lock);
pthread_rwlockattr_init(&lckattr);
pthread_rwlockattr_setpshared(&lckattr, PTHREAD_PROCESS_SHARED);
pthread_rwlockattr_setkind_np(&lckattr, PTHREAD_RWLOCK_PREFER_READER_NP);
pthread_rwlock_init(&g_pthread_lock, &lckattr);
pthread_key_create(&g_pk,NULL);
/* LOGIC BEGIN */
xtrie_init(&x);
x.insert_fn = (xtrie_insert_data_fn) insert_called_cb;
x.search_fn = (xtrie_search_data_fn) search_called_cb;
x.delete_fn = (xtrie_delete_data_fn) delete_called_cb;
x.walk_fn = (xtrie_walk_data_fn) walk_called_cb;
x.root->mask = XTRIE_NODE_ROOT;
printf("Run TC%d => %s\n", i, fn);
printf("BEGIN size = %d, depth = %d \n", x.size, x.root->depth);
do_insert(&x, fn);
printf("INSERT size = %d, depth = %d \n", x.size, x.root->depth);
do_search(&x, fn);
xtrie_walk(&x, NULL);
printf("CURRENT size = %d, depth = %d \n", x.size, x.root->depth);
if (g_pf_test) {
printf("START PERFORMANCE \n");
tworker[0] = pthread_self();
if(t == 0) {
printf("USING PTHREAD_RWLOCK \n");
for (j = 1; j < w; j++) {
pthread_create(&tworker[j], NULL, (void*) pf_pthreadlck_worker,
(void*) &x);
}
pf_pthreadlck_worker(&x);
}else if(t == 1){
printf("USING CK_RWLOCK \n");
for (j = 1; j < w; j++) {
pthread_create(&tworker[j], NULL, (void*) pf_cklck_worker,
(void*) &x);
}
pf_cklck_worker(&x);
}else if(t == 2){
printf("USING ATOMIC LOCK\n");
for (j = 1; j < w; j++) {
pthread_create(&tworker[j], NULL, (void*) pf_atomic_worker,
(void*) &x);
}
pf_atomic_worker(&x);
}else {
printf("USING NO LOCK \n");
for (j = 1; j < w; j++) {
pthread_create(&tworker[j], NULL, (void*) pf_nolck_worker,
(void*) &x);
}
pf_nolck_worker(&x);
}
while (1) {
pthread_mutex_lock(&g_pf_mut);
if (g_workers >= w) {
pthread_mutex_unlock(&g_pf_mut);
break;
}
pthread_mutex_unlock(&g_pf_mut);
usleep(1000);
}
pthread_mutex_lock(&g_pf_mut);
printf("END PERFORMANCE => TOTAL TPS %Lf\n", g_tps);
pthread_mutex_unlock(&g_pf_mut);
}
do_delete(&x, fn);
printf("DELETE size = %d, depth = %d \n", x.size, x.root->depth);
printf("End TC%d\n", i);
xtrie_destroy(&x);
/* LOGIC END */
pthread_mutex_destroy(&g_pf_mut);
pthread_rwlock_destroy(&g_pthread_lock);
pthread_rwlockattr_destroy(&lckattr);
pthread_key_delete(g_pk);
return 0;
}
void pf_atomic_worker(xtrie_t* x) {
int j = 0, k = 0;
xtrie_prefix_t plong;
xtrie_data_t vlong;
called_data_t* xdata;
called_data_t* xret;
called_data_t vret;
long double diff_t = 0, tps = 0;
struct timeval start_t, end_t;
xtrie_scheduler_t tsd;
xtrie_scheduler_t* tsd1 = NULL;
tsd.lck = LCK_R_FLAG;
pthread_setspecific(g_pk,&tsd);
/* BEGIN */
gettimeofday(&start_t, NULL);
for (j = 0; j < XTRIE_BENCHMARK0; j++) {
for (k = 0; k < XTRIE_BENCHMARK1; k++) {
memset(&plong, 0, sizeof(xtrie_prefix_t));
strcpy(plong.prefix, "01234567890123");
plong.ptr = 0;
plong.end = strlen("01234567890123") - 1;
xtrie_check_digit_prefix(plong.prefix,plong.end + 1);
xdata = XTRIE_ALLOC(sizeof(called_data_t));
memset(xdata,0,sizeof(called_data_t));
xdata->call_type = 0;
xdata->nai = 1;
vlong.data = xdata;
vlong.size = sizeof(called_data_t);
tsd1 = (xtrie_scheduler_t*)pthread_getspecific(g_pk);
if(__sync_bool_compare_and_swap(&tsd1->lck,LCK_R_FLAG,LCK_R_FLAG)) {
__sync_lock_test_and_set(&tsd1->pending,1);
xret = xtrie_search(x, &plong, &vlong);
if(xret != NULL) {
memcpy(&vret,xret,sizeof(vret));
}
__sync_lock_release(&tsd1->pending);
}else {
pthread_rwlock_rdlock(&g_pthread_lock);
xret = xtrie_search(x, &plong, &vlong);
if(xret != NULL) {
memcpy(&vret,xret,sizeof(vret));
}
pthread_rwlock_unlock(&g_pthread_lock);
}
XTRIE_FREE(xdata);
}
}
gettimeofday(&end_t, NULL);
diff_t = time_diff(&start_t, &end_t);
tps = (long double) (XTRIE_BENCHMARK0 * XTRIE_BENCHMARK1);
tps = ((tps * 1000000) / diff_t);
printf("THREAD %lu AVG TPS = %Lf \n", pthread_self(), tps);
pthread_mutex_lock(&g_pf_mut);
g_tps = g_tps + tps;
g_workers++;
pthread_mutex_unlock(&g_pf_mut);
/* END */
}
void pf_pthreadlck_worker(xtrie_t* x) {
int j = 0, k = 0;
xtrie_prefix_t plong;
xtrie_data_t vlong;
called_data_t* xdata;
called_data_t* xret;
called_data_t vret;
long double diff_t = 0, tps = 0;
struct timeval start_t, end_t;
/* BEGIN */
gettimeofday(&start_t, NULL);
for (j = 0; j < XTRIE_BENCHMARK0; j++) {
for (k = 0; k < XTRIE_BENCHMARK1; k++) {
memset(&plong, 0, sizeof(xtrie_prefix_t));
strcpy(plong.prefix, "01234567890123");
plong.ptr = 0;
plong.end = strlen("01234567890123") - 1;
xtrie_check_digit_prefix(plong.prefix,plong.end + 1);
xdata = XTRIE_ALLOC(sizeof(called_data_t));
memset(xdata,0,sizeof(called_data_t));
xdata->call_type = 0;
xdata->nai = 1;
vlong.data = xdata;
vlong.size = sizeof(called_data_t);
pthread_rwlock_rdlock(&g_pthread_lock);
xret = xtrie_search(x, &plong, &vlong);
if(xret != NULL) {
memcpy(&vret,xret,sizeof(vret));
}
pthread_rwlock_unlock(&g_pthread_lock);
XTRIE_FREE(xdata);
}
}
gettimeofday(&end_t, NULL);
diff_t = time_diff(&start_t, &end_t);
tps = (long double) (XTRIE_BENCHMARK0 * XTRIE_BENCHMARK1);
tps = ((tps * 1000000) / diff_t);
printf("THREAD %lu AVG TPS = %Lf \n", pthread_self(), tps);
pthread_mutex_lock(&g_pf_mut);
g_tps = g_tps + tps;
g_workers++;
pthread_mutex_unlock(&g_pf_mut);
/* END */
}
void pf_cklck_worker(xtrie_t* x) {
int j = 0, k = 0;
xtrie_prefix_t plong;
xtrie_data_t vlong;
called_data_t* xdata;
called_data_t* xret;
called_data_t vret;
long double diff_t = 0, tps = 0;
struct timeval start_t, end_t;
/* BEGIN */
gettimeofday(&start_t, NULL);
for (j = 0; j < XTRIE_BENCHMARK0; j++) {
for (k = 0; k < XTRIE_BENCHMARK1; k++) {
memset(&plong, 0, sizeof(xtrie_prefix_t));
strcpy(plong.prefix, "01234567890123");
plong.ptr = 0;
plong.end = strlen("01234567890123") - 1;
xtrie_check_digit_prefix(plong.prefix,plong.end + 1);
xdata = XTRIE_ALLOC(sizeof(called_data_t));
memset(xdata,0,sizeof(called_data_t));
xdata->call_type = 0;
xdata->nai = 1;
vlong.data = xdata;
vlong.size = sizeof(called_data_t);
ck_rwlock_read_lock(&g_ck_lock);
xret = xtrie_search(x, &plong, &vlong);
if(xret != NULL) {
memcpy(&vret,xret,sizeof(vret));
}
ck_rwlock_read_unlock(&g_ck_lock);
XTRIE_FREE(xdata);
}
}
gettimeofday(&end_t, NULL);
diff_t = time_diff(&start_t, &end_t);
tps = (long double) (XTRIE_BENCHMARK0 * XTRIE_BENCHMARK1);
tps = ((tps * 1000000) / diff_t);
printf("THREAD %lu AVG TPS = %Lf \n", pthread_self(), tps);
pthread_mutex_lock(&g_pf_mut);
g_tps = g_tps + tps;
g_workers++;
pthread_mutex_unlock(&g_pf_mut);
/* END */
}
void pf_nolck_worker(xtrie_t* x) {
int j = 0, k = 0;
xtrie_prefix_t plong;
xtrie_data_t vlong;
called_data_t* xdata;
called_data_t* xret;
called_data_t vret;
long double diff_t = 0, tps = 0;
struct timeval start_t, end_t;
memset(&plong, 0, sizeof(xtrie_prefix_t));
strcpy(plong.prefix, "01234567890123");
plong.ptr = 0;
plong.end = strlen("01234567890123") - 1;
/* BEGIN */
gettimeofday(&start_t, NULL);
for (j = 0; j < XTRIE_BENCHMARK0; j++) {
for (k = 0; k < XTRIE_BENCHMARK1; k++) {
memset(&plong, 0, sizeof(xtrie_prefix_t));
strcpy(plong.prefix, "01234567890123");
plong.ptr = 0;
plong.end = strlen("01234567890123") - 1;
xtrie_check_digit_prefix(plong.prefix,plong.end + 1);
xdata = XTRIE_ALLOC(sizeof(called_data_t));
memset(xdata,0,sizeof(called_data_t));
xdata->call_type = 0;
xdata->nai = 1;
vlong.data = xdata;
vlong.size = sizeof(called_data_t);
xret = xtrie_search(x, &plong, &vlong);
if(xret != NULL) {
memcpy(&vret,xret,sizeof(vret));
}
XTRIE_FREE(xdata);
}
}
gettimeofday(&end_t, NULL);
diff_t = time_diff(&start_t, &end_t);
tps = (long double) (XTRIE_BENCHMARK0 * XTRIE_BENCHMARK1);
tps = ((tps * 1000000) / diff_t);
printf("THREAD %lu AVG TPS = %Lf \n", pthread_self(), tps);
pthread_mutex_lock(&g_pf_mut);
g_tps = g_tps + tps;
g_workers++;
pthread_mutex_unlock(&g_pf_mut);
/* END */
}
<file_sep>/README.md
# xtrie
another Radix tree implement for the longest digit matching<file_sep>/xtrie.h
/*
* xtrie.h
*
* Created on: Aug 11, 2015
* Author: <NAME>
*/
#ifndef XTRIE_H_
#define XTRIE_H_
#include <stdlib.h>
#include <sys/queue.h>
#include <string.h>
#ifdef ENIF
#include "erl_nif.h"
#define XTRIE_ALLOC(a) enif_alloc(a)
#define XTRIE_FREE(a) do { \
if (a != NULL) { enif_free(a); }\
a = NULL; \
}while(0)
#else
#define XTRIE_ALLOC(a) malloc(a)
#define XTRIE_FREE(a) do { \
if (a != NULL) { free(a); }\
a = NULL; \
}while(0)
#endif
#define XTRIE_DIGIT
#define XTRIE_MAX_LEAF 16
#define ISMASK(a,b) (a & b)
#define XTRIE_SUCCESS 1
#define XTRIE_FALSE 0
#define XTRIE_PREFIX_MAX_LENGTH 20
#define XTRIE_ID2CHAR(a,c) do { \
if((a) >= 0 && (a) <= 9) { c = ((a) + '0'); } \
else if ((a) >= 10 && (a) <= 13) { c= ((a) - 10 + 'a');} \
else if ((a) == 14) { c = '*'; } \
else { c = '#'; } \
}while(0)
#define XTRIE_CHAR2ID(c,id) do { id = (c) - '0'; \
if(id > 9) { id = (c) - 'a' + 10; } \
else if(id < 0 ) { if(c == '*') { id = 14; } else { id = 15; } } \
}while(0)
#define XTRIE_PREFIX_TRIM(a) memset((a)->prefix + (a)->ptr,0,XTRIE_PREFIX_MAX_LENGTH - (a)->ptr)
typedef enum {
XTRIE_NODE_ROOT = 1,
XTRIE_NODE_PARENT = 2,
XTRIE_NODE_CHILD = 4
}XTRIE_LEAF_TYPE;
typedef enum {
XTRIE_NO_ERROR = 0,
XTRIE_BAD_ARG,
XTRIE_OUT_OF_MEMORY,
XTRIE_BAD_STRUCT,
XTRIE_STRUCT_EXISTED,
XTRIE_UNKNOWN_ERROR
}XTRIE_ERROR;
typedef struct __xtrie_node_t xtrie_node_t;
typedef struct __xtrie_prefix_t xtrie_prefix_t;
typedef struct __xtrie_data_t xtrie_data_t;
typedef struct __xtrie_cond_t xtrie_cond_t;
typedef unsigned int xtrie_error_t;
typedef int (*xtrie_insert_data_fn)(void** root, void* data, int* size, xtrie_error_t* ecode);
typedef void* (*xtrie_search_data_fn)(void* data, void* cond, int prefix_len);
typedef int (*xtrie_delete_data_fn)(void** root, void* data, int* size);
typedef void (*xtrie_walk_data_fn)(void* root,xtrie_prefix_t* p, void* extra);
struct __xtrie_node_t {
int depth;
unsigned int mask;
#ifdef XTRIE_DIGIT
int max_digit;
xtrie_node_t* child[XTRIE_MAX_LEAF];
#else
xtrie_node_t* child;
#endif
xtrie_node_t* parent;
void* data;
};
struct __xtrie_prefix_t {
char prefix[XTRIE_PREFIX_MAX_LENGTH];
int end;
int ptr;
};
struct __xtrie_data_t {
int size;
void* data;
};
struct __xtrie_cond_t {
};
typedef struct __xtrie_t {
int type; /* type of trie */
int size; /* size of trie on memory */
int dsize; /* atom data size */
xtrie_node_t* root;
xtrie_insert_data_fn insert_fn;
xtrie_search_data_fn search_fn;
xtrie_delete_data_fn delete_fn;
xtrie_walk_data_fn walk_fn;
}xtrie_t;
#define xtrie_node_init(x) do { \
memset((x),0,sizeof(xtrie_node_t)); \
(x)->mask = XTRIE_NODE_CHILD; \
(x)->max_digit = 0; \
(x)->depth = 0; \
(x)->parent = NULL; \
(x)->data = NULL; \
}while(0)
#define xtrie_init(x) do {\
memset((x),0,sizeof(xtrie_t)); \
(x)->insert_fn = NULL; \
(x)->search_fn = NULL; \
(x)->delete_fn = NULL; \
(x)->walk_fn = NULL; \
if((x)->root == NULL) (x)->root = XTRIE_ALLOC(sizeof(xtrie_node_t)); \
xtrie_node_init((x)->root); \
(x)->size = sizeof(xtrie_t) + sizeof(xtrie_node_t); \
}while(0)
#define xtrie_insert(x,p,c,e) xtrie_insert_from((x)->root,p,(x)->insert_fn,c,&(x)->size,e)
#define xtrie_search(x,p,c) xtrie_search_from((x)->root,p,(x)->search_fn,c)
#define xtrie_delete(x,p,c) xtrie_delete_from((x)->root,p,(x)->delete_fn,c,&(x)->size)
#define xtrie_destroy(x) xtrie_destroy_from((&(x)->root),(x)->delete_fn)
#define xtrie_walk(x,e) xtrie_walk_from((x)->root,(x)->walk_fn,(e))
extern int xtrie_check_digit_prefix(const char* ptr,int len);
extern int xtrie_insert_from(xtrie_node_t* x,xtrie_prefix_t* prefix,xtrie_insert_data_fn fn, void* data, int* asize,xtrie_error_t* ecode);
extern void* xtrie_search_from(xtrie_node_t* x,xtrie_prefix_t* prefix,xtrie_search_data_fn fn, void* cond);
extern int xtrie_delete_from(xtrie_node_t* x,xtrie_prefix_t* prefix,xtrie_delete_data_fn fn, void* cond,int* asize);
extern int xtrie_destroy_from(xtrie_node_t** x,xtrie_delete_data_fn fn);
extern void xtrie_walk_from(xtrie_node_t* x,xtrie_walk_data_fn fn, void* ex);
extern const char* xtrie_error2str(unsigned int ecode);
#endif /* XTRIE_H_ */
<file_sep>/xtrie.c
/*
* xtrie.c
*
* Created on: Aug 11, 2015
* Author: <NAME>
*/
#include "xtrie.h"
#include <stdio.h>
inline void xtrie_update_depth(xtrie_node_t* x);
/**
*
*/
int xtrie_insert_from(xtrie_node_t* x,xtrie_prefix_t* prefix,xtrie_insert_data_fn fn, void* data,int* asize, xtrie_error_t* ecode) {
int leaf = 0;
xtrie_node_t* n = NULL;
if((x == NULL) || (prefix->end < 0) || fn == NULL || data == NULL) {
if(ecode != NULL) {
*ecode = XTRIE_BAD_ARG;
}
return XTRIE_FALSE;
}
while(prefix->ptr <= prefix->end) {
if(prefix->ptr == prefix->end) {
XTRIE_CHAR2ID(prefix->prefix[prefix->ptr],leaf);
n = x->child[leaf];
if(n != NULL) {
if(fn(&n->data,data,asize,ecode) == XTRIE_SUCCESS) {
/* do nothing */
}else {
return XTRIE_FALSE;
}
}else {
n = XTRIE_ALLOC(sizeof(xtrie_node_t));
if(n == NULL) {
if(ecode != NULL) {
*ecode = XTRIE_OUT_OF_MEMORY;
}
return XTRIE_FALSE;
}
memset(n,0,sizeof(xtrie_node_t));
xtrie_node_init(n);
if(fn(&n->data,data,asize,ecode) == XTRIE_SUCCESS) {
x->max_digit = (x->max_digit > leaf)?x->max_digit:leaf;
n->parent = x;
x->child[leaf] = n;
if(!(x->mask & XTRIE_NODE_PARENT)) {
x->mask |= XTRIE_NODE_PARENT;
xtrie_update_depth(x);
}
*asize += sizeof(xtrie_node_t);
}else {
XTRIE_FREE(n);
return XTRIE_FALSE;
}
}
break;
}else {
XTRIE_CHAR2ID(prefix->prefix[prefix->ptr],leaf);
n = x->child[leaf];
if(n != NULL) {
x = n;
}else {
n = XTRIE_ALLOC(sizeof(xtrie_node_t));
if(n == NULL) {
if(ecode != NULL) {
*ecode = XTRIE_OUT_OF_MEMORY;
}
return XTRIE_FALSE;
}
memset(n,0,sizeof(xtrie_node_t));
xtrie_node_init(n);
x->max_digit = (x->max_digit > leaf)?x->max_digit:leaf;
n->parent = x;
x->child[leaf] = n;
if(!(x->mask & XTRIE_NODE_PARENT)) {
x->mask |= XTRIE_NODE_PARENT;
xtrie_update_depth(x);
}
*asize += sizeof(xtrie_node_t);
x = n;
}
prefix->ptr++;
}
}
return XTRIE_SUCCESS;
}
void* xtrie_search_from(xtrie_node_t* x,xtrie_prefix_t* prefix,xtrie_search_data_fn fn, void* cond) {
void* d = NULL;
void* t = NULL;
int leaf = 0, rdepth = 0;
if((x == NULL) || (prefix->end < 0) || (fn == NULL) || cond == NULL) {
return d;
}
rdepth = x->depth;
while((x != NULL) && (prefix->ptr <= prefix->end) && (prefix->ptr <= rdepth)) {
XTRIE_CHAR2ID(prefix->prefix[prefix->ptr],leaf);
if(leaf >= 0 && leaf < XTRIE_MAX_LEAF) {
x = x->child[leaf];
if(x != NULL) {
t = fn(x->data,cond,prefix->end + 1);
if(t != NULL) {
d = t;
}
}
prefix->ptr++;
}else{
break;
}
}
return d;
}
inline int xtrie_rcompact_from(xtrie_node_t* x, int* asize);
int xtrie_delete_from(xtrie_node_t* x,xtrie_prefix_t* prefix,xtrie_delete_data_fn fn, void* cond,int* asize) {
int leaf = 0, ret = XTRIE_FALSE;
if(x == NULL || prefix == NULL || fn == NULL) {
return XTRIE_FALSE;
}
while((x != NULL) && (prefix->ptr <= prefix->end)) {
XTRIE_CHAR2ID(prefix->prefix[prefix->ptr],leaf);
if(leaf >= 0 && leaf < XTRIE_MAX_LEAF) {
x = x->child[leaf];
if((x != NULL) && (prefix->ptr == prefix->end)) {
ret = fn(&x->data,cond,asize);
if(x->data == NULL) {
xtrie_rcompact_from(x,asize);
}
return ret;
}else{
prefix->ptr++;
}
}else {
return XTRIE_FALSE;
}
}
return XTRIE_SUCCESS;
}
int xtrie_destroy_from(xtrie_node_t** x,xtrie_delete_data_fn fn) {
int i = 0;
if((x == NULL) || (*x == NULL)) {
return XTRIE_FALSE;
}
if((*x)->mask & XTRIE_NODE_PARENT) {
for(i = 0; i <= (*x)->max_digit; i++) {
xtrie_destroy_from(&(*x)->child[i],fn);
}
(*x)->mask ^= XTRIE_NODE_PARENT;
xtrie_destroy_from(x,fn);
}else {
fn(&(*x)->data,NULL,NULL);
XTRIE_FREE((*x));
}
return XTRIE_SUCCESS;
}
inline void xtrie_walk_from1(xtrie_node_t* x,xtrie_walk_data_fn fn, xtrie_prefix_t* p, void* ex);
void xtrie_walk_from(xtrie_node_t* x, xtrie_walk_data_fn fn, void* ex) {
xtrie_prefix_t p;
if(x == NULL || fn == NULL) {
return;
}
memset(&p,0,sizeof(xtrie_prefix_t));
xtrie_walk_from1(x,fn,&p,ex);
}
inline void xtrie_walk_from1(xtrie_node_t* x,xtrie_walk_data_fn fn, xtrie_prefix_t* p,void* ex) {
int i = 0;
char c = '0';
if(x == NULL) {
return;
}
if(x->mask & XTRIE_NODE_PARENT) {
if(x->data != NULL) {
fn(x->data,p,ex);
}
for(i = 0; i <= x->max_digit; i++) {
if(x->child[i] != NULL) {
XTRIE_ID2CHAR(i,c);
p->prefix[p->ptr++] = c;
xtrie_walk_from1(x->child[i],fn,p,ex);
p->ptr--;
XTRIE_PREFIX_TRIM(p);
}
}
}else {
if(x->data != NULL) {
fn(x->data,p,ex);
}
}
}
inline int xtrie_rcompact_from(xtrie_node_t* x,int* asize) {
int k = 0, i = 0, m = 0;
xtrie_node_t* t;
while(k < XTRIE_PREFIX_MAX_LENGTH) {
if(x != NULL) {
if(x->mask & (XTRIE_NODE_PARENT | XTRIE_NODE_ROOT)) {
xtrie_update_depth(x);
break;
}else {
t = x->parent;
if(t != NULL) {
for(i = 0; i <= t->max_digit; i++) {
if(t->child[i] == x && x->data == NULL) {
XTRIE_FREE(t->child[i]);
*asize -= sizeof(xtrie_node_t);
break;
}
}
m = 0;
for(i = 0; i <= t->max_digit; i++) {
if(t->child[i] != NULL) {
m = (i > m)?i:m;
}
}
t->max_digit = m;
if(t->max_digit == 0) {
t->mask ^= XTRIE_NODE_PARENT;
x = t;
}else {
xtrie_update_depth(t);
break;
}
}else {
break;
}
}
}else {
break;
}
}
return XTRIE_SUCCESS;
}
static const char* xtrie_merror[XTRIE_UNKNOWN_ERROR+1] = {"XTRIE_NO_ERROR","XTRIE_BAD_ARG","XTRIE_OUT_OF_MEMORY","XTRIE_BAD_STRUCT","XTRIE_STRUCT_EXISTED","XTRIE_UNKNOWN_ERROR"};
const char* xtrie_error2str(unsigned int ecode) {
if(ecode > XTRIE_UNKNOWN_ERROR) {
return xtrie_merror[XTRIE_UNKNOWN_ERROR];
}
return xtrie_merror[ecode];
}
int xtrie_check_digit_prefix(const char* ptr,int len) {
int ret = 0, i = 0;
if(ptr == NULL || len == 0) {
return ret;
}
ret = 1;
for(i = 0; i < len; i++) {
if((ptr[i] >= '0' && ptr[i] <= '9') || (ptr[i] >= 'a' && ptr[i] <= 'd') || ptr[i] == '*' || ptr[i] == '#') {
continue;
}else {
ret = 0;
break;
}
}
return ret;
}
inline void xtrie_update_depth(xtrie_node_t* x) {
int d = 0, k = 0, i = 0;
while(k < XTRIE_PREFIX_MAX_LENGTH) {
if(x != NULL) {
if(x->mask & (XTRIE_NODE_PARENT| XTRIE_NODE_ROOT)){
d = 0;
for(i = 0; i <= x->max_digit; i++) {
if(x->child[i] != NULL) {
if(d == 0) {
d = 1;
}
d = (x->child[i]->depth >= d)?x->child[i]->depth + 1:d;
}
}
x->depth = d;
x = x->parent;
}else {
x = x->parent;
}
}else {
break;
}
k++;
}
}
| 719d11c132aa9cf06e835522d4e972673186d5fc | [
"Markdown",
"C"
] | 4 | C | ztran/xtrie | a35a482a593c3ef8743ee16046e0c3551f0a3758 | 8595585baa608e337fadad134b639ef9cf0d88cc |
refs/heads/master | <repo_name>dyscada/dyscada.github.io<file_sep>/second.js
{
/* <script> */
}
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerWidth,
0.1,
1000
);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerWidth);
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", function () {
var width = window.innerWidth;
var height = window.innerWidth;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});
controls = new THREE.OrbitControls(camera, renderer.domElement);
//create the shape
var geometry = new THREE.BoxGeometry(1.2, 1.2, 1.2);
var cubeMaterials = [
new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load("img/Chol&Ryueae.png"),
side: THREE.DoubleSide, //Right Side
}),
new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load("img/Chol.png"),
side: THREE.DoubleSide, //Left Side
}),
new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load("img/eis.png"),
side: THREE.DoubleSide, //Top Side
}),
new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load("img/mcrc.png"),
side: THREE.DoubleSide, //Bottom Side
}),
new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load("img/Ryueae.png"),
side: THREE.DoubleSide, //Front Side
}),
new THREE.MeshBasicMaterial({
color: 0xffffff,
side: THREE.DoubleSide, //Back Side
}),
];
//create a amterial, color, or image texture
var material = new THREE.MeshFaceMaterial(cubeMaterials);
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 3;
// controls = new THREE.OrbitControls(camera, renderer.domElement);
// camera.position.z = 3;
// //create the shape
// //var geometry = new THREE.BoxGeometry(1.2, 1.2, 1.2);
// var geometry = new THREE.BoxGeometry(1000, 1000, 1000);
// var cubeMaterials = [
// new THREE.MeshBasicMaterial({
// map: new THREE.TextureLoader().load("img/px.jpg"), //
// side: THREE.DoubleSide, //Right Side
// }),
// new THREE.MeshBasicMaterial({
// map: new THREE.TextureLoader().load("img/nx.jpg"), //ok
// side: THREE.DoubleSide, //Left Side
// }),
// new THREE.MeshBasicMaterial({
// map: new THREE.TextureLoader().load("img/py.jpg"), //ok
// side: THREE.DoubleSide, //Top Side
// }),
// new THREE.MeshBasicMaterial({
// map: new THREE.TextureLoader().load("img/ny.jpg"), //
// side: THREE.DoubleSide, //Bottom Side
// }),
// new THREE.MeshBasicMaterial({
// map: new THREE.TextureLoader().load("img/pz.jpg"), //
// side: THREE.DoubleSide, //Front Side
// }),
// new THREE.MeshBasicMaterial({
// map: new THREE.TextureLoader().load("img/nz.jpg"), //
// side: THREE.DoubleSide, //Back Side
// }),
// ];
//create a material, color, or image texture
var cubeMaterial = new THREE.MeshFaceMaterial(cubeMaterials);
var cube = new THREE.Mesh(geometry, cubeMaterial);
scene.add(cube);
// var ambientLight = new THREE.ambientLight(0xffffff, 0.3);
// scene.add(ambientLight);
//Game logic
var update = function () {
// cube.rotation.x += 0.01;
// cube.rotation.y += 0.005;
};
//Draw scene
var render = function () {
renderer.render(scene, camera);
};
//run game loop(update, render, repeate)
var GameLoop = function () {
requestAnimationFrame(GameLoop);
update();
render();
};
GameLoop();
// </script>
| 4e469621d00576b5dd1b7be8ab1400d1fee41eec | [
"JavaScript"
] | 1 | JavaScript | dyscada/dyscada.github.io | 2067355dc51453a4aa71914b5556f622f6092641 | 550ffea4e4582dc33263d78f83c47f275e6a149b |
refs/heads/main | <repo_name>dactyrafficle/treemapping<file_sep>/README.md
# treemapping
treemapping!
https://dactyrafficle.github.io/treemapping/
** fix aggro -> pivotObj function
** choose a better boxing algo
in setup.js:
* change the data source inside fetch()
* change the value to sum by
* change the elements inside the categories array
makeBoxes
1. makeBoxes(0, 0, w, h, array_of_objects)
2. if array > 1? if so, SPLIT into 2, else return object with coordinates and dimensions
3. is h > w? get dimensions for recursive bit
4. makeBoxes(x1,y1,w1,h1,arr1) and makeBoxes(x2,y2,w2,h2,arr2)
need to store all the returns of makeBoxes and its recursive children
and improve SPLIT -> maybe 1. random split ie. n/2 elements per list
or what im using now, n_ where value > some percentage in one box, else in next box
2021-03-22
I think i know how I want the input data to be
[{"group":group,"value":value,"subgroups":[]}]
where subgroups are optional
<file_sep>/arrOfObj2PivotPartA.js
// USAGE:
// CONVERT ARR OF OBJS INTO AN N-LEVEL PIVOT STRUCTURE
// let x = arrOfObj2PivotPartA(data, 'val', 'cat1', 'cat2', ...., 'catn');
// *** ISSUE: WHAT IF A GIVEN CATN MAPS TO MORE THAN ONE CAT(N-1)? THIS ALGO WILL NOT CAPTURE THAT
// categories is an array ie. categories = ['cat1', 'cat2', ... , 'catn']
function arrOfObj2PivotPartA(arr, val, categories) {
let temp = [];
// ARGUMENTS 2, 3, ..., N ARE THE CATEGORIES WE WANT TO AGGREGATE BY
//for (let i = arguments.length-1; i>=2; i--) {
for (let i = categories.length-1; i>=0; i--) {
// FOR EACH OF THESE CATEGORIES, LET US GET THE CATEGORY NAME, AND ITS PARENTS NAME
let x_aggro = categories[i];
let x_parent;
// THE FIRST CATEGORY HAS NO PARENT, SO ITS PARENT IS ROOT
if (i === 0) {
x_parent = 'ROOT';
} else {
x_parent = categories[i-1];
}
// MAKE AN OBJECT TO STORE THE RESULTS FOR EACH LAYER
let obj = {};
for (let y = 0; y < arr.length; y++) {
let cat = arr[y][x_aggro];
if (!obj[cat]) {
obj[cat] = {};
obj[cat].name = cat;
obj[cat].parent = (arr[y][x_parent] || x_parent); // POSSIBLE ISSUE: ASSUMES 1-1 MAPPING OF CHILD-PARENT *** [year-cycle]
obj[cat].value = 0;
}
obj[cat].value += parseFloat(arr[y][val]);
}
temp.push(obj);
}
return temp; // this is 1/2 way there
}<file_sep>/createBoxElementsObject.js
function drawBoxes(b) {
// an array of object
let boxes = document.createElement('div');
boxes.id = 'box-container';
boxes.style.position = 'relative';
let A = 0;
for (let i = 0; i < b.boxes.length; i++) {
let box = b.boxes[i].el
boxes.appendChild(box);
}
boxes.style.width = b.container.w;
boxes.style.height = b.container.h;
return boxes;
}
function addEventListnersAndCreateInfoBox(b) {
let div = document.createElement('div');
div.id = 'hank';
for (let i = 0; i < b.boxes.length; i++) {
//console.log(b.boxes[i].obj);
let el = b.boxes[i].el;
el.addEventListener('mouseover', function() {
//console.log(this);
div.innerHTML = '';
for (let y = 0; y < b.boxes[i].obj.ancestors.length; y++) {
div.innerHTML += '<p> LEVEL ' + y + ': ' + b.boxes[i].obj.ancestors[y] + '</p>';
}
div.innerHTML += '<p> LEVEL ' + b.boxes[i].obj.ancestors.length + ': ' + b.boxes[i].obj.name + '</p>';
div.innerHTML += '<p> VALUE: ' + b.boxes[i].obj.value + '</p>';
});
}
return div;
}
function createArrOfBoxElementObjects(arr, s, s_unit) {
let output = [];
let A = 0;
for (let i = 0; i < arr.length; i++) {
let obj = arr[i];
let box = document.createElement('div');
box.classList.add('box');
box.style.position = 'absolute';
box.style.border = '1px solid #999';
box.style.top = (obj.py)/100*s + s_unit;
box.style.left = obj.px/100*s + s_unit;
let w = obj.sw/100*s;
let h = obj.sh/100*s;
A += w*h;
obj.A = A;
box.style.width = w + s_unit;
box.style.height = h + s_unit;
output.push({
'el': box,
'obj': obj
});
}
//console.log(boxes);
//console.log(Math.sqrt(A));
//boxes.style.width = Math.sqrt(A) + s_unit;
//boxes.style.height = Math.sqrt(A) + s_unit;
return {
"container":{
"w": Math.sqrt(A) + s_unit,
"h": Math.sqrt(A) + s_unit
},
"boxes": output
};
/*
return {
'boxes': boxes,
'width': Math.sqrt(A),
'height': Math.sqrt(A)
}
*/
}<file_sep>/arrOfObj2PivotPartB.js
function arrOfObj2PivotPartB(arr) {
// FOR EACH LEVEL
let root_value = 0;
let root_children = [];
for (let i = 0; i < (arr.length-1); i++) {
// REMEMBER, EACH ELEMENT IS AN OBJECT
Object.keys(arr[i]).forEach(function(a, b, c) {
let obj_name = a;
let obj = arr[i][a];
let parent_obj_name = obj.parent;
let parent_obj = arr[i+1][parent_obj_name];
if (!arr[i+1][parent_obj_name].children) {
//arr[i+1][parent_obj_name].children = {}; //lets make this an array instead
arr[i+1][parent_obj_name].children = [];
}
//arr[i+1][parent_obj_name].children[obj_name] = obj;
arr[i+1][parent_obj_name].children.push(obj);
});
}
Object.keys(arr[arr.length-1]).forEach(function(a, b, c) {
root_children.push(arr[arr.length-1][a]);
root_value += arr[arr.length-1][a].value;
});
return {
"name": "ROOT",
"parent": null,
"children": root_children,
"value": root_value
};
}
// EXCELLENT WORK!
function addAncestors(y) {
if (y.children) {
//console.log(y.children);
for (let i = 0; i < y.children.length; i++) {
y.children[i].ancestors = [];
if (y.ancestors) {
for (let j = 0; j < y.ancestors.length; j++) {
y.children[i].ancestors.push(y.ancestors[j]);
}
}
y.children[i].ancestors.push(y.name);
addAncestors(y.children[i]);
}
}
return y;
}<file_sep>/createBoxObjects.js
// 2021-03-24 LETS TRY ONLY MAKING THE SUBBOXES
function createBoxObjects(x, y, w, h, arr) {
let key = "value";
let thresh = 0.2;
let output = [];
if (arr.length > 1) {
// SPLIT THE ARRAY INTO 2
let arr2 = splitArr(arr, key, thresh);
let sum = getSum(arr, key);
let sum0 = getSum(arr2[0], key);
// DIMENSION OF BOXES
let dw = 0;
let dh = 0;
if (w > h) {dw=1; dh=0;} else {dw=0; dh=1;}
let x1 = x;
let x2 = x1 + dw*(sum0/sum)*w;
let y1 = y;
let y2 = y1 + dh*(sum0/sum)*h;
let w1 = dw*(sum0/sum)*w + dh*w;
let w2 = dw*(w-w1) + dh*w;
let h1 = dw*h + dh*(sum0/sum)*h;
let h2 = dw*h + dh*(h-h1);
// THIS WAS NOT THAT EASY TO FIGURE OUT
return output.concat(createBoxObjects(x1, y1, w1, h1, arr2[0]), createBoxObjects(x2, y2, w2, h2, arr2[1]));
} else {
// IF ARR.LENGTH === 1, THEN WE MIGHT BE ABLE TO MAKE BOXES
let obj = arr[0]; // correct
obj.px = x;
obj.py = y;
obj.sw = w;
obj.sh = h;
// IF THE OBJECT HAS CHILDREN
if (obj.children) {
return output.concat(createBoxObjects(x, y, w, h, obj.children));
} else {
return output.concat(obj);
}
}
}
// CALCULATE SUM ON THE BASIS OF KEY
function getSum(arr, key) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += parseInt(arr[i][key]);
}
return sum;
}
// SPLIT THE ARRAY INTO 2 ARRAYS ON THE BASIS OF THE SUM OF KEY
// ARR IS AN ARRAY OF OBJECTS
function splitArr(arr, key, thresh_pct) {
// IF THE ARRAY HAS 1 ELEMENT, RETURN THE ARRAY
if (arr.length < 2) {
return arr;
}
// SORT THE ARRAY, BIGGEST TO SMALLEST
arr.sort(function(a,b) {
if (parseInt(a[key]) > parseInt(b[key])) {return -1;};
if (parseInt(a[key]) < parseInt(b[key])) {return 1;};
if (parseInt(a[key]) === parseInt(b[key])) {return 0;};
});
let temp = [[],[]];
let sum = getSum(arr, key);
let sum0 = 0;
// THE FIRST VALUE GOES IN THE FIRST ARRAY BY DEFAULT
temp[0].push(arr[0]);
sum0 = parseInt(arr[0][key]);
sum0_pct = sum0 / sum;
for (let i = 1; i < arr.length; i++) {
// THE LAST ELEMENT OF ARR ALWAYS GOES TO THE SECOND ARRAY
if (sum0_pct < thresh_pct && i !== (arr.length-1)) {
temp[0].push(arr[i]);
sum0 += parseInt(arr[i][key]);
sum0_pct = sum0 / sum;
} else {
temp[1].push(arr[i]);
}
}
return temp;
} | 8582db1c29f96300c7e3dad0eb1344d09a19b76f | [
"Markdown",
"JavaScript"
] | 5 | Markdown | dactyrafficle/treemapping | a6c3a9762aa41c2a2fbd63e4b950fe0b7544da04 | 40893030a4881e35c5dcf442d1e74781a56c41ee |
refs/heads/master | <file_sep># lovepad
Virtual gamepad texture for love2d
## How to use
### Require
```lua
local texturelovepad = require "game-tools.texturelovepad"
```
## Creating a button
```lua
texturelovepad:new{
id = "name",
x = 20,
y = 50,
width = 128,
height = 72,
buttonPressed = love.graphics.newImage("buttonPressed.png"),
buttonNormal = love.graphics.newImage("buttonNormal.png")
-- ...
}
```
Note: The button is instanced in `texturelovepad.buttons`.
## Button Properties
| Property | Type |
|-----------|:------:|
| id | string |
| x | number |
| y | number |
| width | number |
| height | number |
| buttonPressed | love.graphics.newImage |
| buttonNormal | love.graphics.newImage |
| sx | number |
| sy | number |
| r | number |
| ox | number |
| oy | number |
| kx | number |
| ky | number |
## Functions
```lua
texturelovepad:draw()
```
Draws the buttons.
```lua
texturelovepad:update()
```
Updates the buttons.
```lua
texturelovepad:isDown(id)
```
Returns `true` if the button `id` (text value) is pressed.
```lua
texturelovepad:isPressed(id)
```
Returns `true` if the button `id` (text value) is pressed once.
```lua
texturelovepad:isReleased(id)
```
Returns `true` if the button `id` (text value) is released.
```lua
texturelovepad:remove(id)
```
Removes the button `id` (text value)
<file_sep>local color = {_VERSION = "v0.1.0", _TYPE = "module", _NAME = "color"}
local newColorMt = {
__tostring = function(s)
return "color(" .. s.r .. ", " .. s.g .. ", " .. s.b .. ", " .. s.a ..")"
end,
__add = function(a, b)
if type(a) == "number" then return color(a + b.r, a + b.g, a + b.b, a + b.a)
elseif type(b) == "number" then return color(a.r + b, a.g + b, a.b + b, a.a + b) end
--assert(a.r and b.r and a.g and b.g and a.a and b.a,"error adding color")
return color(a.r + b.r, a.g + b.g, a.b + b.b, a.a + b.a)
end,
__sub = function(a, b)
if type(a) == "number" then return color(a - b.r, a - b.g, a - b.b, a - b.a)
elseif type(b) == "number" then return color(a.r - b, a.g - b, a.b - b, a.a - b) end
return color(a.r - b.r, a.g - b.g, a.b - b.b, a.a - b.a)
end,
__mul = function(a, b)
if type(a) == "number" then return color(a * b.r, a * b.g, a * b.b, a * b.a)
elseif type(b) == "number" then return color(a.r * b, a.g * b, a.b * b, a.a * b) end
return color(a.r * b.r, a.g * b.g, a.b * b.b, a.a * b.a)
end,
__div = function(a, b)
if type(a) == "number" then return color(a / b.r, a / b.g, a / b.b, a / b.a)
elseif type(b) == "number" then return color(a.r / b, a.g / b, a.b / b, a.a / b) end
return color(a.r / b.r, a.g / b.g, a.b / b.b, a.a / b.a)
end,
__unm = function(t)
return color(-t.r,-t.g,-t.b,-t.a)
end,
__eq = function(a, b)
return a.r == b.r and a.g == b.g and a.b == b.b and a.a == b.a
end,
__pow = function(col, value)
return color(col.r ^ value, col.g ^ value, col.b ^ value, col.a ^ value)
end,
__concat = function(a, b)
if type(a) == "string" then return a .. tostring(b) end
if type(b) == "string" then return tostring(a) .. b end
return tostring(a) .. tostring(b)
end
}
local function clamp(n, low, high) return math.min(math.max(n, low), high) end
local mt = {
__call = function(_, r,g,b,a)
local col = {r = r or 1.0, g = g or 1.0, b = b or 1.0, a = a or 1.0}
col.r = clamp(col.r, 0.0,1.0)
col.g = clamp(col.g, 0.0,1.0)
col.b = clamp(col.b, 0.0,1.0)
col.a = clamp(col.a, 0.0,1.0)
setmetatable(col, newColorMt)
return col
end
}
function color.grayscale(c)
-- Weighted method or luminosity method
local r,g,b,a = c.r*.3,c.g*.59,c.b*.11,c.a
local gray = r+g+b
return color(gray,gray,gray,a)
end
function color.unpack(c)
return c.r,c.g,c.b,c.a
end
function color.hexcode(str)
if #str == 6 then
local r,g,b = tonumber(str:sub(1,2),16), tonumber(str:sub(3,4),16), tonumber(str:sub(5,6),16)
return color.rgb(r,g,b)
elseif #str == 8 then
local r,g,b = tonumber(str:sub(1,2),16), tonumber(str:sub(3,4),16), tonumber(str:sub(5,6),16)
local a = tonumber(str:sub(7,8),16)
return color.rgba(r,g,b,a)
end
end
function color.rgb(r,g,b)
local max = 255
return color(r/max,g/max,b/max)
end
function color.rgba(r,g,b,a)
local max = 255
return color(r/max,g/max,b/max,a/max)
end
-- function color.inverted(c)
-- return color(1-c.r,1-c.g,1-c.b,c.a)
-- end
-- function color.blend(c1, c2)
-- local r,g,b,a = c1.r+c2.r, c1.g+c2.g,c1.b+c2.b,c1.a+c2.a
-- --local r = (c.r*c.a) * ((1-c.a) * bg.r)
-- --local g = (c.g*c.a) * ((1-c.a) * bg.g)
-- --local b = (c.b*c.a) * ((1-c.a) * bg.b)
-- return color(r,g,b,a)
-- end
setmetatable(color, mt)
return color
<file_sep>package = "game-tools"
version = "0.4.0-3"
source = {
url = "git+https://github.com/DeybisMelendez/game-tools"
}
description = {
summary = "Game tools for Love2D",
detailed = [[Include:
- Vector 2D - Vector math
- Lovepad - Create buttons for multitouch devices.
- Texturelovepad - Create texture buttons for multitouch devices.
- Color - Color math and utilities
- Scene - State pattern for game scenes]],
homepage = "https://github.com/DeybisMelendez/game-tools",
license = "MIT"
}
dependencies = {}
build = {
type = "builtin",
modules = {
["game-tools.vector"] = "vector.lua",
["game-tools.lovepad"] = "lovepad.lua",
["game-tools.texturelovepad"] = "texturelovepad.lua",
["game-tools.color"] = "color.lua",
["game-tools.scene"] = "scene.lua"
}
}
<file_sep># game-tools.vector
Vector 2d for Love2d and Lua.
## How to use
### Require
```lua
local vector = require "game-tools.vector"
```
## Properties
<table>
<tr>
<td>number</td>
<td>x</td>
</tr>
<tr>
<td>number</td>
<td>y</td>
</tr>
</table>
## Create a vector
Example:
```lua
a = vector(5, 4)
print(a) --> vector(5, 4) or print(tostring(a))
b = vector(3, 2)
if a.x > b.x then print(a .. b) end --> vector(5, 4)vector(3, 2)
c = a + b
print(c) --> vector(8, 6) or print(tostring(c))
b = -b --> vector(-3, -2)
```
## Constants
<table>
<tr>
<th>Constant</th>
<th>Value</th>
</tr>
<tr>
<td>vector.UP</td>
<td>vector(0,-1)</td>
</tr>
<tr>
<td>vector.DOWN</td>
<td>vector(0,1)</td>
</tr>
<tr>
<td>vector.LEFT</td>
<td>vector(-1, 0)</td>
</tr>
<tr>
<td>vector.RIGHT</td>
<td>vector(1, 0)</td>
</tr>
<tr>
<td>vector.ZERO</td>
<td>vector(0,0)</td>
</tr>
<tr>
<td>vector.ONE</td>
<td>vector(1,1)</td>
</tr>
</table>
## Functions
```lua
vector.angle(vector)
```
Returns the angle of vector in radians.
```lua
vector.normalized(vec)
```
Set the vector normalized. Normalizing a vector means reducing its length to 1 while preserving its direction.
```lua
vector.distanceTo(vec1, vec2)
```
Returns the distance between 2 vectors.
```lua
vector.distanceSquaredTo(vec1, vec2)
```
Returns the distance squared between 2 vectors.
```lua
vector.distance(vec)
```
Returns the distance of the vector.
```lua
vector.distanceSquared(vec)
```
Returns the distance squared of the vector.
```lua
vector.dot(vec1, vec2)
```
Returns the [dot product](https://en.wikipedia.org/wiki/Dot_product) of 2 vectors.
```lua
vector.perpDot(vec1, vec2)
```
Returns the [Perp Dot Product](http://mathworld.wolfram.com/PerpDotProduct.html) of 2 vectors.
```lua
vector.toPolar(vec, angle, lenght)
```
Set the vector to the polar coordinate.
```lua
vector.abs(vec)
```
Set the absolute value of the vector.
```lua
vector.round(vec, decimals)
```
Set the vector with `decimals`, 0 or ignore for integer number. Example: `vector(2.5, 3.4):round() --> vector(3, 3)`
```lua
vector.rotated(vec, phi)
```
Set the vector rotated by `phi`radians.
```lua
vector.cross(vec1, vec2)
```
Returns the 2 dimensional analog of the cross product with the given vector.
```lua
vector.perpendicular(vec)
```
Set the vector rotated 90°.
```lua
vector.lerpTo(vec1, vec2, time)
```
Set the result of the linear interpolation between this vector and `vector` by amount `time`. `time` is in the range of 0.0 - 1.0, representing the amount of interpolation.
```lua
vector.unpack(vec)
```
Returns `x, y` value of the vector.
## Vector Math
### Addition
```lua
this = vector(a, b) + vector(c, d) --> vector(a+c, b+d)
```
### Substraction
```lua
this = vector(a, b) - vector(c, d) --> vector(a-c, b-d)
```
### Multiplication
```lua
this = vector(a, b) * vector(c, d) --> vector(a*c, b*d)
```
### Division
```lua
this = vector(a, b) / vector(c, d) --> vector(a/c, b/d)
```
### Exponetiation
```lua
this = vector(a, b) ^ c --> vector(a^c, b^c)
```
### Concatenation
```lua
this = vector(a, b) .. vector(c, d) --> "vector(a, b)vector(c, d)"
```
<file_sep>local scene = {}
scene.state = {}
function scene:__exit()
if self.state.onExit then self.state:onExit() end
end
function scene:__load()
if self.state.onLoad then self.state:onLoad() end
end
function scene:setScene(s)
self:__exit()
self.state = nil
collectgarbage("collect")
self.state = require(s)
self.current = s
self:__load()
end
function scene:reload()
self:__exit()
self.state = nil
collectgarbage("collect")
self.state = require(self.lib)
self:__load()
end
local mt = {
__index = function(table, key)
if table.state[key] then return table.state[key] end
end
}
setmetatable(scene, mt)
return scene
<file_sep>local lovepad = {_VERSION = "v1.0.0", _TYPE= "module", _NAME = "lovepad", buttons = {}}
local mt = {x = 0, y = 0, radius = 40, text = "button", font = love.graphics.getFont(), fontColor= {1, 1, 1, 1},
normalColor = {1, 0, 0, 1}, pressedColor = {0,1,0,0.5}, mode = "fill",
isDown = false, _lastIsDown = false}
function lovepad:new(o)
o = o or {}
setmetatable(o, {__index = mt})
self.buttons[o.text] = o
end
function lovepad:draw()
for _, button in pairs(self.buttons) do
if button.isDown then
love.graphics.setColor(button.pressedColor)
else
love.graphics.setColor(button.normalColor)
end
love.graphics.circle(button.mode, button.x, button.y, button.radius)
love.graphics.setColor(button.fontColor)
love.graphics.printf(button.text, button.font, button.x - button.radius,
button.y - button.font:getHeight()/2, button.radius * 2, "center")
end
love.graphics.setColor(1, 1, 1, 1)
end
function lovepad:update()
local touches = love.touch.getTouches()
for _, button in pairs(self.buttons) do
button._lastIsDown = button.isDown
button.isDown = false
for _, touch in ipairs(touches) do
local xt, yt = love.touch.getPosition(touch)
if (math.abs((xt - button.x))^2 + math.abs((yt - button.y))^2)^0.5 < button.radius then
button.isDown = true
end
end
end
end
function lovepad:isDown(id)
return self.buttons[id].isDown
end
function lovepad:isPressed(id)
return self.buttons[id].isDown and not self.buttons[id]._lastIsDown
end
function lovepad:isReleased(id)
return not self.buttons[id].isDown and self.buttons[id]._lastIsDown
end
function lovepad:remove(id)
table.remove(self.buttons, id)
end
function lovepad:setGamePad(radius, dir, ab, xy, font)
local width = love.graphics.getWidth()
local height = love.graphics.getHeight()
radius = radius or width/24
dir = dir or true
ab = ab or true
xy = xy or false
font = font or love.graphics.getFont()
if dir then
self:new{
text = 'Down',
radius = radius,
x = radius * 3,
y = height - radius * 1.25,
normalColor = {0.8,0.8,0.8,0.5},
pressedColor = {0.4,0.4,0.4,0.5},
font = font
}
self:new{
text = 'Up',
radius = radius,
x = radius * 3,
y = height - radius * 4.5,
normalColor = {0.8,0.8,0.8,0.5},
pressedColor = {0.4,0.4,0.4,0.5},
font = font
}
self:new{
text = 'Left',
radius = radius,
x = radius * 1.25,
y = height - radius * 2.75,
normalColor = {0.8,0.8,0.8,0.5},
pressedColor = {0.4,0.4,0.4,0.5},
font = font
}
self:new{
text = 'Right',
radius = radius,
x = radius * 4.75,
y = height - radius * 2.75,
normalColor = {0.8,0.8,0.8,0.5},
pressedColor = {0.4,0.4,0.4,0.5},
font = font
}
end
if ab then
self:new{
text = 'A',
radius = radius,
x = width - radius * 1.25,
y = height - radius * 2.75,
normalColor = {0.9,0.1,0.1,0.5},
pressedColor = {0.4,0,0,0.5},
font = font
}
self:new{
text = 'B',
radius = radius,
x = width - radius * 3,
y = height - radius * 1.25,
normalColor = {0,0.9,0,0.5},
pressedColor = {0,0.4,0,0.5},
font = font
}
end
if xy then
self:new{
text = 'X',
radius = radius,
x = width - radius * 3,
y = height - radius * 4.5,
normalColor = {0.9,0.9,0,0.5},
pressedColor = {0.4,0.4,0,0.5},
font = font
}
self:new{
text = 'Y',
radius = radius,
x = width - radius * 4.75,
y = height - radius * 2.75,
normalColor = {0,0,0.9,0.5},
pressedColor = {0,0,0.4,0.5},
font = font
}
end
end
return lovepad
<file_sep># game-tools.scene
Scenes for Lua games.
## How to use
### Require
```lua
scene = require "game-tools.scene"
```
### Create scenes
```lua
-- myScene.lua
local myScene = {}
function myScene.foo()
-- code
end
return myScene
-- myOtherScene.lua
local myOtherScene = {}
function myOtherScene.foo()
-- code
end
return myOtherScene
```
### Set the scene
```lua
-- main.lua
scene = require "game-tools.scene"
scene:setScene("myScene") -- Works with require()
scene.foo()
scene:setScene("myOtherScene")
scene.foo()
```
### Working with Love2D
```lua
-- myScene.lua
local myScene = {}
function myScene.draw()
-- code
end
function myScene.update(dt)
-- code
end
return myScene
-- main.lua
scene = require "game-tools.scene" -- with global you can call scene functions from your scenes
scene:setScene("myScene")
function love.draw()
scene.draw()
end
function love.update(dt)
scene.update(dt)
end
```
### Reload scene
```lua
scene:reload()
```
### Other methods
#### myScene.onLoad()
This method is called once when the scene is loaded.
#### myScene.onExit()
This method is called once when the scene is exited.
<file_sep># game-tools.color
Color tool for Lua.
## How to use
### Require
```lua
local color = require "game-tools.color"
```
### Create a color
```lua
local myColor = color(r,g,b,a) -- values from 0 to 1
```
## Properties
<table>
<tr>
<td>float (0-1)</td>
<td>r</td>
</tr>
<tr>
<td>float (0-1)</td>
<td>g</td>
</tr>
<tr>
<td>float (0-1)</td>
<td>b</td>
</tr>
<tr>
<td>float (0-1)</td>
<td>a</td>
</tr>
</table>
## Create a color
Example:
```lua
local color = require"color"
local red = color(1,0,0) --r,g,b from 0 to 1
local blue = color(0,1,0)
local yellow = red + blue -- blend colors
local aqua = blue + color(0,0,1) -- blue+green
local aquaDarken = aqua * 0.5
print(red) -- prints -> color(1, 0, 0, 1)
local pink = red
pink.g, pink.b = 0.5,0.5
local chocolate = color.hexcode("d2691e")
local purple = color.rgb(128,0,128) --r,g,b from 0 to 255
love.graphics.setBackgroundColor( color.unpack(pink) )
```
## Functions
```lua
color.grayscale(yourColor) -- color()
```
Returns the color's grayscale representation using Weighted method or luminosity method.
```lua
color.unpack(yourColor) -- color()
```
Returns r,g,b,a values of color.
```lua
color.hexcode(yourColor) -- string
```
Returns the color's hexcode, example: "ff0000" (rgb) or "ff000011" (rgba)
```lua
color.rgb(r,g,b) -- values from 0 to 255
```
Returns the color from decimal color code.
```lua
color.rgba(r,g,b,a) -- values from 0 to 255
```
Returns the color from decimal color code with alpha.
## Color Math
### Addition
```lua
this = color(ra,ga,ba) + color(rb,gb,bb) --> vector(ra+rb, ga+gb, ba+bb)
this = color(r,g,b) + a --> vector(r+a, g+a, b+a)
```
### Substraction
```lua
this = color(ra,ga,ba) - color(rb,gb,bb) --> vector(ra-rb, ga-gb, ba-bb)
this = color(r,g,b) - a --> vector(r-a, g-a, b-a)
```
### Multiplication
```lua
this = color(ra,ga,ba) * color(rb,gb,bb) --> vector(ra*rb, ga*gb, ba*bb)
this = color(r,g,b) * a --> vector(r*a, g*a, b*a)
```
### Division
```lua
this = color(ra,ga,ba) / color(rb,gb,bb) --> vector(ra/rb, ga/gb, ba/bb)
this = color(r,g,b) / a --> vector(r/a, g/a, b/a)
```
### Exponetiation
```lua
this = color(r,g,b) ^ a --> vector(r^a, g^a, b^a)
```
### Concatenation
```lua
this = color() .. color() --> "color(1, 1, 1, 1)color(1, 1, 1, 1)"
```
<file_sep>local texturelovepad = {_VERSION = "v0.1.0", _TYPE= "module", _NAME = "texturelovepad", buttons = {}}
local mt = {x = 0, y = 0, width=64, height=64, r=0, sx=1, sy=1, ox=0, oy=0, kx=0, ky=0,
id = "button",isDown = false, _lastIsDown = false, texturePressed=false, textureNormal=false}
function texturelovepad:new(o)
o = o or {}
setmetatable(o, {__index = mt})
self.buttons[o.id] = o
end
function texturelovepad:draw()
for _, button in pairs(self.buttons) do
if button.isDown then
if button.texturePressed then
love.graphics.draw(button.texturePressed,
button.x,
button.y,
button.r,
button.sx,
button.sy,
button.ox,
button.oy,
button.kx,
button.ky)
end
else
if button.textureNormal then
love.graphics.draw(button.textureNormal,
button.x,
button.y,
button.r,
button.sx,
button.sy,
button.ox,
button.oy,
button.kx,
button.ky)
end
end
end
end
function texturelovepad:update()
local touches = love.touch.getTouches()
for _, button in pairs(self.buttons) do
button._lastIsDown = button.isDown
button.isDown = false
for _, touch in ipairs(touches) do
local xt, yt = love.touch.getPosition(touch)
if xt > button.x and xt < button.x + button.width and
yt > button.y and yt < button.y + button.height then
button.isDown = true
end
end
end
end
function texturelovepad:isDown(id)
return self.buttons[id].isDown
end
function texturelovepad:isPressed(id)
return self.buttons[id].isDown and not self.buttons[id]._lastIsDown
end
function texturelovepad:isReleased(id)
return not self.buttons[id].isDown and self.buttons[id]._lastIsDown
end
function texturelovepad:remove(id)
table.remove(self.buttons, id)
end
-- function texturelovepad:setGamePad(radius, dir, ab, xy, font)
-- local width = love.graphics.getWidth()
-- local height = love.graphics.getHeight()
-- radius = radius or width/24
-- dir = dir or true
-- ab = ab or true
-- xy = xy or false
-- font = font or love.graphics.getFont()
-- if dir then
-- self:new{
-- text = 'Down',
-- radius = radius,
-- x = radius * 3,
-- y = height - radius * 1.25,
-- normalColor = {0.8,0.8,0.8,0.5},
-- pressedColor = {0.4,0.4,0.4,0.5},
-- font = font
-- }
-- self:new{
-- text = 'Up',
-- radius = radius,
-- x = radius * 3,
-- y = height - radius * 4.5,
-- normalColor = {0.8,0.8,0.8,0.5},
-- pressedColor = {0.4,0.4,0.4,0.5},
-- font = font
-- }
-- self:new{
-- text = 'Left',
-- radius = radius,
-- x = radius * 1.25,
-- y = height - radius * 2.75,
-- normalColor = {0.8,0.8,0.8,0.5},
-- pressedColor = {0.4,0.4,0.4,0.5},
-- font = font
-- }
-- self:new{
-- text = 'Right',
-- radius = radius,
-- x = radius * 4.75,
-- y = height - radius * 2.75,
-- normalColor = {0.8,0.8,0.8,0.5},
-- pressedColor = {0.4,0.4,0.4,0.5},
-- font = font
-- }
-- end
-- if ab then
-- self:new{
-- text = 'A',
-- radius = radius,
-- x = width - radius * 1.25,
-- y = height - radius * 2.75,
-- normalColor = {0.9,0.1,0.1,0.5},
-- pressedColor = {0.4,0,0,0.5},
-- font = font
-- }
-- self:new{
-- text = 'B',
-- radius = radius,
-- x = width - radius * 3,
-- y = height - radius * 1.25,
-- normalColor = {0,0.9,0,0.5},
-- pressedColor = {0,0.4,0,0.5},
-- font = font
-- }
-- end
-- if xy then
-- self:new{
-- text = 'X',
-- radius = radius,
-- x = width - radius * 3,
-- y = height - radius * 4.5,
-- normalColor = {0.9,0.9,0,0.5},
-- pressedColor = {0.4,0.4,0,0.5},
-- font = font
-- }
-- self:new{
-- text = 'Y',
-- radius = radius,
-- x = width - radius * 4.75,
-- y = height - radius * 2.75,
-- normalColor = {0,0,0.9,0.5},
-- pressedColor = {0,0,0.4,0.5},
-- font = font
-- }
-- end
-- end
return texturelovepad
<file_sep># lovepad
Virtual gamepad for love2d
## How to use
### Require
```lua
local lovepad = require "game-tools.lovepad"
```
## Creating a button
```lua
lovepad:new{
text = "name",
x = 20,
y = 50,
radius = 50,
-- ...
}
```
Note: The button is instanced in `lovepad.buttons`.
## Creating a simple gamepad
```lua
lovepad:setGamePad()
```
## Screenshot example

## Button Properties
| Property | Type |
|-----------|:------:|
| x | number |
| y | number |
| radius | number |
| text | string |
| font | Font |
|fontColor | table {r, g, b, a} |
|normalColor| table {r, g, b, a} |
|pressedColor| table {r, g, b, a} |
| mode | string ("fill" or "line") |
## Functions
```lua
lovepad:draw()
```
Draws the buttons.
```lua
lovepad:update()
```
Updates the buttons.
```lua
lovepad:setGamePad([radius, dirButton, abButton, xyButton, font])
```
Create a simple gamepad.
`radius` [number] sets the button radius.
`dirButton` [boolean] create directional buttons.
`abButton` [boolean] create additional buttons (a, b)
`xyButton` [boolean] create additional buttons (x, y).
`font` [Font] sets the font to text buttons.
```lua
lovepad:isDown(id)
```
Returns `true` if the button `id` (text value) is pressed.
```lua
lovepad:isPressed(id)
```
Returns `true` if the button `id` (text value) is pressed once.
```lua
lovepad:isReleased(id)
```
Returns `true` if the button `id` (text value) is released.
```lua
lovepad:remove(id)
```
Removes the button `id` (text value)
<file_sep>[](https://travis-ci.org/DeybisMelendez/game-tools)
[](LICENSE)
# game-tools
Game tools for Love2D.
## How to use
You can download libraries or use luarocks.
### Install
```$ luarocks install game-tools```
## Libraries
- [Vector 2D](https://github.com/DeybisMelendez/game-tools/blob/master/doc/vector.md)
- [Lovepad - A gamepad for multitouch](https://github.com/DeybisMelendez/game-tools/blob/master/doc/lovepad.md)
- [Texturelovepad - A texture gamepad for multitouch](https://github.com/DeybisMelendez/game-tools/blob/master/doc/texturelovepad.md)
- [Color - Color tool](https://github.com/DeybisMelendez/game-tools/blob/master/doc/color.md)
- [Scene](https://github.com/DeybisMelendez/game-tools/blob/master/doc/scene.md)
<file_sep>local vector = {_VERSION = "v0.8.0", _TYPE = "module", _NAME = "vector"}
local newVectorMt = {
__tostring = function(s)
return "vector(" .. s.x .. ", " .. s.y ..")"
end,
__add = function(a, b)
if type(a) == "number" then return vector(a + b.x, a + b.y)
elseif type(b) == "number" then return vector(a.x + b, a.y + b) end
return vector(a.x + b.x, a.y + b.y)
end,
__sub = function(a, b)
if type(a) == "number" then return vector(a - b.x, a - b.y)
elseif type(b) == "number" then return vector(a.x - b, a.y - b) end
return vector(a.x - b.x, a.y - b.y)
end,
__mul = function(a, b)
if type(a) == "number" then return vector(a * b.x, a * b.y)
elseif type(b) == "number" then return vector(a.x * b, a.y * b) end
return vector(a.x * b.x, a.y * b.y)
end,
__div = function(a, b)
if type(a) == "number" then return vector(a / b.x, a / b.y)
elseif type(b) == "number" then return vector(a.x / b, a.y / b) end
return vector(a.x / b.x, a.y / b.y)
end,
__unm = function(t)
return vector(-t.x, -t.y)
end,
__eq = function(a, b)
return a.x == b.x and a.y == b.y
end,
__pow = function(vec, value)
return vector(vec.x ^ value, vec.y ^ value)
end,
__concat = function(a, b)
if type(a) == "string" then return a .. tostring(b) end
if type(b) == "string" then return tostring(a) .. b end
return tostring(a) .. tostring(b)
end
}
local mt = {
__call = function(_, x, y)
local vec = {x = x or 0, y = y or 0}
setmetatable(vec, newVectorMt)
return vec
end
}
function vector.angle(v)
return math.atan2(v.y, v.x)
end
function vector.normalized(v)
local m = (v.x^2 + v.y^2)^0.5 --magnitude
if v.x/m ~= v.x/m then v.x = 0 else v.x = v.x/m end
if v.y/m ~= v.y/m then v.y = 0 else v.y = v.y/m end
end
function vector.round(v, dec)
dec = dec or 0
local mult = 10^(dec)
local nx, ny
if v.x >= 0 then nx = math.floor(v.x * mult + 0.5) / mult
else nx = math.ceil(v.x * mult - 0.5) / mult end
if v.y >= 0 then ny = math.floor(v.y * mult + 0.5) / mult
else ny = math.ceil(v.y * mult - 0.5) / mult end
v.x, v.y = nx, ny
return v
end
function vector.distanceSquaredTo(s, v)
local x1, y1 = s.x, s.y
local x2, y2 = v.x, v.y
return (x2 - x1)^2 + (y2 - y1)^2
end
function vector.distanceTo(s, v)
return vector.distanceSquaredTo(s, v)^0.5
end
function vector.distanceSquared(v)
return v.x^2 + v.y^2
end
function vector.distance(v)
return (vector.distanceSquared(v))^0.5
end
function vector.dot(s, v)
return s.x * v.x + s.y * v.y
end
function vector.perpDot(s, v)
return s.x * v.x - s.y * v.y
end
function vector.abs(v)
v.x, v.y = math.abs(v.x), math.abs(v.y)
return v
end
function vector.toPolar(v, angle, len)
len = len or 1
v.x, v.y = math.cos(angle) * len, math.sin(angle) * len
return v
end
function vector.rotated(v, phi)
v.x = math.cos(phi) * v.x - math.sin(phi) * v.y
v.y = math.sin(phi) * v.x + math.cos(phi) * v.y
return v
end
function vector.cross(s, v)
return s.x * v.y - s.y * v.x
end
function vector.perpendicular(v)
local px, py = v.x, v.y
v.x, v.y = -py, px
return v
end
function vector.lerp(s, v, t)
local i = 1 - t
s.x, s.y = s.x * i + v.x * t, s.y * i + v.y * t
return s
end
function vector.unpack(v)
return v.x, v.y
end
setmetatable(vector, mt)
vector.DOWN = vector(0, 1)
vector.UP = vector(0, -1)
vector.LEFT = vector(-1, 0)
vector.RIGHT = vector(1, 0)
vector.ZERO = vector(0, 0)
vector.ONE = vector(1, 1)
return vector
| f46fa7ed77716bcc6b83d3d4c15f621affbf758e | [
"Markdown",
"Lua"
] | 12 | Markdown | DeybisMelendez/game-tools | 90690b864e3d3b0ffeec66d04c1956198e383abf | ca3de07da24ffe3cb8366ff99164d5d4c7464ac8 |
refs/heads/master | <repo_name>icefoxz/TestServer<file_sep>/TestPing/Function1.cs
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace TestPing
{
public static class Function1
{
[FunctionName("Time")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var now = DateTimeOffset.UtcNow;
var responseMessage =
"你已经顺利连上服务器了!\n" +
$"当前服务器时间是:{now:F}\n" +
$"本地时间是:{now.ToLocalTime():F}";
return new OkObjectResult(responseMessage);
}
}
}
| b92c6c73b1ad5a37dcb3efcbecb218b24cb542d5 | [
"C#"
] | 1 | C# | icefoxz/TestServer | 343597bde08c83cc5bdfa99c9a3310e3e1dc60ae | 60a5891478d3749901ab53a8148dbe517bb8dbc9 |
refs/heads/master | <repo_name>Albertomanas/Script_VLC_Linux<file_sep>/ScriptsVlc.sh
#!/bin/bash
############################################################################
# #
# MEN<NAME> #
# IMPORTANT: #
# Tots els menús i submenús d'opcions són Vectors. #
# Les opcions de menú han d'esser a l'hora, també Vectors. #
# Excepció 1: excepte la darrera opció de Sortida o Menú Anterior #
# Excepció 2: quan es una opció per l'ejecució #
# #
############################################################################
# DEFINICIÓ DE FUNCIONS, VARIABLES I VECTORS
Principal=('Musica' 'Videos' 'WebCam' 'Sortida');
Musica=('Pop' 'Jazz' 'Rock' 'Reggeton' 'Clàsica' 'Chillout' 'Menú principal')
Pop=('Mecano' 'Radio Futura' 'Pink Floid' 'The Police' 'Menú anterior')
Jazz=('Colosseum' 'Soft Machine' 'Weather Report' 'Menú anterior')
Rock=('The Beatles' 'Queen' 'AC/DC' 'The Rolling Stones' 'Led Zeppelin' 'Menú anterior')
OpcionsMusica=('Escollir cançó' 'Escoltar Al·leatori' 'Menú anterior')
Videos=('Viatges' 'Festes' 'Receptes cuina' 'Excursions' 'Menú principal')
Viatges=('Italia' 'Londres' 'New York' 'Menú anterior')
Festes=('Nit vella' 'Cumples' 'Fi de curs' 'Aniversaris' 'Desfresses' 'Menú anterior')
OpcionsVideos=('Pantalla completa' 'Subtítols' 'Video-Wall' 'Menú anterior')
#Gestió del programa amb tres submenús, més les opcions adients al gènere escollit (Videos o Musica)
#MenuOpcio és un VECTOR
MenuOpcio[0]=0 #contendrà el nombre de l'opció escollida del Menu PRINCIPAL
MenuOpcio[1]=0 # '' '' del SEGON menú
MenuOpcio[2]=0 # '' '' del TERCER menú
CadenaMenus="${MenuOpcio[@]}"
#"CadenaMenus" (string) contendrà en tot moment el número d'opció activa de cada un dels menús (al principi 0 0 0)
# | | |
# opció escollida en el menu Principal --------------------┘ | |
# opció escollida en el SEGON submenú ----------------------┘ |
# opció escollida en el SEGON submenú ------------------------┘
function pause()
{
read -p "Press [Enter] key to continue..." fackEnterKey
}
function escollir()
#Mostra el contingut del directori ($Ruta) i enumera cada sortida, permetent
#a l'usuari escollir el video que vol
{
NumVideo=0 #Serà el número de la llista escollida per l'usuari
echo -e '\n'
echo ' LLISTA DE VIDEOS'
while true
do
local linia=0
IFS=$'\n' #Combatim els espais en blanc dels noms dels arxius
for x in $(ls $Ruta*.mp4 | xargs -d '\n' -n 1 basename) #Mostrarà els arxius del directori
do
linia=$(($linia + 1))
if [ $linia -eq $NumVideo ] #En la segona pasada es comprova que el num. video = linia
then
NomVideo=$x && return #S'agafa el nom de l'arxiu escollit per l'usuari
else
echo ' '$linia") $x"
fi
done
echo -e '\n'
read -p " Indica el número del video: " NumVideo #L'usuari indica el número de video que vol
done
}
function menu()
#Construéix un menú d'opcions i es crida amb dos paràmetres: Nom del menú, i el seu número de opcions
{
Opcio=0
MenuTriat=''
local linia=0
local -n NomArray=$1
clear
echo
echo ---------- MENU $1 ---------- && echo -e '\n'
for i in "${NomArray[@]}" #..per cada valor del vertor
do
linia=$(($linia + 1)) #Incrementa el número de opció
if [ $2 -eq $linia ]; then echo ; fi #Fa una linia en blanc per separar la opció de sortida del menú
echo ' '$linia - $i #Mostra enumerades totes les opcions del menú
done
echo -e '\n'
read -p " Indica una opció: " Opcio #Opcio serà un valor numèric
MenuTriat="${NomArray[$Opcio - 1]}" #Guarda el nom de l'opció de menú escollida
}
function opera()
{
Parametres=''
NomVideo=''
TancaVlc=''
if [ "$SegonMenu" == "Videos" ]
then
TancaVlc=vlc://quit
escollir #Mostra els videos disponibles i permet escollir-ne un
fi
case $Opcio in
1)
if [[ "$SegonMenu" == "Musica" ]]
then
Parametres="--intf dummy --extraintf ncurses" #Opció seleccionar música
else
Parametres="--fullscreen" #Opció de Video escollit en Pantalla completa
fi
;;
2)
if [[ "$SegonMenu" == "Musica" ]]
then
Parametres="--intf dummy --random --play-and-exit" #Opció escoltar música aleatòria
fi
;;
*)
echo "Opció no vàlida"
;;
esac
}
function InitCadena()
#actualitza el vector d'opcions de menú per permetre l'entrada al while adient.
{
MenuOpcio[$1]=$2
CadenaMenus="${MenuOpcio[@]}"
}
# LOGICA DE L'SCRIPT
while [ "${CadenaMenus:0:1}" -lt ${#Principal[@]} ] #MENU PRINCIPAL
#Repetir mentres la opció escollida per l'usuari sigui menor que el NOMBRE TOTAL D'OPCIONS del menú Principal
do
Play=''
menu Principal 4 #crida la funció que crea el menú a partir del nom del verctor que conté les opcions
InitCadena 0 $Opcio
declare -n NumOpSegonMenu="$MenuTriat" #${#NumOpSegonMenu[@]} conté el nombre d'opcions del segon menú
SegonMenu=$MenuTriat
Ruta=$SegonMenu
Play="Opcions$SegonMenu" #Valdrà OpcionsMusica o OpcionsVideos i s'empra per cridar el menú de opcions del gènere
declare -n NumOpMenuPlay="Opcions$SegonMenu"
while [ "${CadenaMenus:2:1}" -lt ${#NumOpSegonMenu[@]} ] #SEGON SUBMENU
do
menu $SegonMenu ${#NumOpSegonMenu[@]}
InitCadena 1 $Opcio
if [ $Opcio -lt ${#NumOpSegonMenu[@]} ]
then
declare -n NumOpTercerMenu="$MenuTriat"
TercerMenu=$MenuTriat
Ruta=$SegonMenu/$TercerMenu
while [ "${CadenaMenus:4:1}" -lt ${#NumOpTercerMenu[@]} ] #TERCER SUBMENU
do
menu $TercerMenu ${#NumOpTercerMenu[@]}
InitCadena 2 $Opcio
if [ $Opcio -lt ${#NumOpTercerMenu[@]} ]
then
Ruta=$SegonMenu/$TercerMenu/$MenuTriat/
menu $Play ${#NumOpMenuPlay[@]} #OPCIONS DEL GÈNERE ESCOLLIT (Musica o Videos)
if [ $Opcio -lt ${#NumOpMenuPlay[@]} ] #Aquest if és per controlar si l'usuari escull "Menú anterior"
then
opera
if [ "$SegonMenu" == "Musica" ]; then clear && echo "reproducció en curs..(CTRL+C per cancelar)"; fi
vlc $Parametres "$Ruta"$NomVideo $TancaVlc 2> /dev/null #CRIDA VLC (NomVideo és null amb Música)
fi
fi
done
InitCadena 2 0 #reseteja Segon Submenu
fi
done
InitCadena 1 0 #reseteja Primer Submenu
done
clear
exit
#https://gulvi.com/serie/curso-programacion-bash/capitulo/arrays-bash
#https://askubuntu.com/questions/674333/how-to-pass-an-array-as-function-argument
#https://unix.stackexchange.com/questions/60584/how-to-use-a-variable-as-part-of-an-array-name
#https://unix.stackexchange.com/questions/281390/how-to-get-the-size-of-an-indirect-array-in-bash
#https://superuser.com/questions/31464/looping-through-ls-results-in-bash-shell-script
#https://wiki.videolan.org/Documentation:Alternative_Interfaces/
#https://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern
#https://stackoverflow.com/questions/8518750/to-show-only-file-name-without-the-entire-directory-path
<file_sep>/README.md
# Script_VLC_Linux
Trabajo VLC en Linux, dicha practica convalida el primer parcial hecho en Sistemas informáticos
| 5c808794fd1660a9174ae0eab95354efec2ab623 | [
"Markdown",
"Shell"
] | 2 | Shell | Albertomanas/Script_VLC_Linux | 194548ae15cdff05cdedb6e6b5724925926b960c | aee7ecf55353ba871d7327ef694268202391383d |
refs/heads/main | <file_sep>(function ($, player) {
function MusicPlayer() {
this.songList = null; //存储数据
this.timer = null; //图片旋转定时器
}
MusicPlayer.prototype = {
/**
* initiate musicPlayer's functions
*/
init() {
this.getDom();
this.getData('../mock/data.json');
},
/**
* get DOM from page
*/
getDom() {
this.record = document.querySelector('.songImg img');
this.controlBtns = document.querySelector('.control').children;
},
/**
* using ajax to get songs data
*/
getData(url) {
$.ajax({
url: url,
method: 'get',
success: (data) => {
this.songList = data; //存储数据
this.indexManager = new player.indexManager(data.length); //实例化索引管理器,需要放在其他功能前面,因为要用到里面的当前歌曲索引值
this.listMusic(); //歌曲列表
this.loadMusic(this.indexManager.defaultIndex); //加载音乐
this.musicControl(); //控制音乐, 绑定点击事件
},
error: () => {
console.log('obtain data failed');
}
});
},
/**
* 加载音乐
*/
loadMusic(index) {
player.render(this.songList[index]); //渲染当前歌曲背景页面
player.music.load(this.songList[index].audioSrc); //根据当前索引加载音乐
},
/**
* 控制音乐,绑定点击事件
*/
musicControl() {
const _this = this;
//上一首
this.controlBtns[1].addEventListener('touchend', () => {
this.controlBtns[2].className = 'playing';
this.loadMusic(this.indexManager.prev());
this.listManager.changeActive(this.indexManager.curIndex);//点击上一首时,联动到列表中,改变样式
player.music.play();
this.imgRotate(0);
});
//控制播放、暂停
this.controlBtns[2].addEventListener('touchend', function () {
if (player.music.status == 'play') { //歌曲正在播放,按下后暂停播放
this.className = '';
player.music.pause();
_this.imgStopRotate();
} else { //歌曲没有播放,按下后开始播放
this.className = 'playing';
player.music.play();
_this.imgRotate(_this.record.dataset.rotate || 0);
}
});
//下一首
this.controlBtns[3].addEventListener('touchend', () => {
this.controlBtns[2].className = 'playing';
this.loadMusic(this.indexManager.next());
this.listManager.changeActive(this.indexManager.curIndex);//点击下一首时,联动到列表中,改变样式
player.music.play();
this.imgRotate(0);
});
},
/**
* 歌曲列表功能
*/
listMusic() {
this.listManager = new player.listManager(this.songList);
this.listManager.renderList(); // 渲染列表
//给每一个歌曲绑定点击事件
this.listManager.list.forEach((ele, index) => {
ele.addEventListener('touchend', () => {
//判断当前点击的歌曲是否是目前正在播放的歌曲
if(index == this.indexManager.curIndex) {
return;
}
this.loadMusic(index);
this.controlBtns[2].className = 'playing';
player.music.play();
this.indexManager.curIndex = index; //当在列表中切换到对应歌曲后,要修改curIndex的值到到当前索引
//点击歌曲播放后隐藏列表
this.listManager.slideDown();
})
});
this.controlBtns[4].addEventListener('touchend', () => {
this.listManager.slideUp();
});
},
/**
* 图片旋转
* @param {*} deg
*/
imgRotate(deg) {
clearInterval(this.timer);
this.timer = setInterval(() => {
deg = +deg + 0.2;
this.record.style.transform = `rotate(${deg}deg)`;
this.record.dataset.rotate = deg; //将旋转的角度保存到标签上,当前歌曲暂停后再次播放,以该值为基础继续旋转
}, 1000 / 60);
},
/**
* 停止图片旋转
*/
imgStopRotate() {
clearInterval(this.timer);
}
}
const musicPlayer = new MusicPlayer();
musicPlayer.init();
})(window.Zepto, window.player)<file_sep># music-player
project developed by gulp
<file_sep>(function (root) {
function Index(len) {
this.defaultIndex = 0; // 页面初始化时索引为0
this.curIndex = 0; // 当前播放歌曲的索引
this.len = len; // 歌曲数组的长度
}
Index.prototype = {
//返回上一首歌曲的索引值
prev() {
return this.getValue(-1);
},
//返回下一首歌曲的索引值
next(){
return this.getValue(1);
},
/**
* 解决边界越界问题
* @param {*} val val为1时,代表下一首;val为-1时,代表上一首
*/
getValue(val) {
this.curIndex = (this.curIndex + val + this.len) % this.len;
return this.curIndex;
}
}
root.indexManager = Index;
})(window.player || (window.player = {}))<file_sep>;(function (root) {
/**
* set background of body using GaussBlur
* set album bg
* @param {*} src
*/
function renderBg(src) {
root.blurImg(src);
const img = document.querySelector('.songImg img');
img.src = src;
}
/**
* render song name, author and album
* @param {*} data
*/
function renderInfo(data) {
const title = document.querySelector('.songInfo h2');
const author = document.querySelector('.songInfo .author');
const album = document.querySelector('.songInfo .album');
title.innerHTML = data.name;
author.innerHTML = data.singer;
album.innerHTML = data.album;
}
/**
* render if current song is liked
* @param {*} isLike
*/
function renderFavorite(isLike) {
const control = document.querySelector('.control').children;
control[0].className = isLike? 'liked' : '';
}
function render(data) {
renderBg(data.image);
renderInfo(data);
renderFavorite(data.isLike);
}
root.render = render;
})(window.player || (window.player = {}))<file_sep>(function (root) {
function ListManager(data) {
this.data = data;
this.list = []; //存储所有歌曲DOM对象
this.songList = document.querySelector('.songList');
this.closeBtn = this.songList.querySelector('.close');
}
ListManager.prototype = {
/**
* 渲染列表内容,并绑定事件
*/
renderList() {
const dt = document.createElement('dt');
const dl = document.querySelector('.songList dl');
dt.innerHTML = '播放列表';
dl.appendChild(dt);
this.data.forEach((ele, index) => {
const dd = document.createElement('dd');
dd.innerHTML = ele.name;
dl.appendChild(dd);
this.list.push(dd);
//给每个dd绑定点击事件,切换选中的状态
dd.addEventListener('touchend', () => {
this.changeActive(index);
})
});
this.changeActive(0); //默认第一首为激活状态
//绑定关闭事件
this.closeBtn.addEventListener('touchend', () => {
this.slideDown();
});
//渲染完成后,把列表向下移动隐藏
this.slideDown();
},
/**
* 点击列表按钮时,显示列表界面
*/
slideUp() {
this.songList.style.transition = `all 0.5s`;
this.songList.style.transform = `translateY(0)`;
},
/**
* 隐藏列表页面
*/
slideDown() {
this.listHeight = this.songList.offsetHeight; //得到当前列表的高度
this.songList.style.transform = `translateY(${this.listHeight}px)`;
},
/**
* 点击后切换选中的状态
*/
changeActive(val) {
for (let i = 0; i < this.list.length; i++) {
this.list[i].className = '';
}
this.list[val].className = 'active';
}
}
root.listManager = ListManager;
})(window.player || (window.player = {})) | ba4464645653630c494e34b7014c77c73dd1df2f | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | uids6779/music-player | fb8c2e4a517a6dd287883a44218c986a0e1b019e | c48984e31ea3d9e9b943875872d31c6dc5d47ee6 |
refs/heads/master | <repo_name>kylinfish/research<file_sep>/dataset.py
import numpy as np
class Bunch(dict):
"""Container object for datasets: dictionary-like object that
exposes its keys as attributes."""
def __init__(self, **kwargs):
dict.__init__(self, kwargs)
self.__dict__ = self
def read_data(filename):
file_feature = open(filename, "r")
define = file_feature.readline().split(", ")
n_samples = int(define[0])
n_features = int(define[1])
target_names = np.array(define[2].split("\n")[0].split("|"))
data = np.empty((n_samples, n_features))
target = np.empty((n_samples,), dtype=np.int)
for i, obj in enumerate(file_feature):
tmp=[]
for fea in obj.split(", ")[:-1]:
tmp.append(fea)
data[i] = np.asarray(fea, dtype=np.float)
target[i] = np.asarray(obj.split(", ")[-1], dtype=np.int)
return Bunch(data=data, target=target,
target_names=target_names,
feature_names=['R (mean)', 'G (mean)','B(mean)'])<file_sep>/compareHist/compareHist.py
import numpy as np
import cv2
import random
# org = []
for x in xrange(1,31):
org.append(x)
images1={}
index1={}
images2={}
index2={}
result=[]
def readImageCalHist(imagePath,ind_dic,img_dic):
# extract the image filename (assumed to be unique) and
# load the image, updating the images dictionary
filename = imagePath[imagePath.rfind("/") + 1:]
image = cv2.imread(imagePath)
img_dic[filename] = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# extract a 3D RGB color histogram from the image,
# using 8 bins per channel, normalize, and update
# the index
hist = cv2.calcHist([image], [0, 1, 2], None, [8, 8, 8],
[0, 256, 0, 256, 0, 256])
hist = cv2.normalize(hist).flatten()
ind_dic[filename] = hist
#======== first class =======#
for i in org:
count = str(i)
if i <10:
count = str(0)+str(i)
im = "/Users/viplab/Documents/dataset/tmp/crocodile/image_00"+count+".jpg"
readImageCalHist(im,index1,images1)
#======== second class =======#
for i in xrange(1,31):
count = str(i)
if i <10:
count = str(0)+str(i)
im = "/Users/viplab/Documents/dataset/tmp/sunflower/image_00"+count+".jpg"
readImageCalHist(im,index2,images2)
#Method: CV_COMP_CORREL , CV_COMP_INTERSECT , CV_COMP_CHISQR
for i in xrange(0,30):
c1 = index1.values()[i]
c2 = index2.values()[i]
d = cv2.compareHist(c1,c2, cv2.cv.CV_COMP_CHISQR )
result.append(d)
totall_d = sum(result)
avg = totall_d / len(result)
print 'result: ',result
print 'totaly',totall_d
print 'avg:' , avg
<file_sep>/main.py
import preprocess as pp
import dataset as dataset
#extract feature and store to txt
pp.Make_feature_set()
flower = dataset.read_data("data/feature.txt")
<file_sep>/preprocess.py
# -*- coding: utf-8 -*-
import numpy as np
import cv2
#path = '../dataset_flower/image_'
path = '/Users/viplab/Documents/dataset/TEST/image_'
number_of_types = 5 #類別種類
type_of_images = 80 #每種類圖片張數
max_size = number_of_types * type_of_images #總共檔案數量
def featureExtraction(name, i):
#Color mean feature :[r,g,b,label]
#50.73430769230769, 90.87095791001451, 97.54420319303338, 1
img = cv2.imread(name)
means = cv2.mean(img)
p = list(means)
layer = (i-1)/type_of_images
p[3]= layer
return (p)
def Make_feature_set(filename,labelStr):
feature_vector=str(max_size)+", "+str(3)+", "+labelStr
for i in range(1, max_size+1):
index= str(i)
if (i< 10):
fullname = path + "000"+ index + ".jpg"
elif (i>=10 and i <100):
fullname = path +"00"+index+".jpg"
elif (i>=100 and i <1000):
fullname = path +"0"+index+".jpg"
else:
fullname = path +index + ".jpg"
feature_vector += "\n"+str(featureExtraction(fullname, i)).split("[")[1].split("]")[0]
file_RW(filename,True,feature_vector)
print "end process of feature collecting "
def file_RW(filename, empty, content):
#empty : empty orgin file before overwrite
if (empty == True):
open(filename,"w").close()
f = open(filename, "r+")
f.write(content)
f.close()
| 166499d30f73acc195c8340f18f36d97031b5363 | [
"Python"
] | 4 | Python | kylinfish/research | 2ff6d3930f0ab0d597297a17279c16b4c767e4af | 8afea01c1d0f64a27665267d7697324b1b67ff15 |
refs/heads/main | <repo_name>Naveen-yennaboina/newone-Repository-1<file_sep>/Bank-Management-System/Bank_Main.py
from colorama import Fore, Style
import mysql.connector as mc
from prettytable import PrettyTable
import datetime
class bankAccount:
mydb = mc.connect(host="localhost", user="root", password="<PASSWORD>", database='Bank_Management_System')
my_cursor = mydb.cursor()
def __init__(self, owner_name, account_number, balance1, m_pin, c_bill_s):
self.Owner_name = owner_name
self.account_number = account_number
self.balance = balance1
self.m_pin = m_pin
self.c_bill_s = c_bill_s
self.mydb = bankAccount.mydb
self.my_cursor = bankAccount.my_cursor
if 1000 > self.balance and self.c_bill_s >= 50:
print(Fore.LIGHTRED_EX + '"------LOW ACCOUNT BALANCE FEE : 200 ------"' + Style.RESET_ALL)
amount = 0
try:
try:
self.my_cursor.execute(' select Bank_Balance from bank_info where IFSC_CODE = "BANK0FT6UTH1"')
my_result = self.my_cursor.fetchone()
for i in my_result:
amount = i
self.mydb.commit()
except Exception as e1:
print(Fore.LIGHTRED_EX + "EXCEPTION : " + Style.RESET_ALL, e1)
quarry = f"update bank_info set Bank_Balance = {amount} + {200} where IFSC_CODE = 'BANK0FT6UTH1'"
quarry1 = f"update user_info set balance = {self.balance} - {200}" \
f" here account = {self.account_number}"
self.my_cursor.execute(quarry)
self.my_cursor.execute(quarry1)
self.mydb.commit()
except Exception as e:
print(Fore.LIGHTRED_EX + "EXCEPTION : " + Style.RESET_ALL, e)
self.mydb.rollback()
else:
self.balance = self.balance - 200
print(Fore.LIGHTBLUE_EX + " Account Balance : " + Style.RESET_ALL, self.balance, '.00')
def tr_history(self):
try:
my_table = PrettyTable(['Date', 'Time', "Description", 'Deposit', 'Money-Transfer', 'Loan-Balance',
'Payed-loan-balance', 'Operation', 'Main-Balance'])
bankAccount.my_cursor.execute(f'select * from {"s" + str(self.account_number)}')
my_result = bankAccount.my_cursor.fetchall()
for i in my_result:
my_table.add_row([i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8]])
except Exception as e:
print(Fore.LIGHTRED_EX + ' Exception : ' + Style.RESET_ALL, e)
else:
print(my_table)
def c_bill_score(self):
try:
self.my_cursor.execute(f'select c_bill from user_info where Account_number = {self.account_number}')
my_result = self.my_cursor.fetchone()
for i in my_result:
print(Fore.LIGHTBLUE_EX + ' Account C-Bill Score : ' + Style.RESET_ALL, i)
except Exception as e:
print(Fore.LIGHTRED_EX + "EXCEPTION : " + Style.RESET_ALL, e)
def check_acc_bal(self):
try:
m_pin = int(input(' enter PIN : '))
if m_pin == self.m_pin:
self.c_bill_s = self.c_bill_s + 2
print(Fore.LIGHTBLUE_EX + ' your Account Balance : ' + Style.RESET_ALL, self.balance, '.00')
else:
print(Fore.LIGHTRED_EX + ' INVALID PIN' + Style.RESET_ALL)
except Exception as e:
print(Fore.LIGHTRED_EX + ' EXCEPTION : ' + Style.RESET_ALL, e)
def deposit(self):
try:
bal = int(input(' enter amount : '))
m_pin = int(input(' enter PIN : '))
if m_pin == self.m_pin:
self.balance = self.balance + bal
try:
quarry = f"update user_info SET balance = {self.balance}" \
f" where Account_number = {self.account_number}"
self.my_cursor.execute(quarry)
self.mydb.commit()
except Exception as e:
self.balance = self.balance - bal
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e, Style.RESET_ALL)
self.mydb.rollback()
else:
self.c_bill_s = self.c_bill_s + 5
print(Fore.LIGHTBLUE_EX + f'Rs.{bal}.00 credited to A/c : {self.account_number}.'
f' total balance : Rs.{self.balance}.00' + Style.RESET_ALL)
t = datetime.datetime.now()
k = 's' + str(self.account_number)
self.my_cursor.execute(
' insert into ' + str(k) + '(Date, Time ,Description, Deposit, Operation,'
' main_balance) values("{}", "{}", "{}", {}, "{}", {})'.format(
t.date(), t.time(),
f"money added to A/c: "
f"{str(self.account_number)}",
bal, "+", self.balance))
self.mydb.commit()
else:
print(Fore.LIGHTRED_EX + ' INVALID PIN ' + Style.RESET_ALL)
except Exception as e:
print(' EXCEPTION : ', e)
def transfer_money(self, var_an, var_name, if_se):
ifsc1 = ''
try:
quarry = f"select balance from user_info where Account_number = {var_an}"
self.my_cursor.execute(quarry)
bal1 = self.my_cursor.fetchone()
for i in bal1:
bal1 = i
self.mydb.commit()
except Exception as e:
self.mydb.rollback()
self.mydb.close()
raise Exception(e)
else:
quarry = f"select balance from user_info where Account_number = {self.account_number}"
self.my_cursor.execute(quarry)
bal = self.my_cursor.fetchone()
for i in bal:
bal = i
if bal > 0:
bal_2 = int(input(' enter amount : '))
m_pin = int(input(' enter PIN : '))
if m_pin == self.m_pin:
if bal_2 <= bal:
try:
self.my_cursor = self.mydb.cursor()
self.my_cursor.execute('select IFSC_CODE from bank_info')
my_result = self.my_cursor.fetchone()
for i in my_result:
ifsc1 = i
if ifsc1 == if_se:
try:
quarry = f"update user_info SET balance = {self.balance} - {bal_2} " \
f"where Account_number = {self.account_number} "
self.my_cursor.execute(quarry)
self.mydb.commit()
try:
quarry1 = f"update user_info SET balance = {bal1} + {bal_2} where" \
f" Account_number = {var_an}"
self.my_cursor.execute(quarry1)
self.mydb.commit()
except Exception as e:
self.mydb.rollback()
self.mydb.close()
raise Exception(e)
except Exception as e:
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e, Style.RESET_ALL)
self.mydb.rollback()
else:
self.balance = self.balance - bal_2
self.my_cursor.execute(f'update user_info SET balance = {self.balance}'
f' where Account_number = {self.account_number}')
self.mydb.commit()
self.c_bill_s = self.c_bill_s + 5
t = datetime.datetime.now()
k = 's' + str(self.account_number)
self.my_cursor.execute(
' insert into ' + str(k) + '(Date, Time ,Description, Money_Tr, Operation,'
' main_balance) values("{}", "{}", "{}", {}, "{}", {})'.format(
t.date(), t.time(),
f"money transfer to A/c: "
f"{str(var_an)}",
bal_2, "-", self.balance))
self.mydb.commit()
print(Fore.LIGHTBLUE_EX + ' TRANSACTION SUCCESSFUL ' + Style.RESET_ALL)
except Exception as e:
self.mydb.close()
raise Exception(e)
else:
print(Fore.LIGHTRED_EX + " INVALID AMOUNT " + Style.RESET_ALL)
else:
print(Fore.LIGHTRED_EX + " INVALID PIN " + Style.RESET_ALL)
<file_sep>/HospitalManagementSystem/Home/src/Health/Health.java
package Health;
import java.util.Scanner;
public class Health
{
public void register()
{
System.out.println("***-------------****----> Enter Patient Details <----****-------------***");
System.out.print("patient name : ");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
System.out.print("\n"+"age : ");
int age = scanner.nextInt();
System.out.print("\n"+"Contact-number : ");
String ph_num = scanner.next();
System.out.print("\n"+"Gender : ");
String sex = scanner.next();
System.out.println("***-------------****----> Treatment Available <----****-------------***\n");
System.out.println("enter 1 ---> Cardiologist <-------> Heart Care");
System.out.println("enter 2 ---> Oncologist <-------> Cancer Care");
System.out.println("enter 3 ---> ENT <-------> Ear, Nose, Throat");
System.out.println("enter 4 ---> Hematologist <-------> Blood (Related)");
System.out.println("enter 5 ---> Infection Disease <-------> All(skin, viruses, malaria, parasites, HIV/AIDS)");
System.out.println("enter 6 ---> Nephrologists <-------> Kidney Care, High BP");
System.out.println("enter 7 ---> Neurologist <-------> Brain and Nervous System");
System.out.println("enter 8 ---> Gynecologist <-------> Women Health");
System.out.println("enter 9 ---> Rheumatologist <-------> Bones, Muscles, Joint-Pains etc... ");
System.out.println("enter 10 --> General Surgeon <-------> Stomach, Liver, Appendix, Thyroid Gland, Gallbladder etc... \n");
System.out.println("***-------------****-------------****---------------****-------------***");
System.out.print("\n"+"Enter Problem : ");
String opt = scanner.next();
String prob = "";
switch (opt) {
case "1" -> prob = "cardiologist";
case "2" -> prob = "oncologist";
case "3" -> prob = "ent";
case "4" -> prob = "hematologist";
case "5" -> prob = "infection - disease";
case "6" -> prob = "nephrologists";
case "7" -> prob = "neurologist";
case "8" -> prob = "gynecologist";
case "9" -> prob = "rheumatologist";
case "10"-> prob = "general-surgeon";
}
HealthHome hh = new HealthHome(name, age, ph_num, sex, prob);
hh.register();
}
}
<file_sep>/HospitalManagementSystem/Home/src/Home/Home.java
package Home;
import Health.Health;
import Job.Job;
import java.util.Scanner;
public class Home
{
public static void main(String[] args) {
System.out.println("\n|***************************************************************************************************|");
System.out.println("|* *|");
System.out.println("|* ***-------****----*----**-- WELCOME NEW HOSPITAL --**----*----****--------*** *|");
System.out.println("|* *|");
System.out.println("|***************************************************************************************************|");
while (true)
{
System.out.println("\n-------------***---------------> HOME <---------------***-----------\n");
System.out.println("Enter - 1 - for Health purpose \n");
System.out.println("Enter - 2 - for Enquiry purpose \n");
System.out.println("Enter - 3 - for Job purpose \n");
System.out.println("Enter - 4 - for Exit\n");
System.out.println("------------**-----------**----------**-----------**----------**---------\n");
Scanner scan = new Scanner(System.in);
System.out.print("Enter your option : ");
String s1 = scan.next();
if(s1.equals("1"))
{
Health h = new Health();
h.register();
}
else if (s1.equals("2"))
{
Enquiry e = new Enquiry();
e.enquiry();
}
else if(s1.equals("3"))
{
Job j = new Job();
j.job();
}
else if(s1.equals("4"))
{
System.out.println("THANK YOU, HAVE A NICE DAY");
System.exit(0);
}
else
{
System.out.println("invalid input");
}
}
}
}
<file_sep>/Bank-Management-System/Main_Code.py
from Bank_code_2 import *
import sys
from colorama import Back
import random
if __name__ == '__main__':
print('', '*' * 100, '\n',
'------------------------------------' + Back.MAGENTA + '"WELCOME TO BANK OF TRUTH"' + Style.RESET_ALL +
'-----------------------------------',
'\n', '*' * 100, '\n')
print('-' * 70)
print(' enter "C" for creating account')
print(' enter "L" for login into account')
print('-' * 70)
create = input(' enter your option : ')
if create in ('L', 'l', 'login', 'Login'):
user_name = input(' E-MAIL : ')
pass1 = input(' PASSWORD : ')
account_number, balance, loan_bal, m_pin, c_bill, ph_num, ad_num, age = 0, 0, 0, 0, 0, 0, 0, 0
name, e_mail, pc_num, password = '', '', '', ''
try:
bankAccount.my_cursor.execute(f'select * from user_info where e_mail = "{user_name}" and pass = {<PASSWORD>};')
my_result = bankAccount.my_cursor.fetchall()
for i in my_result:
account_number = i[0]
name = i[1]
age = i[2]
e_mail = i[3]
password = i[4]
ph_num = i[5]
ad_num = i[6]
pc_num = i[7]
balance = i[8]
loan_bal = i[9]
m_pin = i[10]
c_bill = i[11]
if account_number == 0 and age == 0 and ph_num == 0 and m_pin == 0 and ad_num == 0:
raise Exception(' INVALID E-MAIL OR PASSWORD')
except Exception:
raise Exception(' INVALID PASSWORD OR E-MAIL')
else:
account1 = use(name, age, e_mail, ph_num, ad_num, pc_num, password, account_number, balance, loan_bal,
m_pin, c_bill)
account1.display2()
elif create in ('create', 'Create', 'c', 'C'): # ----------creating account
while True:
print(Fore.CYAN + ' CREATE BANK ACCOUNT' + Style.RESET_ALL)
# name ----------------------------------------------------- Name
name = input(' enter name : ')
# age------------------------------------------------------- Age
try:
ag = int(input(' enter age : '))
except ValueError as e:
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e, Style.RESET_ALL)
try:
ag = int(input(' enter age : '))
except ValueError as e1:
raise ValueError(' INVALID INFO')
# E-mail-----------------------------------------------------E-mail
email = input(' enter E-Mail : ')
for i1 in range(len(email)):
if '@' == email[i1]:
break
else:
sys.exit(' invalid e_mail')
# phone number -------------------------------------------- phone number
ph_num = 0
try:
ph_num = int(input(' enter Phone Number : '))
except ValueError as e:
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e, Style.RESET_ALL)
try:
ph_num = int(input(' enter Phone Number : '))
except ValueError as e1:
raise ValueError(' INVALID INFO')
count = 0
for i in range(0, 3):
if ph_num in range(6000000000, 9999999999):
print(Fore.LIGHTBLUE_EX + f' {ph_num} VALIDATED SUCCESSFULLY')
print(' OTP SENT SUCCESSFULLY' + Style.RESET_ALL)
break
elif count <= 2:
print(Fore.LIGHTRED_EX + ' INVALID PHONE NUMBER' + Style.RESET_ALL)
ph_num = int(input(' enter valid phone number : '))
count = count + 1
elif count == 3:
sys.exit(' REACHED THE LIMIT, TRY AGAIN LATER')
# OTP -----------------------------------------------------OTP
otp1 = random.randint(00000, 99999)
print("-" * 60)
print(Fore.GREEN + ' MESSAGE : THIS IS ONE TIME PASSWORD ----" ' + Style.RESET_ALL, otp1,
Fore.GREEN + ' "---- DO NOT SHARE WITH ANY ONE. ' + Style.RESET_ALL)
print("-" * 60)
otp = 0
try:
otp = int(input(' enter OTP : '))
except ValueError as e:
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e, Style.RESET_ALL)
try:
otp = int(input(' enter OTP : '))
except ValueError as e1:
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e1, Style.RESET_ALL)
count = 0
for i in range(0, 3):
if otp1 == otp:
print(Fore.LIGHTBLUE_EX + ' OTP VALIDATED SUCCESSFULLY' + Style.RESET_ALL)
break
elif count <= 2:
print(Fore.LIGHTRED_EX + ' INVALID OTP' + Style.RESET_ALL)
otp = int(input(' enter correct OTP : '))
count = count + 1
elif count == 3:
sys.exit(' REACHED THE LIMIT, TRY AGAIN LATER')
print("-" * 60)
print(Fore.GREEN + ' MESSAGE : MAKE SURE AADHER MUST BE CONNECTED WITH PHONE NUMBER' + Style.RESET_ALL)
print("-" * 60)
# addhar number----------------------------------Aadher Number
ad_num = 0
try:
ad_num = int(input(' enter Aadher Number : '))
except ValueError as e:
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e, Style.RESET_ALL)
try:
ad_num = int(input(' enter Valid Aadher Number : '))
except ValueError as e1:
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e1, Style.RESET_ALL)
count = 0
for i in range(0, 3):
if ad_num in range(100000000000, 999999999999):
break
elif count <= 2:
print(Fore.LIGHTRED_EX + ' INVALID AADHER NUMBER' + Style.RESET_ALL)
ad_num = int(input(' enter Valid Aadher number : '))
count = count + 1
continue
elif count == 3:
sys.exit(' -------------> REACHED THE LIMIT, TRY AGAIN LATER <-------------')
# pan-cord number --------------------------------------PAN-CORD NUMBER
pan_num = input(' enter PAN-CARD Number : ')
count = 1
for i in range(0, 3):
if len(pan_num) == 10:
print(Fore.LIGHTBLUE_EX + f' {pan_num} VALIDATED SUCCESSFULLY' + Style.RESET_ALL)
break
elif count <= 2:
print(Fore.LIGHTRED_EX + ' INVALID PAN_CORD NUMBER' + Style.RESET_ALL)
pan_num = input(' enter Valid PAN-CARD Number : ')
count = count + 1
elif count == 3:
sys.exit(' REACHED THE LIMIT, TRY AGAIN LATER')
# password --------------------------------------------- PASSWORD
pss = input(' create password : ')
pss2 = input(' conform password : ')
count = 0
for i in range(0, 3):
if pss == pss2:
break
elif count <= 2:
print(Fore.LIGHTRED_EX + ' INVALID PASSWORD' + Style.RESET_ALL)
pss2 = input(' conform password : ')
count = count + 1
elif count == 3:
sys.exit(' -----------> REACHED THE LIMIT, TRY AGAIN LATER <-------------')
# conform account creation
conf = input(' conform account creation : ')
if conf in ('Yes', 'yes', 'YES', 'Y', 'y', 'OK', 'ok'):
balance = 0.00
loan_bal = 0.00
account_num = 0
c_bill = 0
# create m-pin----------------------------- M-PIN
m_pin = int(input(' create M-PIN : '))
m_pin1 = int(input(' conform M-PIN : '))
count = 0
for i in range(0, 3):
if m_pin == m_pin1:
break
elif count <= 2:
print(Fore.LIGHTRED_EX + " INVALID M-PIN " + Style.RESET_ALL)
m_pin1 = int(input(' conform M-PIN : '))
count += 1
elif count == 3:
sys.exit(' -------------- TRY AGAIN LATER --------------')
print('*' * 90)
account1 = use(name, ag, email, ph_num, ad_num, pan_num, pss2, account_num, balance, loan_bal, m_pin1,
c_bill)
account1.display()
break
else:
sys.exit(' INVALID ENTRY ')
def person2():
for q in range(0, 3):
while True:
j = 1
for g in range(j):
print('*' * 90)
print(Fore.BLUE + ' ------------------- HELLO', name.upper(),
' ------------------' + Style.RESET_ALL)
print(f'|----------------| |------------------|\n'
f'| 1. Deposit | | 6.Loan Balance |\n'
f'|----------------| |------------------|\n'
f' \n'
f'|----------------| |------------------|\n'
f'|2.Money Transfer| | 7. pay Loan |\n'
f'|----------------| |------------------|\n'
f' \n'
f'|------- -------| |------------------|\n'
f'| 3.Balance | | 8. C-Bill Score |\n'
f'|------ --------| |------------------|\n'
f' \n'
f'|----------------| |------------------|\n'
f'| 4.Account_info | | 9. Security |\n'
f'|----------------| |------------------|\n'
f' \n'
f'|----------------| |------------------|\n'
f'| 5.Bank Loan | | 10. Exit |\n'
f'|----------------| |------------------|\n'
f'|---------------------------------------------------|\n'
f'| 11. Transaction History |\n'
f'|---------------------------------------------------|')
print('*' * 90)
opt = input(' enter your option : ')
if opt == '1': # adding money
try:
print(Fore.LIGHTCYAN_EX + ' PROCESSING......' + Style.RESET_ALL)
account1.deposit()
account1.update()
except Exception as e3:
print(Fore.LIGHTRED_EX + ' Please Enter Valid Information : ' + Style.RESET_ALL, e3)
elif opt == '2': # money transfer
try:
var1 = int(input(' Account-Number : '))
var11 = int(input(' Re-enter Account_Number : '))
var2 = input(' Account-Holder name : ')
var3 = input(' IFSC-CODE : ')
if var1 == var11:
print(Fore.LIGHTCYAN_EX + ' PROCESSING......' + Style.RESET_ALL)
account1.transfer_money(var11, var2, var3)
account1.update()
except Exception as e3:
print(Fore.LIGHTRED_EX + ' Please Enter Valid Information : ' + Style.RESET_ALL, e3)
elif opt == '3': # checking account balance
account1.check_acc_bal()
elif opt == '4':
print(Fore.LIGHTCYAN_EX + ' PROCESSING......' + Style.RESET_ALL)
account1.display2()
elif opt == '5': # applying bank loan
try:
bal = int(input(' enter amount for loan : '))
tim = int(input(' enter time in days : '))
account1.bank_loan(bal)
account1.update()
except Exception as e2:
print(Fore.LIGHTRED_EX + ' Please Enter Valid Information : ' + Style.RESET_ALL, e2)
elif opt == '6': # checking loan balance
account1.loan_balance()
elif opt == '7': # paying loan balance
try:
account1.pay_loan()
account1.update()
except Exception as e3:
print(Fore.LIGHTRED_EX + ' Please Enter Valid Information : ' + Style.RESET_ALL, e3)
elif opt == '8': # checking c_bill score
account1.c_bill_score()
elif opt == '9': # security option
account1.edit_option()
account1.update()
elif opt == '10': # exit
bankAccount.mydb.close()
sys.exit(' "------------> THANK YOU, HAVE A NICE DAY <------------"')
elif opt == '11': # transaction history
print(Fore.LIGHTRED_EX + ('*' * 110) + Style.RESET_ALL)
account1.tr_history()
print(Fore.LIGHTRED_EX + ('*' * 110) + Style.RESET_ALL)
else:
print(Fore.LIGHTRED_EX + ' INVALID OPTION' + Style.RESET_ALL)
print(' -------*--------*--------*--------')
opt1 = input(' do you want to continue : ')
for v in range(0, 3):
if opt1 in ('yes', 'YES', 'Yes', 'Y', 'y', 'OK', 'Ok', 'ok'):
j = j + 1
break
elif opt1 in ('no', 'No', 'N', 'n', 'NO'):
bankAccount.mydb.close()
sys.exit(' "------------>THANK YOU , VISIT AGAIN<------------"')
elif v <= 3:
print(Fore.LIGHTRED_EX + ' INVALID OPTION , TRY AGAIN' + Style.RESET_ALL)
opt1 = input(' do you want to continue : ')
v += 1
else:
sys.exit(' "------------>THANK YOU , VISIT AGAIN<------------"')
person2()
<file_sep>/HospitalManagementSystem/Home/src/Job/Register.java
package Job;
import DBconnect.DBconnect;
import java.util.Scanner;
public class Register
{
String dr_name, ph_num, email, position, college;
int age, count, exp;
public Register(String position, String name, int age, String ph_num, String email, int count)
{
this.dr_name = name;
this.age = age;
this.ph_num = ph_num;
this.email = email;
this.count = count;
this.position = position;
}
public void register()
{
Scanner scanner = new Scanner(System.in);
System.out.println("***-------------***----> enter Experience Details <----***-------------***");
System.out.print("company name : ");
String c_name = scanner.next();
System.out.print("\n"+"Experience : ");
exp = scanner.nextInt();
if (exp != 0)
{
this.count = this.count + 5;
}
System.out.print("\n"+"Specialization : ");
String position = scanner.next();
if (!position.equals(" "))
{
this.count = this.count + 1;
}
System.out.println("***-------------***----> Hello "+this.dr_name+" enter Educational Details <----***-------------***");
System.out.print("College Name : ");
String col = scanner.next();
college = col.replace(" ", "_");
System.out.print("\n"+"enter degree : ");
String degree = scanner.next();
if (!degree.equals(""))
{
this.count = this.count + 1;
}
System.out.print("\n"+"enter CGPA or Percentage : ");
int cgpa = scanner.nextInt();
if (cgpa != 0)
{
this.count = this.count + 1;
}
conform();
}
public void conform()
{
if (this.count == 18)
{
try {
System.out.println("\nwe are processing your request.....\n");
int salary = 25000;
String quarry = "insert into doctor_data" + "(name, age, email, phone, specialist, experiance, college, patient_count)" + "values('"+this.dr_name+"','"
+this.age+"','"+this.email+"','"+this.ph_num+"','"+this.position +"','"+exp+"','"+college+"','"+0+"')";
DBconnect db = new DBconnect();
db.insert(quarry);
System.out.println("***-------**--> your selected <--**-------*** ");
} catch (Exception e)
{
System.out.println("something went wrong");
}
}
else
{
System.out.println("Sorry your not selected");
System.out.println("we hope you will got placed sooner");
}
}
}
<file_sep>/Bank-Management-System/Bank_code_2.py
from Bank_Main import *
import sys
import random
import mysql.connector as mc
class use(bankAccount):
def __init__(self, owner_name, age, g_mail, ph_num1, ad_num1, pc_num, password, account_number, balance1, loan_bal,
m_pin, c_bill_s):
super().__init__(owner_name, account_number, balance1, m_pin, c_bill_s)
self.age = age
self.g_mail = g_mail
self.ph_num = ph_num1
self.ad_num = ad_num1
self.pc_num = pc_num
self.password = <PASSWORD>
self.loan_bal = loan_bal
def loan_balance(self):
self.my_cursor.execute(f'select loan_bal from user_info where Account_number = {self.account_number}')
my_result = self.my_cursor.fetchone()
for i in my_result:
print(Fore.LIGHTBLUE_EX + ' Loan Balance : ' + Style.RESET_ALL, i,'.00')
def update(self):
try:
self.my_cursor.execute(
f'update user_info SET balance = {self.balance} where Account_number = {self.account_number}')
self.my_cursor.execute(
f'update user_info SET loan_bal = {self.loan_bal} where Account_number = {self.account_number}')
self.my_cursor.execute(
f'update user_info SET c_bill = {self.c_bill_s} where Account_number = {self.account_number}')
self.mydb.commit()
except Exception as e:
self.mydb.rollback()
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e, Style.RESET_ALL)
def display(self):
if self.c_bill_s < 15:
self.c_bill_s+= 10
try:
mydb = mc.connect(host="localhost", user="root", password="<PASSWORD>", database='Bank_Management_System')
my_cursor = mydb.cursor()
quarry = 'insert into user_info(name, age, e_mail, pass, ph_num, ad_num, pc_num,' \
' balance, loan_bal, m_pin, c_bill) ' \
'values("{}",{}, "{}", "{}", {}, {}, "{}", {}, {}, {}, {})'.format(self.Owner_name, self.age,
self.g_mail, self.password,
self.ph_num, self.ad_num,
self.pc_num, self.balance,
self.loan_bal, self.m_pin,
self.c_bill_s)
my_cursor.execute(quarry)
mydb.commit()
except Exception as e:
print(' create account again')
raise Exception(e)
else:
try:
mydb = mc.connect(host="localhost", user="root", password="<PASSWORD>",
database='Bank_Management_System')
my_cursor = mydb.cursor()
my_cursor.execute(f'select Account_number from user_info where e_mail = "{self.g_mail}"')
my_result = my_cursor.fetchone()
for i in my_result:
self.account_number = i
mydb.commit()
my_cursor.execute(
f'update bank_info set Account_num_c = {self.account_number} where IFSC_CODE = "BANK0FT6UTH1"')
except Exception as e:
raise Exception(' Something Wrong :', e)
else:
mydb = mc.connect(host="localhost", user="root", password="<PASSWORD>",
database='Bank_Transaction_History')
mycurser = mydb.cursor()
k = 's'+ str(self.account_number)
mycurser.execute(
f'create table {str(k)}(Date varchar(30), Time varchar(30),'
f' Description varchar(100), Deposit int(30), Money_Tr int(30), loan_bal int(30),'
f' payed_loan_bal int(30), Operation varchar(30), main_balance Bigint(30))')
print(Fore.BLUE + 'Your Account Successfully Created' + Style.RESET_ALL)
print(f' Name : {self.Owner_name}\n'
f' E-Mail : {self.g_mail}\n'
f' Age : {self.age}\n'
f' Phone-Number : {self.ph_num}\n'
f' Account-Number : {self.account_number}\n'
f' Balance : {self.balance}.00')
else:
raise Exception(' Something Wrong')
def display2(self):
m_pin = int(input(' enter PIN : '))
if m_pin == self.m_pin:
print("*" * 90)
try:
self.my_cursor.execute(f'select * from user_info where Account_number = {self.account_number}'
f' and e_mail = "{self.g_mail}";')
my_result = self.my_cursor.fetchall()
for i in my_result:
self.account_number = i[0]
self.Owner_name = i[1]
self.age = i[2]
self.g_mail = i[3]
self.password = i[4]
self.ph_num = i[5]
self.ad_num = i[6]
self.pc_num = i[7]
self.balance = i[8]
self.loan_bal = i[9]
self.m_pin = i[10]
self.c_bill_s = i[11]
self.mydb.commit()
except Exception as e:
raise Exception(e)
else:
print(Fore.LIGHTBLUE_EX + ' ------------ ACCOUNT INFORMATION -------------' + Style.RESET_ALL)
print(f' Name : {self.Owner_name}\n'
f' E-Mail : {self.g_mail}\n'
f' Age : {self.age}\n'
f' Phone-Number : {self.ph_num}\n'
f' Account-Number : {self.account_number}\n'
f' Balance : {self.balance}.00\n'
f' IFSE-CODE : BANK0FT6UTH1')
else:
print(Fore.LIGHTRED_EX+' INVALID PIN'+Style.RESET_ALL)
def bank_loan(self, var):
if self.c_bill_s >= 50:
m_pin = int(input(' enter PIN : '))
if m_pin == self.m_pin:
self.c_bill_s = self.c_bill_s + 5
self.balance = self.balance + var
self.loan_bal = self.loan_bal + var
amount = 0
try:
try:
self.my_cursor.execute(' select BanK_Balance from bank_info where IFSC_CODE = "BANK0FT6UTH1"')
my_result = self.my_cursor.fetchone()
for i in my_result:
amount = i
self.mydb.commit()
except Exception as e:
self.mydb.rollback()
print(Fore.LIGHTRED_EX + ' EXCEPTION : ' + Style.RESET_ALL, e)
self.my_cursor.execute(
f'update bank_info set Bank_Balance = {amount} - {var} where IFSC_CODE = "BANK0FT6UTH1"')
self.mydb.commit()
except Exception as e:
self.mydb.rollback()
print(Fore.LIGHTRED_EX + ' EXCEPTION : ' + Style.RESET_ALL, e)
else:
t = datetime.datetime.now()
k = 's' + str(self.account_number)
self.my_cursor1.execute(
' insert into ' + str(k) + '(Date, Time ,Description, loan_bal, Operation,'
' main_balance) values("{}", "{}", "{}", {}, "{}", {})'.format(
t.date(), t.time(),
f"bank loan approved for A/c: "
f"{str(self.account_number)}",
var, "+", self.balance))
self.mydb1.commit()
print(Fore.LIGHTBLUE_EX + " Account Balance : " + Style.RESET_ALL, self.balance, '.00')
else:
print(Fore.LIGHTRED_EX+' INVALID PIN'+Style.RESET_ALL)
else:
print(Fore.YELLOW + ' your C-Bill is less, so you not eligible for loan' + Style.RESET_ALL)
def pay_loan(self):
if self.loan_bal > 0:
m_pin = int(input(' enter PIN : '))
if m_pin == self.m_pin:
print(Fore.LIGHTBLUE_EX + ' YOUR LOAN BALANCE : ' + Style.RESET_ALL, self.loan_bal)
var = int(input(' enter amount : '))
if self.loan_bal >= var:
self.c_bill_s += 5
self.loan_bal -= var
amount = 0
try:
try:
self.my_cursor.execute(
' select BanK_Balance from bank_info where IFSC_CODE = "BANK0FT6UTH1"')
my_result = self.my_cursor.fetchone()
for i in my_result:
amount = i
except Exception as e:
print(Fore.LIGHTRED_EX + ' EXCEPTION : ' + Style.RESET_ALL, e)
self.my_cursor.execute(
f'update bank_info set Bank_Balance = {amount} + {var} where IFSC_CODE = "BANK0FT6UTH1"')
self.mydb.commit()
except Exception as e:
self.mydb.rollback()
print(Fore.LIGHTRED_EX + ' EXCEPTION : ' + Style.RESET_ALL, e)
else:
print(Fore.LIGHTBLUE_EX + ' LOAN PAYMENT SUCCESSFUL ' + Style.RESET_ALL)
t = datetime.datetime.now()
self.my_cursor1.execute(
f' update "{"s"+str(self.account_number)}" SET Date = {t.date()}, SET Time = {t.time()}'
f'SET Description = "loan-balance payed to A/c: {self.account_number}", SET payed_loan_bal = {var},'
f'SET Operation = " ", SET main_balance = {self.balance} ')
k = 's' + str(self.account_number)
self.my_cursor1.execute(
' insert into ' + str(k) + '(Date, Time ,Description, Money_Tr, Operation,'
' main_balance) values("{}", "{}", "{}", {}, "{}", {})'.format(
t.date(), t.time(),
f"loan-balance payed for A/c: "
f"{str(self.account_number)}",
var, " ", self.balance))
self.mydb1.commit()
self.mydb1.commit()
print(Fore.LIGHTBLUE_EX + ' Account Balance : ' + Style.RESET_ALL, self.balance, '.00')
print(Fore.LIGHTBLUE_EX + ' Loan Balance : ' + Style.RESET_ALL, self.loan_bal, '.00')
else:
print(Fore.LIGHTYELLOW_EX + ' INVALID AMOUNT' + Style.RESET_ALL)
else:
print(Fore.LIGHTRED_EX+' INVALID PIN'+Style.RESET_ALL)
elif self.loan_bal == 0:
print(Fore.LIGHTRED_EX + ' YOU HAVE NO LOAN BALANCE' + Style.RESET_ALL)
def edit_option(self):
for i4 in range(0, 10):
print('*' * 90)
print(Fore.BLUE, '-------------------SECURITY PORTAL--------------------', Style.RESET_ALL)
print(f'|----------------------| |-----------------------|\n'
f'| 1. Edit E-Mail | | 2. Edit Phone-Number |\n'
f'|----------------------| |-----------------------|\n'
f' \n'
f'|----------------------| |-----------------------|\n'
f'| 3. Edit Account PIN | | 4. Edit password |\n'
f'|----------------------| |-----------------------|\n'
f' \n'
f'|----------------------| |-----------------------|\n'
f'| 5. Home Page | | 6. Delete Account |\n'
f'|----------------------| |-----------------------|\n')
print('*' * 90)
opt = input(" enter your option : ")
# Edit E-MAIL
if opt == '1':
pass_word = input(' enter password : ')
if self.password == pass_word:
new_g_mail = str(input(' enter New E-Mail : '))
for i1 in range(len(new_g_mail)):
if '@' == new_g_mail[i1]:
break
else:
print(Fore.LIGHTRED_EX+' INVALID E-MAIL'+Style.RESET_ALL)
break
self.g_mail = new_g_mail
try:
quarry = f'update user_info SET e_mail ="{self.g_mail}" where Account_number ={self.account_number} '
self.my_cursor.execute(quarry)
self.mydb.commit()
except Exception as e:
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e, Style.RESET_ALL)
self.mydb.rollback()
print(' new E-Mail : ', self.g_mail)
else:
print(Fore.LIGHTRED_EX + ' invalid password, try again later' + Style.RESET_ALL)
# Edit Phone-Number
elif opt == '2':
for i3 in range(1):
old_phn = int(input(' enter Phone-Number : '))
if self.ph_num == old_phn:
otp2 = random.randint(00000, 99999)
print(Fore.LIGHTBLUE_EX + ' OTP SENT SUCCESSFULLY' + Style.RESET_ALL)
print('-' * 60)
print(Fore.GREEN + ' MESSAGE : THIS IS ONE TIME PASSWORD ' + Style.RESET_ALL, otp2, Fore.GREEN +
' DO NOT SHARE WITH ANY ONE' + Style.RESET_ALL)
print('-' * 60)
otp3 = int(input(' enter OTP : '))
if otp2 == otp3:
new_num = int(input(' enter New Phone Number : '))
if new_num == self.ph_num:
count1 = 0
for i2 in range(0, 3):
if new_num in range(6000000000, 9999999999):
print(Fore.LIGHTBLUE_EX + f' {new_num} VALIDATED SUCCESSFULLY')
print(' OTP SENT SUCCESSFULLY' + Style.RESET_ALL)
break
elif count1 <= 2:
print(Fore.LIGHTRED_EX + ' INVALID PHONE NUMBER' + Style.RESET_ALL)
new_num = int(input(' enter correct phone number : '))
count1 = count1 + 1
elif count1 == 3:
print(
Fore.LIGHTRED_EX + ' REACHED THE LIMIT, TRY AGAIN LATER' + Style.RESET_ALL)
otp11 = random.randint(00000, 99999)
print("-" * 60)
print(Fore.GREEN + ' MESSAGE : THIS IS ONE TIME PASSWORD ----" ' + Style.RESET_ALL,
otp11,
Fore.GREEN + ' "---- DO NOT SHARE WITH ANY ONE. ' + Style.RESET_ALL)
print("-" * 60)
otp22 = int(input(' enter OPT : '))
count1 = 0
for i11 in range(0, 3):
if otp11 == otp22:
print(Fore.LIGHTBLUE_EX + ' OTP VALIDATED SUCCESSFULLY' + Style.RESET_ALL)
self.ph_num = new_num
try:
quarry = f"update user_info SET ph_num ={new_num} where Account_number" \
f" = {self.account_number} "
self.my_cursor.execute(quarry)
self.mydb.commit()
except Exception as e:
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e, Style.RESET_ALL)
self.mydb.rollback()
print(' Phone Number updated Successfully : ', self.ph_num)
break
elif count1 <= 2:
print(Fore.LIGHTRED_EX + ' INVALID OTP' + Style.RESET_ALL)
otp22 = int(input(' enter correct OTP : '))
count1 = count1 + 1
elif count1 == 3:
print(
Fore.LIGHTRED_EX + ' REACHED THE LIMIT, TRY AGAIN LATER' + Style.RESET_ALL)
break
else:
print(Fore.LIGHTRED_EX+' PLEASE ENTER NEW PHONE-NUMBER '+Style.RESET_ALL)
break
else:
print(Fore.LIGHTRED_EX + ' INVALID OTP, TRY AGAIN LATER' + Style.RESET_ALL)
break
else:
print(Fore.LIGHTRED_EX + ' INVALID PHONE-NUMBER, TRY AGAIN LATER' + Style.RESET_ALL)
break
# Edit M-PIN
elif opt == '3':
o_pin = int(input(' enter current PIN : '))
if self.m_pin == o_pin:
pin1 = int(input(' enter New PIN : '))
count1 = 0
for i2 in range(0, 3):
if pin1 in range(0000, 9999):
break
elif count1 <= 2:
print(Fore.LIGHTRED_EX + ' PIN NUMBER MUST BE WITH IN 4 DIGITS RANGE' + Style.RESET_ALL)
pin1 = int(input(' enter valid PIN : '))
count1 = count1 + 1
elif count1 == 3:
print(Fore.LIGHTRED_EX + ' REACHED THE LIMIT, TRY AGAIN LATER' + Style.RESET_ALL)
break
pin2 = int(input(' conform PIN : '))
for i11 in range(0, 3):
if pin1 == pin2:
print(' PIN Created Successfully ')
print('*' * 90)
self.m_pin = pin2
self.my_cursor.execute(f'update user_info SET m_pin = {self.m_pin}'
f' where Account_number = {self.account_number}')
self.mydb.commit()
break
elif count1 <= 2:
print(Fore.LIGHTRED_EX + ' INVALID PIn' + Style.RESET_ALL)
pin2 = int(input(' enter Valid PIN : '))
count1 = count1 + 1
elif count1 == 3:
print(Fore.LIGHTRED_EX + ' REACHED THE LIMIT, TRY AGAIN LATER' + Style.RESET_ALL)
break
else:
print(Fore.LIGHTRED_EX + ' INVALID PIN, TRY AGAIN LATER' + Style.RESET_ALL)
break
elif opt == '4':
if True:
o2 = random.randint(00000, 99999)
print('-' * 80)
print(Fore.GREEN + ' MESSAGE : THIS IS ONE TIME PASSWORD ----" ' + Style.RESET_ALL, o2,
Fore.GREEN + ' "---- DO NOT SHARE WITH ANY ONE. ' + Style.RESET_ALL)
print('-' * 80)
o3 = int(input(' enter otp :'))
count = 0
for i in range(0, 3):
if o2 == o3:
print(Fore.LIGHTBLUE_EX + ' OTP VALIDATED SUCCESSFULLY' + Style.RESET_ALL)
new_pss = input(' enter new Password : ')
new_pss1 = input(' conform new password : ')
for i1 in range(0, 3):
if new_pss == new_pss1:
self.password = <PASSWORD>
try:
quarry = f"update user_info SET pass ={<PASSWORD>} where Account_number = " \
f"{self.account_number} "
self.my_cursor.execute(quarry)
self.mydb.commit()
except Exception as e:
print(Fore.LIGHTRED_EX, "EXCEPTION : ", e, Style.RESET_ALL)
self.mydb.rollback()
print(Fore.LIGHTBLUE_EX + ' Password updated successfully' + Style.RESET_ALL)
elif i1 <= 2:
print(Fore.LIGHTRED_EX + ' INVALID PASSWORD' + Style.RESET_ALL)
new_pss1 = input(' conform new password : ')
else:
sys.exit(' REACHED THE LIMIT, TRY AGAIN LATER')
break
elif count <= 2:
print(Fore.LIGHTRED_EX + ' INVALID OTP' + Style.RESET_ALL)
o3 = int(input(' enter correct OTP : '))
count = count + 1
elif count == 3:
sys.exit(' REACHED THE LIMIT, TRY AGAIN LATER')
elif opt == '5':
break
elif opt == '6':
m_pin = int(input(' enter PIN : '))
if m_pin == self.m_pin:
paa = input(' enter your password : ')
if self.password == paa:
print(Fore.LIGHTBLUE_EX+" NOTE : once account is deleted, you can't get anything back "+Style.RESET_ALL)
if self.balance > 0:
print(Fore.LIGHTRED_EX + " NOTE : Please Withdrawal the money " + Style.RESET_ALL)
print(f' Your Account Balance : {self.balance}')
print(Fore.LIGHTBLUE_EX + ' Note : say yes or no ' + Style.RESET_ALL)
i4 = input(' Conform : ')
if i4 in ('yes', 'ok', 'OK', 'Ok', 'YES', 'Yes'):
try:
quarry = f"delete from user_info where Account_number = {self.account_number}"
self.my_cursor.execute(quarry)
self.mydb.commit()
except Exception as e:
print(Fore.LIGHTRED_EX + ' EXCEPTION : ' + Style.RESET_ALL, e)
self.mydb.rollback()
else:
self.mydb.close()
sys.exit(' your account has been deleted, you can not get anything back , \n'
' THANK YOU FOR USING THE BANK, vesit again')
else:
break
else:
print(Fore.LIGHTRED_EX + ' Invalid Password' + Style.RESET_ALL)
else:
print(Fore.LIGHTBLUE_EX + ' INVALID PIN ' + Style.RESET_ALL)
<file_sep>/README.md
# newone-Repository-1 | 352050921fced3608435e56ad0bf79602766533a | [
"Markdown",
"Java",
"Python"
] | 7 | Python | Naveen-yennaboina/newone-Repository-1 | 64cd0d87125cff803a4e38bcd4da897dc81f677d | a6ca89e7b0d79530ec6cadef964700bd144b3347 |
refs/heads/master | <file_sep>package com.eugene.androidpractice.ui.base
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import javax.inject.Inject
abstract class BaseActivity<V : ViewModel> : AppCompatActivity() {
@Inject
lateinit var viewModelClass: Class<V>
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
protected lateinit var viewModel: V
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(viewModelClass)
}
}
<file_sep>package com.eugene.androidpractice.utils
const val SP_NAME = "ap_prefs"
const val PREFS_LANGUAGE_KEY = "pref_lang"
const val LANGUAGE_CODE_UKRAINIAN = "uk"
const val LANGUAGE_CODE_ENGLISH = "en"
const val SWITCH_LANGUAGE_REQUEST = 101<file_sep>package com.eugene.androidpractice.ui.animation.shared
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.transition.TransitionInflater
import android.support.v4.app.Fragment
import android.transition.Explode
import android.transition.Fade
import android.view.Window
import com.eugene.androidpractice.R
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import javax.inject.Inject
class SecondSharedAnimationsActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupWindow()
setContentView(R.layout.activity_second_shared_animations)
}
private fun setupWindow() {
val moveTransition = TransitionInflater.from(this).inflateTransition(android.R.transition.move)
val changeTransform = TransitionInflater.from(this).inflateTransition(R.transition.image_shared_element_transition)
changeTransform.duration = 600
with(window) {
// enable transitions (if you did not enable transitions in your theme)
requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
enterTransition = Fade()
exitTransition = Fade()
sharedElementEnterTransition = moveTransition
sharedElementExitTransition = changeTransform
}
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector
}
<file_sep>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.eugene.androidpractice"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$rootProject.kotlinVersion"
implementation "com.android.support:appcompat-v7:$rootProject.supportVersion"
implementation "com.android.support:support-v4:$rootProject.supportVersion"
implementation "com.android.support:design:$rootProject.supportVersion"
implementation "com.android.support:recyclerview-v7:$rootProject.supportVersion"
implementation "com.android.support.constraint:constraint-layout:$rootProject.constraintLayoutVersion"
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation "junit:junit:$rootProject.junitVersion"
androidTestImplementation "com.android.support.test:runner:$rootProject.runnerVersion"
androidTestImplementation "com.android.support.test.espresso:espresso-core:$rootProject.espressoVersion"
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:$rootProject.lifecycleVersion"
implementation "android.arch.lifecycle:reactivestreams:$rootProject.lifecycleVersion"
kapt "android.arch.lifecycle:compiler:$rootProject.lifecycleVersion"
//Room
implementation "android.arch.persistence.room:runtime:$rootProject.roomVersion"
kapt "android.arch.persistence.room:compiler:$rootProject.roomVersion"
//Dagger 2
implementation "com.google.dagger:dagger:$rootProject.daggerVersion"
kapt "com.google.dagger:dagger-compiler:$rootProject.daggerVersion"
implementation "com.google.dagger:dagger-android:$rootProject.daggerVersion"
implementation "com.google.dagger:dagger-android-support:$rootProject.daggerVersion"
kapt "com.google.dagger:dagger-android-processor:$rootProject.daggerVersion"
//Timber
implementation "com.jakewharton.timber:timber:$rootProject.timberVersion"
//Rx
implementation "io.reactivex.rxjava2:rxjava:$rootProject.rxJavaVersion"
implementation "io.reactivex.rxjava2:rxandroid:$rootProject.rxAndroidVersion"
//Coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.kotlinCoroutinesVersion"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.kotlinCoroutinesVersion"
//Glide
implementation "com.github.bumptech.glide:glide:$rootProject.glideVersion"
kapt "com.github.bumptech.glide:compiler:$rootProject.glideVersion"
//ExoPlayer
implementation 'com.google.android.exoplayer:exoplayer:2.7.3'
}
<file_sep>package com.eugene.androidpractice.ui.base
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.annotation.AnimRes
import android.support.annotation.IdRes
import android.support.v4.app.DialogFragment
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentManager.POP_BACK_STACK_INCLUSIVE
import javax.inject.Inject
class NavigationController @Inject
constructor(val activity: FragmentActivity) : Navigator {
private val fragmentManager: FragmentManager = activity.supportFragmentManager
override fun finishActivity() {
activity.finish()
}
override fun startActivity(activityClass: Class<out Activity>) {
startActivityNavigation(activityClass, null, null, false)
}
override fun startActivity(activityClass: Class<out Activity>, args: Bundle?, newTask: Boolean) {
startActivityNavigation(activityClass, args, null, newTask)
}
override fun startActivity(activityClass: Class<out Activity>, args: Bundle) {
startActivityNavigation(activityClass, args, null, false)
}
override fun startActivityForResult(activityClass: Class<out Activity>, requestCode: Int) {
startActivityNavigation(activityClass, null, requestCode, false)
}
override fun startActivityForResult(activityClass: Class<out Activity>, requestCode: Int, args: Bundle) {
startActivityNavigation(activityClass, args, requestCode, false)
}
override fun startActivityForResult(intent: Intent, requestCode: Int) {
activity.startActivityForResult(intent, requestCode)
}
override fun replaceFragment(containerId: Int, fragment: Fragment, args: Bundle?) {
replaceFragmentNavigation(containerId, fragment, null, args, false, null, null, null, null, null)
}
override fun replaceFragment(containerId: Int, fragment: Fragment, fragmentTag: String, args: Bundle?) {
replaceFragmentNavigation(containerId, fragment, fragmentTag, args, false, null, null, null, null, null)
}
override fun replaceFragmentBackStack(containerId: Int, fragment: Fragment, fragmentTag: String?, args: Bundle?) {
replaceFragmentNavigation(containerId, fragment, fragmentTag, args, true, null, null, null, null, null)
}
override fun replaceFragmentBackStack(containerId: Int, fragment: Fragment, fragmentTag: String, args: Bundle?, backstackTag: String?) {
replaceFragmentNavigation(containerId, fragment, fragmentTag, args, true, backstackTag, null, null, null, null)
}
override fun replaceFragmentBackStack(containerId: Int, fragment: Fragment, fragmentTag: String, args: Bundle?, backstackTag: String?,
enterAnimation: Int, exitAnimation: Int, popEnterAnimation: Int, popExitAnimation: Int) {
replaceFragmentNavigation(containerId, fragment, fragmentTag, args, true, backstackTag,
enterAnimation, exitAnimation, popEnterAnimation, popExitAnimation)
}
override fun showDialog(dialogFragment: DialogFragment) {
dialogFragment.show(activity.supportFragmentManager, dialogFragment.tag)
}
override fun clearBackStack() {
if (fragmentManager.backStackEntryCount > 0) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
}
override fun popupBackStack() {
if (fragmentManager.backStackEntryCount > 0) {
fragmentManager.popBackStack()
}
}
override fun popupBackStackInclusive(fragmentTag: String) {
if (fragmentManager.backStackEntryCount > 0) {
fragmentManager.popBackStack(null, POP_BACK_STACK_INCLUSIVE)
}
}
private fun startActivityNavigation(activityClass: Class<out Activity>, args: Bundle?, requestCode: Int?, newTask: Boolean) {
val intent = Intent(activity, activityClass)
if (args != null)
intent.putExtras(args)
if (newTask) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
if (requestCode != null)
activity.startActivityForResult(intent, requestCode)
else
activity.startActivity(intent)
}
private fun replaceFragmentNavigation(@IdRes containerId: Int, fragment: Fragment, fragmentTag: String?, args: Bundle?, addToBackstack: Boolean, backstackTag: String?,
@AnimRes enterAnimation: Int?, @AnimRes exitAnimation: Int?, @AnimRes popEnterAnimation: Int?, @AnimRes popExitAnimation: Int?) {
var frag = fragment
var fragTag = fragmentTag
var _addToBackStack = addToBackstack
if (fragmentTag != null) {
if (isFragmentTheSame(getCurrentFragment(containerId), fragment))
return
if (fragmentManager.findFragmentByTag(fragmentTag) != null) {
frag = fragmentManager.findFragmentByTag(fragmentTag) as Fragment
fragTag = frag.tag
_addToBackStack = false
}
}
if (args != null) {
frag.arguments = args
}
val ft = fragmentManager.beginTransaction()
if (enterAnimation != null && exitAnimation != null && popEnterAnimation != null && popExitAnimation != null)
ft.setCustomAnimations(enterAnimation, exitAnimation, popEnterAnimation, popExitAnimation)
else if (enterAnimation != null && exitAnimation != null)
ft.setCustomAnimations(enterAnimation, exitAnimation)
ft.replace(containerId, frag, fragTag)
if (_addToBackStack) {
ft.addToBackStack(backstackTag).commit()
fragmentManager.executePendingTransactions()
} else {
ft.commitAllowingStateLoss()
}
}
private fun isFragmentTheSame(current: Fragment?, newFragment: Fragment): Boolean {
return current != null && newFragment.javaClass == current.javaClass
}
private fun getCurrentFragment(@IdRes containerId: Int): Fragment? {
return fragmentManager.findFragmentById(containerId)
}
}
<file_sep>package com.eugene.androidpractice.di
/**
* Marks an activity / fragment injectable.
*/
interface Injectable<file_sep>package com.eugene.androidpractice.utils
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MediatorLiveData
import com.eugene.androidpractice.data.model.Resource
fun <T1, T2> zip(src1: LiveData<Resource<T1>>, src2: LiveData<Resource<T2>>):
LiveData<Resource<Pair<Resource<T1>?, Resource<T2>?>>> {
return MediatorLiveData<Resource<Pair<Resource<T1>?, Resource<T2>?>>>().apply {
value = Resource.loading(null)
var src1Version = 0
var src2Version = 0
var lastSrc1: Resource<T1>? = null
var lastSrc2: Resource<T2>? = null
fun update() {
if (src1Version > 0 && src2Version > 0){
if(lastSrc1 != null && lastSrc2 != null) {
value = Resource.success(Pair(lastSrc1, lastSrc2))
src1Version = 0
src2Version = 0
} else {
value = Resource.error("", Pair(lastSrc1, lastSrc2))
}
}
}
addSource(src1) {
lastSrc1 = it
src1Version++
update()
}
addSource(src2) {
lastSrc2 = it
src2Version++
update()
}
}
}
fun <T1, T2, R> zip2Sources(src1: LiveData<Resource<T1>>, src2: LiveData<Resource<T2>>, zipper: (Resource<T1>, Resource<T2>) -> R):
LiveData<Resource<R>> {
return MediatorLiveData<Resource<R>>().apply {
value = Resource.loading(null)
var src1Version = 0
var src2Version = 0
var lastSrc1: Resource<T1>? = null
var lastSrc2: Resource<T2>? = null
fun update() {
if (src1Version > 0 && src2Version > 0){
if(lastSrc1 != null && lastSrc2 != null) {
value = Resource.success(zipper(lastSrc1!!, lastSrc2!!))
src1Version = 0
src2Version = 0
} else {
value = Resource.error("", zipper(lastSrc1!!, lastSrc2!!))
}
}
}
addSource(src1) {
lastSrc1 = it
src1Version++
update()
}
addSource(src2) {
lastSrc2 = it
src2Version++
update()
}
}
}<file_sep>package com.eugene.androidpractice.data.repository
import io.reactivex.Observable
interface Repository {
fun getSampleObservable(): Observable<String>
}<file_sep>package com.eugene.androidpractice.di.activities
import android.support.v4.app.FragmentActivity
import com.eugene.androidpractice.ui.localization.LanguageSettingsActivity
import dagger.Module
import dagger.Provides
@Module
class LanguageSettingsActivityModule {
@Provides
internal fun provideActivity(activity: LanguageSettingsActivity): FragmentActivity = activity
}<file_sep>package com.eugene.androidpractice.ui.animation
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.constraint.ConstraintSet
import android.support.transition.ChangeBounds
import android.support.transition.Transition
import android.support.transition.TransitionInflater
import android.support.transition.TransitionManager
import android.view.animation.OvershootInterpolator
import com.eugene.androidpractice.R
import kotlinx.android.synthetic.main.activity_key_frame_animations_set1.*
class KeyFrameAnimationsActivity : AppCompatActivity() {
private val constraintSet1 = ConstraintSet()
private val constraintSet2 = ConstraintSet()
private var show = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_animations)
constraintSet1.clone(this, R.layout.activity_key_frame_animations_set1)
constraintSet2.clone(this, R.layout.activity_key_frame_animations_set2)
article_image.setOnClickListener {
if (show)
showArticleDetails()
else
showArticlePreview()
}
}
private fun showArticlePreview() {
show = true
val transition = ChangeBounds()
transition.interpolator = OvershootInterpolator()
TransitionManager.beginDelayedTransition(constraint_layout_root, transition)
constraintSet1.applyTo(constraint_layout_root)
}
private fun showArticleDetails() {
show = false
val transition: Transition = TransitionInflater.from(this)
.inflateTransition(R.transition.article_details_transition)
TransitionManager.beginDelayedTransition(constraint_layout_root, transition)
constraintSet2.applyTo(constraint_layout_root)
}
}
<file_sep>package com.eugene.androidpractice.di.activities
import android.support.v4.app.FragmentActivity
import com.eugene.androidpractice.ui.animation.KeyFrameAnimationsActivity
import dagger.Module
import dagger.Provides
@Module
class KeyFrameAnimationsActivityModule {
@Provides
internal fun provideActivity(activity: KeyFrameAnimationsActivity): FragmentActivity = activity
}<file_sep>package com.eugene.androidpractice.ui.recyclerview
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import com.eugene.androidpractice.AppExecutors
import com.eugene.androidpractice.R
import com.eugene.androidpractice.data.model.SimpleModel
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import kotlinx.android.synthetic.main.activity_recycler_view.*
import timber.log.Timber
import javax.inject.Inject
class RecyclerViewActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
lateinit var appExecutors: AppExecutors
private lateinit var items: MutableList<SimpleModel>
private lateinit var adapter: SimpleModelAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler_view)
setupRecyclerView()
}
private fun setupRecyclerView() {
adapter = SimpleModelAdapter(appExecutors) {
Timber.d("Item ${it.id} clicked")
}
val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.END) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
val fromPos = viewHolder.adapterPosition
val toPos = target.adapterPosition
val selectedItem = items[fromPos]
items.removeAt(fromPos)
items.add(toPos, selectedItem)
adapter.notifyItemMoved(fromPos, toPos)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
items.removeAt(position)
adapter.notifyItemRemoved(position)
}
})
rv.adapter = adapter
itemTouchHelper.attachToRecyclerView(rv)
items = ArrayList<SimpleModel>().apply {
for (i in 1..15)
add(SimpleModel(i, "Item $i"))
}
adapter.submitList(items)
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector
}
<file_sep>package com.eugene.androidpractice.ui.animation.shared
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.transition.TransitionInflater
import android.support.v4.app.Fragment
import android.transition.AutoTransition
import android.transition.Fade
import android.view.Window
import com.eugene.androidpractice.R
import com.eugene.androidpractice.ui.base.AppNavigator
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import javax.inject.Inject
class MainSharedAnimationsActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
lateinit var appNavigator: AppNavigator
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupWindow()
setContentView(R.layout.activity_main_shared_animations)
val moveTransition = TransitionInflater.from(this).inflateTransition(android.R.transition.move)
if (savedInstanceState == null) {
appNavigator.navigateToSharedElementFragmentOne(moveTransition)
}
}
private fun setupWindow() {
val moveTransition = TransitionInflater.from(this).inflateTransition(android.R.transition.move)
val changeTransform = TransitionInflater.from(this).inflateTransition(R.transition.image_shared_element_transition)
changeTransform.duration = 600
// enable transitions (if you did not enable transitions in your theme)
with(window) {
requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
enterTransition = Fade()
exitTransition = Fade()
sharedElementEnterTransition = AutoTransition()
sharedElementExitTransition = AutoTransition()
}
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector
override fun onBackPressed() {
if (supportFragmentManager.findFragmentById(R.id.fragment_container) is SharedElementFirstFragment)
finish()
else
super.onBackPressed()
}
}
<file_sep>package com.eugene.androidpractice.ui.rx
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import com.eugene.androidpractice.R
import com.eugene.androidpractice.ui.base.AppNavigator
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import javax.inject.Inject
class RXActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
lateinit var appNavigator: AppNavigator
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rx)
if(savedInstanceState == null)
appNavigator.navigateToRxPracticeFragment()
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector
}
<file_sep>package com.eugene.androidpractice.di.activities
import android.support.v4.app.FragmentActivity
import com.eugene.androidpractice.ui.animation.shared.MainSharedAnimationsActivity
import dagger.Module
import dagger.Provides
@Module
class MainSharedAnimationsActivityModule {
@Provides
internal fun provideActivity(activity: MainSharedAnimationsActivity): FragmentActivity = activity
}<file_sep>package com.eugene.androidpractice.ui.recyclerview
import android.databinding.DataBindingUtil
import android.support.v7.util.DiffUtil
import android.view.LayoutInflater
import android.view.ViewGroup
import com.eugene.androidpractice.AppExecutors
import com.eugene.androidpractice.R
import com.eugene.androidpractice.data.model.SimpleModel
import com.eugene.androidpractice.databinding.ListItemSampleBinding
import com.eugene.androidpractice.ui.base.DataBoundListAdapter
class SimpleModelAdapter(appExecutors: AppExecutors, private val callback: ((SimpleModel) -> Unit)?) :
DataBoundListAdapter<SimpleModel, ListItemSampleBinding>(
appExecutors = appExecutors,
diffCallback = object : DiffUtil.ItemCallback<SimpleModel>() {
override fun areItemsTheSame(oldItem: SimpleModel, newItem: SimpleModel): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: SimpleModel, newItem: SimpleModel): Boolean {
return oldItem.title == newItem.title
}
}
) {
override fun createBinding(parent: ViewGroup): ListItemSampleBinding {
val binding: ListItemSampleBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.list_item_sample, parent, false
)
binding.root.setOnClickListener { binding.item?.let { item -> callback?.invoke(item) } }
return binding
}
override fun bind(binding: ListItemSampleBinding, item: SimpleModel, position: Int) {
binding.item = item
}
}<file_sep>package com.eugene.androidpractice.ui.coroutines
import android.arch.lifecycle.Observer
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.view.View
import com.eugene.androidpractice.R
import com.eugene.androidpractice.ui.base.BaseActivity
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import kotlinx.android.synthetic.main.activity_coroutines.*
import javax.inject.Inject
class CoroutinesActivity : BaseActivity<CoroutinesViewModel>(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_coroutines)
if (savedInstanceState == null) {
viewModel.startSimpleCoroutine()
viewModel.loadTitles()
}
observeViewModel()
}
private fun observeViewModel() {
viewModel.snackbar.observe(this, Observer {
it?.let { message -> Snackbar.make(root, message, Snackbar.LENGTH_SHORT).show() }
})
viewModel.loading.observe(this, Observer {
it?.let { loading -> progress.visibility = if (loading) View.VISIBLE else View.GONE }
})
viewModel.listOfItems.observe(this, Observer {list ->
list?.let { result.text = it.map { it.title }.toString()}
})
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector
}
<file_sep>package com.eugene.androidpractice.ui.rx
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.content.res.Resources
import com.eugene.androidpractice.R
import com.eugene.androidpractice.data.repository.Repository
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
class RxPracticeFragmentViewModel @Inject constructor(private val repository: Repository,
resources: Resources) : ViewModel()
{
private val _compositeDisposables = CompositeDisposable()
val result = MutableLiveData<String>()
var resultText: String = resources.getString(R.string.result)
/**
* Don't do this
*/
fun getSampleObservable() {
repository.getSampleObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<String> {
override fun onComplete() {
Timber.d("onComplete")
}
override fun onSubscribe(d: Disposable) {
Timber.d("onSubscribe")
_compositeDisposables.add(d)
}
override fun onNext(t: String) {
Timber.d("onNext $t")
resultText += " $t"
result.value = resultText
}
override fun onError(e: Throwable) {
Timber.d("onError")
}
})
}
override fun onCleared() {
_compositeDisposables.clear()
super.onCleared()
}
}<file_sep>package com.eugene.androidpractice.ui.rx
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.eugene.androidpractice.R
import com.eugene.androidpractice.di.Injectable
import kotlinx.android.synthetic.main.fragment_rx_practice.*
import javax.inject.Inject
class RxPracticeFragment : Fragment(), Injectable {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var viewModel: RxPracticeFragmentViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_rx_practice, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(RxPracticeFragmentViewModel::class.java)
if(savedInstanceState == null)
viewModel.getSampleObservable()
observeViewModel()
}
private fun observeViewModel() {
viewModel.result.observe(this, Observer {
result_text.text = it
})
}
}
<file_sep>package com.eugene.androidpractice.ui.animation
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.View
import com.eugene.androidpractice.R
import com.eugene.androidpractice.ui.base.AppNavigator
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import kotlinx.android.synthetic.main.activity_main_animations.*
import javax.inject.Inject
class MainAnimationsActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
lateinit var appNavigator: AppNavigator
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_animations)
}
fun clickHandler(v: View){
when(v.id){
key_frame_button.id -> appNavigator.navigateToKeyFrameAnimations()
shared_element_button.id -> appNavigator.navigateToSharedElementAnimations()
}
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector
}
<file_sep>package com.eugene.androidpractice.ui.animation.shared
import android.os.Bundle
import android.support.transition.TransitionInflater
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.eugene.androidpractice.R
import com.eugene.androidpractice.di.Injectable
import com.eugene.androidpractice.ui.base.AppNavigator
import kotlinx.android.synthetic.main.fragment_shared_element_first.*
import javax.inject.Inject
class SharedElementFirstFragment : Fragment(), Injectable {
@Inject
lateinit var appNavigator: AppNavigator
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_shared_element_first, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val changeTransform = TransitionInflater.from(context).inflateTransition(R.transition.image_shared_element_transition)
changeTransform.duration = 600
user_icon.setOnClickListener {
appNavigator.navigateToSharedElementFragmentTwo(user_icon, changeTransform)
}
}
}
<file_sep>package com.eugene.androidpractice.di
import android.app.Application
import android.content.res.Resources
import com.eugene.androidpractice.data.repository.DataRepository
import com.eugene.androidpractice.data.repository.Repository
import com.eugene.androidpractice.data.repository.local.PrefsManager
import com.eugene.androidpractice.ui.coroutines.CoroutinesViewModel
import com.eugene.androidpractice.utils.LocaleManager
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module(includes = [ViewModelModule::class])
class AppModule {
@Provides
@Singleton
fun provideResources(application: Application): Resources = application.resources
@Provides
@Singleton
fun providePrefsManager(application: Application): PrefsManager = PrefsManager(application)
@Provides
@Singleton
fun provideRepository(dataRepository: DataRepository): Repository = dataRepository
@Provides
@Singleton
fun provideLocaleManager(prefsManager: PrefsManager, resources: Resources): LocaleManager =
LocaleManager(prefsManager, resources)
@Provides
fun provideCoroutinesViewModel(): Class<CoroutinesViewModel> = CoroutinesViewModel::class.java
}
<file_sep>package com.eugene.androidpractice.data.repository.local
import android.content.Context
import android.content.SharedPreferences
import com.eugene.androidpractice.utils.PREFS_LANGUAGE_KEY
import com.eugene.androidpractice.utils.SP_NAME
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PrefsManager @Inject constructor(context: Context) {
private val sharedPreferences: SharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
fun deleteSP() {
sharedPreferences.edit().clear().apply()
}
fun saveString(key: String, value: String?) {
val editor = sharedPreferences.edit()
editor.putString(key, value)
editor.apply()
}
fun saveBoolean(key: String, value: Boolean) {
val editor = sharedPreferences.edit()
editor.putBoolean(key, value)
editor.apply()
}
fun saveInt(key: String, value: Int) {
val editor = sharedPreferences.edit()
editor.putInt(key, value)
editor.apply()
}
fun saveLong(key: String, value: Long) {
val editor = sharedPreferences.edit()
editor.putLong(key, value)
editor.apply()
}
fun retrieveString(key: String, defValue: String): String {
return sharedPreferences.getString(key, defValue)
}
fun retrieveInt(key: String, defValue: Int): Int {
return sharedPreferences.getInt(key, defValue)
}
fun retrieveLong(key: String, defValue: Long): Long {
return sharedPreferences.getLong(key, defValue)
}
fun retrieveBoolean(key: String, defValue: Boolean): Boolean {
return sharedPreferences.getBoolean(key, defValue)
}
fun retrieveFloat(key: String, defValue: Float): Float {
return sharedPreferences.getFloat(key, defValue)
}
fun saveLanguageCode(languageCode: String) {
saveString(PREFS_LANGUAGE_KEY, languageCode)
}
fun getLanguageCode(): String =
retrieveString(PREFS_LANGUAGE_KEY, Locale.getDefault().language).toLowerCase()
}<file_sep>package com.eugene.androidpractice.di
import com.eugene.androidpractice.ui.animation.shared.SharedElementFirstFragment
import com.eugene.androidpractice.ui.animation.shared.SharedElementSecondFragment
import com.eugene.androidpractice.ui.rx.RxPracticeFragment
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class FragmentBuildersModule{
@ContributesAndroidInjector
internal abstract fun contributeRxPracticeFragment(): RxPracticeFragment
@ContributesAndroidInjector
internal abstract fun contributeSharedElementFirstFragment(): SharedElementFirstFragment
@ContributesAndroidInjector
internal abstract fun contributeSharedElementSecondFragment(): SharedElementSecondFragment
}<file_sep>package com.eugene.androidpractice.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.View
import com.eugene.androidpractice.R
import com.eugene.androidpractice.ui.base.AppNavigator
import com.eugene.androidpractice.utils.*
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import javax.inject.Inject
class MainActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
lateinit var appNavigator: AppNavigator
@Inject
lateinit var localeManager: LocaleManager
override fun attachBaseContext(newBase: Context?) {
var base = newBase
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val locale = Locale(newBase?.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
?.getString(PREFS_LANGUAGE_KEY, LANGUAGE_CODE_ENGLISH)?.toLowerCase())
Locale.setDefault(locale)
val config = Configuration()
config.setLocale(locale)
base = newBase!!.createConfigurationContext(config)
}
super.attachBaseContext(base)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
localeManager.setLocale()
}
fun clickHandler(v: View){
when(v.id){
rx_button.id -> appNavigator.navigateToRx()
localization_button.id -> appNavigator.navigateToLanguageSettings()
animations_button.id -> appNavigator.navigateToAnimations()
inflater_button.id -> appNavigator.navigateToInflater()
coroutines_button.id -> appNavigator.navigateToCoroutines()
media_button.id -> appNavigator.navigateToMedia()
rv_button.id -> appNavigator.navigateToRV()
}
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == SWITCH_LANGUAGE_REQUEST && resultCode == Activity.RESULT_OK) {
//Recreate activity to create new ConfigurationContext with appropriate resources
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
localeManager.setLocale()
recreate()
}
}
}
<file_sep>package com.eugene.androidpractice.data.model
data class SimpleModel (val id: Int, var title: String)<file_sep>package com.eugene.androidpractice.di.activities
import android.support.v4.app.FragmentActivity
import com.eugene.androidpractice.ui.recyclerview.RecyclerViewActivity
import dagger.Module
import dagger.Provides
@Module
class RecyclerViewActivityModule {
@Provides
internal fun provideActivity(activity: RecyclerViewActivity): FragmentActivity = activity
}<file_sep>package com.eugene.androidpractice.glide
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
/**
* Defines a set of dependencies and options to use when initializing Glide within an application.
*/
@GlideModule
class AndroidPracticeGlideModule : AppGlideModule()<file_sep>package com.eugene.androidpractice.ui.base
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.annotation.AnimRes
import android.support.annotation.IdRes
import android.support.v4.app.DialogFragment
import android.support.v4.app.Fragment
interface Navigator {
fun finishActivity()
fun startActivity(activityClass: Class<out Activity>)
fun startActivity(activityClass: Class<out Activity>, args: Bundle)
fun startActivityForResult(intent: Intent, requestCode: Int)
fun startActivityForResult(activityClass: Class<out Activity>, requestCode: Int)
fun startActivityForResult(activityClass: Class<out Activity>, requestCode: Int, args: Bundle)
fun startActivity(activityClass: Class<out Activity>, args: Bundle?, newTask: Boolean)
fun replaceFragment(@IdRes containerId: Int, fragment: Fragment, args: Bundle?)
fun replaceFragment(containerId: Int, fragment: Fragment, fragmentTag: String, args: Bundle?)
fun replaceFragmentBackStack(@IdRes containerId: Int, fragment: Fragment, fragmentTag: String?, args: Bundle?)
fun replaceFragmentBackStack(@IdRes containerId: Int, fragment: Fragment, fragmentTag: String, args: Bundle?, backstackTag: String?)
fun replaceFragmentBackStack(@IdRes containerId: Int, fragment: Fragment, fragmentTag: String, args: Bundle?, backstackTag: String?,
@AnimRes enterAnimation: Int, @AnimRes exitAnimation: Int, @AnimRes popEnterAnimation: Int, @AnimRes popExitAnimation: Int)
fun showDialog(dialogFragment: DialogFragment)
fun clearBackStack()
fun popupBackStack()
fun popupBackStackInclusive(fragmentTag: String)
}
<file_sep>package com.eugene.androidpractice.di
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import com.eugene.androidpractice.ui.coroutines.CoroutinesViewModel
import com.eugene.androidpractice.ui.rx.RxPracticeFragmentViewModel
import com.eugene.androidpractice.viewmodel.PracticeViewModelFactory
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
@Module
abstract class ViewModelModule {
@Binds
abstract fun bindViewModelFactory(factory: PracticeViewModelFactory): ViewModelProvider.Factory
@Binds
@IntoMap
@ViewModelKey(RxPracticeFragmentViewModel::class)
abstract fun bindRxPracticeFragmentViewModel(viewModel: RxPracticeFragmentViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(CoroutinesViewModel::class)
abstract fun bindCoroutinesViewModel(viewModel: CoroutinesViewModel): ViewModel
}
<file_sep>package com.eugene.androidpractice.di.activities
import android.support.v4.app.FragmentActivity
import com.eugene.androidpractice.ui.animation.shared.SecondSharedAnimationsActivity
import dagger.Module
import dagger.Provides
@Module
class SecondAnimationsActivityModule {
@Provides
internal fun provideActivity(activity: SecondSharedAnimationsActivity): FragmentActivity = activity
}<file_sep>package com.eugene.androidpractice.di.activities
import android.support.v4.app.FragmentActivity
import com.eugene.androidpractice.ui.animation.MainAnimationsActivity
import dagger.Module
import dagger.Provides
@Module
class MainAnimationsActivityModule {
@Provides
internal fun provideActivity(activity: MainAnimationsActivity): FragmentActivity = activity
}<file_sep>package com.eugene.androidpractice.ui.coroutines
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.content.res.Resources
import com.eugene.androidpractice.R
import com.eugene.androidpractice.data.model.SimpleModel
import com.eugene.androidpractice.utils.SingleLiveEvent
import kotlinx.coroutines.*
import java.io.IOException
import javax.inject.Inject
import kotlin.random.Random
class CoroutinesViewModel @Inject constructor(val resources: Resources) : ViewModel() {
/**
* Request a snackbar to display a string.
*/
private val _snackBar = SingleLiveEvent<String>()
val snackbar: SingleLiveEvent<String>
get() = _snackBar
/**
* Show a loading spinner if true
*/
private val _loading = MutableLiveData<Boolean>()
val loading: LiveData<Boolean>
get() = _loading
/**
* This is the job for all coroutines started by this ViewModel.
* Cancelling this job will cancel all coroutines started by this ViewModel.
*/
private val viewModelJob = Job()
/**
* This is the main scope for all coroutines launched by MainViewModel.
* Dispatchers.Main is confined to the Main thread operating with UI objects.
* Since we pass viewModelJob, you can cancel all coroutines launched by uiScope by calling
* viewModelJob.cancel()
*/
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
val listOfItems = MutableLiveData<List<SimpleModel>>()
/**
* Called from the CoroutinesActivity
*/
fun startSimpleCoroutine() {
launchDataLoad {
loadSomething()
}
}
/**
* Called from the CoroutinesActivity.
* Parallel calls with async and awaitAll.
*/
fun loadTitles() {
val list = mutableListOf<SimpleModel>().apply {
for (i in 0..10)
add(SimpleModel(i, ""))
}
listOfItems.value = list
launchDataLoad {
val listOfDeferred = list.map {
GlobalScope.async {
it.title = loadTitle()
it
}
}
listOfItems.value = listOfDeferred.awaitAll()
}
}
@Throws(IOException::class)
private suspend fun loadTitle(): String {
delay(3000)
val id = Random.nextInt(100)
if (id > 95)
throw IOException("Unknown Error Occurred")
return "Item $id"
}
private suspend fun loadSomething() {
delay(2000)
_snackBar.value = resources.getString(R.string.hello_from_couroutines)
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
/**
* Helper function to call a data load function with a loading spinner, errors will trigger a
* snackbar.
*
* By marking `block` as `suspend` this creates a suspend lambda which can call suspend
* functions.
*
* @param block lambda to actually load data. It is called in the uiScope. Before calling the
* lambda the loading spinner will display, after completion or error the loading
* spinner will stop
*/
private fun launchDataLoad(block: suspend () -> Unit): Job {
return uiScope.launch {
try {
_loading.value = true
block()
} catch (error: IOException) {
_snackBar.value = error.message
} finally {
_loading.value = false
}
}
}
}
<file_sep>package com.eugene.androidpractice.ui.base
import android.app.ActivityOptions
import android.content.Intent
import android.support.transition.Fade
import android.support.transition.Transition
import android.support.v7.widget.AppCompatImageView
import android.view.View
import android.widget.TextView
import com.eugene.androidpractice.R
import com.eugene.androidpractice.ui.animation.KeyFrameAnimationsActivity
import com.eugene.androidpractice.ui.animation.MainAnimationsActivity
import com.eugene.androidpractice.ui.animation.shared.MainSharedAnimationsActivity
import com.eugene.androidpractice.ui.animation.shared.SecondSharedAnimationsActivity
import com.eugene.androidpractice.ui.animation.shared.SharedElementFirstFragment
import com.eugene.androidpractice.ui.animation.shared.SharedElementSecondFragment
import com.eugene.androidpractice.ui.coroutines.CoroutinesActivity
import com.eugene.androidpractice.ui.inflate.InflaterActivity
import com.eugene.androidpractice.ui.localization.LanguageSettingsActivity
import com.eugene.androidpractice.ui.media.MediaActivity
import com.eugene.androidpractice.ui.recyclerview.RecyclerViewActivity
import com.eugene.androidpractice.ui.rx.RXActivity
import com.eugene.androidpractice.ui.rx.RxPracticeFragment
import com.eugene.androidpractice.utils.SWITCH_LANGUAGE_REQUEST
import javax.inject.Inject
// Rename the Pair class from the Android framework to avoid a name clash
import android.util.Pair as UtilPair
class AppNavigator @Inject constructor(private val navigation: NavigationController) {
fun navigateToRx() {
navigation.startActivity(RXActivity::class.java)
}
fun navigateToRxPracticeFragment() {
navigation.replaceFragment(R.id.fragment_container, RxPracticeFragment(), null)
}
fun navigateToLanguageSettings() {
navigation.startActivityForResult(LanguageSettingsActivity::class.java, SWITCH_LANGUAGE_REQUEST)
}
fun navigateToAnimations() {
navigation.startActivity(MainAnimationsActivity::class.java)
}
fun navigateToKeyFrameAnimations() {
navigation.startActivity(KeyFrameAnimationsActivity::class.java)
}
fun navigateToSharedElementAnimations() {
navigation.startActivity(MainSharedAnimationsActivity::class.java)
}
fun navigateToSharedElementFragmentOne(elementReturnTransition: Transition) {
navigation.activity.supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container,
SharedElementFirstFragment().apply {
sharedElementReturnTransition = elementReturnTransition
enterTransition = Fade().apply { duration = 300 }
exitTransition = Fade().apply { duration = 300 }
})
.addToBackStack(null)
.commit()
}
//Navigation to navigateToSharedElementFragmentTwo with 1 shared image
fun navigateToSharedElementFragmentTwo(sharedImage: AppCompatImageView,
elementEnterTransition: Transition) {
val fm = navigation.activity.supportFragmentManager
fm.beginTransaction()
.addSharedElement(sharedImage, sharedImage.transitionName)
.replace(R.id.fragment_container,
SharedElementSecondFragment().apply {
// 1. Shared Elements Transition
sharedElementEnterTransition = elementEnterTransition
// 2. Enter/exit Transition for new Fragment
enterTransition = Fade().apply { duration = 300 }
exitTransition = Fade().apply { duration = 300 }
})
.addToBackStack(null)
.commitAllowingStateLoss()
}
//Navigation to SecondSharedAnimationsActivity with 2 shared elements
fun navigateToSecondSharedAnimationsActivity(sharedImage: AppCompatImageView, sharedTitle: TextView) {
val options = ActivityOptions.makeSceneTransitionAnimation(navigation.activity,
UtilPair.create<View, String>(sharedImage, sharedImage.transitionName),
UtilPair.create<View, String>(sharedTitle, sharedTitle.transitionName))
navigation.activity.startActivity(
Intent(navigation.activity, SecondSharedAnimationsActivity::class.java),
options.toBundle())
}
fun navigateToInflater() {
navigation.startActivity(InflaterActivity::class.java)
}
fun navigateToCoroutines() {
navigation.startActivity(CoroutinesActivity::class.java)
}
fun navigateToMedia() {
navigation.startActivity(MediaActivity::class.java)
}
fun navigateToRV() {
navigation.startActivity(RecyclerViewActivity::class.java)
}
}
<file_sep>package com.eugene.androidpractice.di.activities
import android.support.v4.app.FragmentActivity
import com.eugene.androidpractice.ui.MainActivity
import dagger.Module
import dagger.Provides
@Module
class MainActivityModule {
@Provides
internal fun provideActivity(activity: MainActivity): FragmentActivity = activity
}<file_sep>package com.eugene.androidpractice.ui.inflate
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.EditText
import com.eugene.androidpractice.R
import kotlinx.android.synthetic.main.activity_inflater.*
import java.util.ArrayList
class InflaterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_inflater)
add_view_button.setOnClickListener { addViewToLayout() }
print_results_button.setOnClickListener { printResults() }
}
private fun printResults() {
val resultsArray = ArrayList<String>()
var deletedViews = 0
for (i in 0..list_container.childCount) {
val view = list_container.getChildAt(i - deletedViews)
if (view is EditText) {
val text = view.text.toString().trim()
if (text.isEmpty()) {
//remove view
list_container.removeViewAt(i - deletedViews++)
//remove divider
list_container.removeViewAt(i + 1 - deletedViews++)
} else
resultsArray.add(text)
}
}
results.text = resultsArray.toString()
}
private fun addViewToLayout() {
layoutInflater.inflate(R.layout.edit_text_layout, list_container)
layoutInflater.inflate(R.layout.divider, list_container)
}
}
<file_sep>package com.eugene.androidpractice.di.activities
import android.support.v4.app.FragmentActivity
import com.eugene.androidpractice.ui.rx.RXActivity
import dagger.Module
import dagger.Provides
@Module
class RxActivityModule {
@Provides
internal fun provideActivity(activity: RXActivity): FragmentActivity = activity
}<file_sep>package com.eugene.androidpractice.ui.localization
import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.widget.Toast
import com.eugene.androidpractice.R
import com.eugene.androidpractice.data.repository.local.PrefsManager
import com.eugene.androidpractice.utils.*
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import kotlinx.android.synthetic.main.activity_language_settings.*
import java.util.*
import javax.inject.Inject
class LanguageSettingsActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
lateinit var prefsManager: PrefsManager
@Inject
lateinit var localeManager: LocaleManager
override fun attachBaseContext(newBase: Context?) {
var base = newBase
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val locale = Locale(newBase?.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
?.getString(PREFS_LANGUAGE_KEY, LANGUAGE_CODE_ENGLISH)?.toLowerCase())
Locale.setDefault(locale)
val config = Configuration()
config.setLocale(locale)
base = newBase!!.createConfigurationContext(config)
}
super.attachBaseContext(base)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_language_settings)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
localeManager.setLocale()
button_english.setOnClickListener {
if(prefsManager.getLanguageCode() != LANGUAGE_CODE_ENGLISH) {
prefsManager.saveLanguageCode(LANGUAGE_CODE_ENGLISH)
showToast("App language is English")
setResult(Activity.RESULT_OK)
finish()
}
}
button_ukrainian.setOnClickListener {
if(prefsManager.getLanguageCode() != LANGUAGE_CODE_UKRAINIAN) {
prefsManager.saveLanguageCode(LANGUAGE_CODE_UKRAINIAN)
showToast("Мова додатка українська")
setResult(Activity.RESULT_OK)
finish()
}
}
}
private fun showToast(message: String){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector
}
<file_sep>package com.eugene.androidpractice.data.repository
import android.os.SystemClock
import io.reactivex.Observable
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DataRepository @Inject constructor(): Repository {
override fun getSampleObservable(): Observable<String> {
return Observable.defer {
// Do some long running operation
SystemClock.sleep(2000)
Observable.just("one", "two", "three", "four", "five")
}
}
}<file_sep>package com.eugene.androidpractice.ui.animation.shared
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.eugene.androidpractice.R
import com.eugene.androidpractice.di.Injectable
import com.eugene.androidpractice.ui.base.AppNavigator
import kotlinx.android.synthetic.main.fragment_shared_element_second.*
import javax.inject.Inject
class SharedElementSecondFragment : Fragment(), Injectable {
@Inject
lateinit var appNavigator: AppNavigator
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_shared_element_second, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
user_icon2.setOnClickListener { appNavigator.navigateToSecondSharedAnimationsActivity(user_icon2, title2) }
}
}
<file_sep>package com.eugene.androidpractice.ui.media
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.annotation.RawRes
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.util.Util
import kotlinx.android.synthetic.main.activity_media.*
import com.google.android.exoplayer2.source.MediaSource
import android.view.View
import com.eugene.androidpractice.R
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.source.ConcatenatingMediaSource
import com.google.android.exoplayer2.upstream.*
import java.io.IOException
class MediaActivity : AppCompatActivity() {
private lateinit var exoPlayer: SimpleExoPlayer
private var playbackPosition = 0L
private var currentWindow = 0
private var playWhenReady = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_media)
// recovering the instance state
savedInstanceState?.let {
playbackPosition = it.getLong("playback_position", 0L)
currentWindow = it.getInt("current_window", 0)
playWhenReady = it.getBoolean("play_when_ready", true)
}
}
private fun initializePlayer() {
exoPlayer = ExoPlayerFactory.newSimpleInstance(
DefaultRenderersFactory(this), DefaultTrackSelector(), DefaultLoadControl()
)
player_view.player = exoPlayer
// val resVideoUri = Uri.parse("android.resource://${this.packageName}/${R.raw.test_video}")
val assetsVideoUri = Uri.parse("file:///android_asset/test_video.mp4")
val streamVideoUri = Uri.parse("https://firebasestorage.googleapis.com/v0/b/lifesaver-18f28.appspot.com/o/flood.mp4?alt=media&token=<PASSWORD>1-4a87-b1f8-b1fc3d976c60")
val videoSource = buildConcatenatingMediaSource(R.raw.test_video, streamVideoUri, assetsVideoUri)
videoSource?.let {
// Prepare the player with the source.
exoPlayer.prepare(videoSource, false, false)
exoPlayer.playWhenReady = playWhenReady
exoPlayer.seekTo(currentWindow, playbackPosition)
}
}
private fun buildConcatenatingMediaSource(rawId: Int,
assetsVideoUri: Uri,
streamVideoUri: Uri): MediaSource? =
ConcatenatingMediaSource(
buildRawMediaSource(rawId),
buildStreamMediaSource(assetsVideoUri),
buildAssetsMediaSource(streamVideoUri)
)
private fun buildStreamMediaSource(uri: Uri): MediaSource {
return ExtractorMediaSource.Factory(
DefaultHttpDataSourceFactory("androidPractice")).createMediaSource(uri)
}
private fun buildAssetsMediaSource(uri: Uri): MediaSource {
//Produces DataSource instances through which media data is loaded.
val dataSourceFactory = DefaultDataSourceFactory(this,
Util.getUserAgent(this, "androidPractice"))
//Returns the MediaSource representing the media to be played.
return ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri)
}
private fun buildRawMediaSource(@RawRes rawId: Int): MediaSource? {
val rawDataSource = RawResourceDataSource(this)
try {
//Opens the raw source to read the specified data
rawDataSource.open(DataSpec(RawResourceDataSource.buildRawResourceUri(rawId)))
} catch (e: IOException) {
try {
//If an IOException is thrown, callers must still call DataSource.close() to ensure
//that any partial effects of the invocation are cleaned up.
rawDataSource.close()
} catch (e: IOException) {
} //do nothing
return null
}
//Returns the MediaSource representing the media to be played.
return ExtractorMediaSource.Factory(DataSource.Factory { rawDataSource })
.createMediaSource(rawDataSource.uri)
}
//Starting with API level 24 Android supports multiple windows. As our app can be visible
// but not active in split window mode, we need to initialize the player in onStart.
public override fun onStart() {
super.onStart()
if (Util.SDK_INT > 23)
initializePlayer()
}
// Before API level 24 we wait as long as possible until we grab resources,
// so we wait until onResume before initializing the player.
public override fun onResume() {
super.onResume()
hideSystemUi()
if (Util.SDK_INT <= 23 || !::exoPlayer.isInitialized)
initializePlayer()
}
public override fun onPause() {
super.onPause()
savePlayerState()
if (Util.SDK_INT <= 23) {
releasePlayer()
}
}
private fun savePlayerState() {
playbackPosition = exoPlayer.currentPosition
currentWindow = exoPlayer.currentWindowIndex
playWhenReady = exoPlayer.playWhenReady
}
public override fun onStop() {
super.onStop()
if (Util.SDK_INT > 23) {
releasePlayer()
}
}
private fun hideSystemUi() {
player_view.systemUiVisibility = (View.SYSTEM_UI_FLAG_LOW_PROFILE
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)
}
private fun releasePlayer() {
exoPlayer.release()
}
override fun onSaveInstanceState(outState: Bundle?) {
outState?.run {
putLong("playback_position", playbackPosition)
putInt("current_window", currentWindow)
putBoolean("play_when_ready", playWhenReady)
}
super.onSaveInstanceState(outState)
}
}
<file_sep>package com.eugene.androidpractice.utils
import android.content.res.Configuration
import android.content.res.Resources
import com.eugene.androidpractice.data.repository.local.PrefsManager
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/**
* For API level < 24 (Nougat)
* Build.VERSION.SDK_INT < Build.VERSION_CODES.N
*/
@Singleton
class LocaleManager @Inject constructor(private val prefsManager: PrefsManager,
val resources: Resources) {
fun setLocale(){
setNewLocale(getLanguage())
}
private fun setNewLocale(language: String){
updateResources(language)
}
private fun getLanguage(): String = prefsManager.getLanguageCode()
@Suppress("DEPRECATION")
private fun updateResources(language: String) {
val locale = Locale(language)
Locale.setDefault(locale)
val config = Configuration(resources.configuration)
config.setLocale(locale)
resources.updateConfiguration(config, resources.displayMetrics)
}
}<file_sep>package com.eugene.androidpractice.di.activities
import com.eugene.androidpractice.di.*
import com.eugene.androidpractice.ui.MainActivity
import com.eugene.androidpractice.ui.animation.KeyFrameAnimationsActivity
import com.eugene.androidpractice.ui.animation.MainAnimationsActivity
import com.eugene.androidpractice.ui.animation.shared.MainSharedAnimationsActivity
import com.eugene.androidpractice.ui.animation.shared.SecondSharedAnimationsActivity
import com.eugene.androidpractice.ui.coroutines.CoroutinesActivity
import com.eugene.androidpractice.ui.localization.LanguageSettingsActivity
import com.eugene.androidpractice.ui.recyclerview.RecyclerViewActivity
import com.eugene.androidpractice.ui.rx.RXActivity
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class ActivityBuildersModule {
@ContributesAndroidInjector(modules = [MainActivityModule::class, FragmentBuildersModule::class])
abstract fun contributeMainActivity(): MainActivity
@ContributesAndroidInjector(modules = [RxActivityModule::class, FragmentBuildersModule::class])
abstract fun contributeRXActivity(): RXActivity
@ContributesAndroidInjector(modules = [LanguageSettingsActivityModule::class, FragmentBuildersModule::class])
abstract fun contributeLanguageSettingsActivity(): LanguageSettingsActivity
@ContributesAndroidInjector(modules = [MainAnimationsActivityModule::class, FragmentBuildersModule::class])
abstract fun contributeMainAnimationsActivity(): MainAnimationsActivity
@ContributesAndroidInjector(modules = [KeyFrameAnimationsActivityModule::class, FragmentBuildersModule::class])
abstract fun contributeKeyFrameAnimationsActivity(): KeyFrameAnimationsActivity
@ContributesAndroidInjector(modules = [MainSharedAnimationsActivityModule::class, FragmentBuildersModule::class])
abstract fun contributeMainSharedAnimationsActivity(): MainSharedAnimationsActivity
@ContributesAndroidInjector(modules = [SecondAnimationsActivityModule::class, FragmentBuildersModule::class])
abstract fun contributeSecondSharedAnimationsActivity(): SecondSharedAnimationsActivity
@ContributesAndroidInjector(modules = [CoroutinesActivityModule::class, FragmentBuildersModule::class])
abstract fun contributeCoroutinesActivity(): CoroutinesActivity
@ContributesAndroidInjector(modules = [RecyclerViewActivityModule::class, FragmentBuildersModule::class])
abstract fun contributeRecyclerViewActivity(): RecyclerViewActivity
}
<file_sep>package com.eugene.androidpractice.di.activities
import android.support.v4.app.FragmentActivity
import com.eugene.androidpractice.ui.coroutines.CoroutinesActivity
import dagger.Module
import dagger.Provides
@Module
class CoroutinesActivityModule {
@Provides
internal fun provideActivity(activity: CoroutinesActivity): FragmentActivity = activity
} | dfa981fa94a0b8ce54af195e76fa51e970df65eb | [
"Kotlin",
"Gradle"
] | 44 | Kotlin | EugeneJAD/AndroidPractice | 02a4b0dc52ad7361cffc8e39508a93e1922630a6 | eaa013cb78bff865a4f0a2a45ac4e07cb1c69ce4 |
refs/heads/master | <file_sep>smiegel
=======
Self-hosted desktop text mirroring service. Because the other options suck.
**NOTE**: In development, come back later.
<file_sep>import flask
from flask.ext.sqlalchemy import SQLAlchemy
from smiegel.publisher import Publisher
app = flask.Flask(__name__)
db = SQLAlchemy(app)
publisher = Publisher()
from smiegel.views import ui, api
app.register_blueprint(api.app, url_prefix='/api')
app.register_blueprint(ui.app, static_path='/static')
<file_sep>var Reflux = require('reflux');
var store = require('../vendor/store');
var ContactStore = Reflux.createStore({
init: function() {
if (!store.get('contacts')) {
store.set('contacts', []);
}
},
setContacts: function(contacts) {
store.set('contacts', contacts);
this.trigger();
},
getAll: function() {
var contacts = store.get('contacts') || [];
contacts.sort(function(a, b) {
return a.name.localeCompare(b.name);
});
return contacts;
},
getAllMatching: function(query) {
query = query.toLowerCase();
if (query.trim() === '') {
return this.getAll();
}
var contacts = this.getAll();
var matches = [];
for (var i in contacts) {
var contact = contacts[i];
if (contact.name.toLowerCase().indexOf(query) !== -1) {
matches.push(contact);
} else {
for (var j in contact.numbers) {
if (contact.numbers[j].number.indexOf(query) !== -1) {
matches.push(contact);
break;
}
}
}
}
return matches;
}
});
module.exports = ContactStore;
<file_sep>var forge = require('../vendor/forge').forge;
var humane = require('../vendor/humane');
var KeyStore = require('../stores/KeyStore');
module.exports = {
genRandomBytes: function(length) {
var array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return array;
},
base64ToArray: function(b64) {
var raw = window.atob(b64);
var array = new Uint8Array(new ArrayBuffer(raw.length));
for (var i in raw) {
array[i] = raw.charCodeAt(i);
}
return array;
},
arrayToBase64: function(array) {
var encoded_str = String.fromCharCode.apply(null, array);
return window.btoa(encoded_str);
},
sign: function(message) {
var hmac = forge.hmac.create();
hmac.start('sha256', KeyStore.getToken());
hmac.update(message);
return window.btoa(hmac.digest().data);
},
encrypt: function(message) {
var result = this._encrypt(KeyStore.getSecret(), message);
return result.map(window.btoa);
},
decrypt: function(enc) {
var iv = window.atob(enc[0]);
var tag = window.atob(enc[1]);
var cipher = window.atob(enc[2]);
var key_bytes = KeyStore.getSecret();
return this._decrypt(key_bytes, iv, tag, cipher);
},
_encrypt: function(key, msgBytes) {
var cipher = forge.cipher.createCipher('AES-GCM', key);
var iv = this.genRandomBytes(16);
cipher.start({
iv: iv,
tagLength: 128
});
cipher.update(forge.util.createBuffer(msgBytes));
cipher.finish();
var encrypted = cipher.output.getBytes();
var tag = cipher.mode.tag.getBytes();
return [this.arrayToBase64(iv), tag, encrypted];
},
_decrypt: function(key, iv, tag, cipher) {
var decipher = forge.cipher.createDecipher('AES-GCM', key);
decipher.start({
iv: iv,
tag: forge.util.createBuffer(tag)
});
decipher.update(forge.util.createBuffer(cipher));
if (decipher.finish()) {
return decipher.output;
}
humane.log('Decryption failed! Did your key change?');
return null;
}
};
<file_sep>var humane = require('../vendor/humane');
var ChatAction = require('../actions/ChatAction');
var EventTypes = require('../constants/EventConstants').EventTypes;
var ContactStore = require('../stores/ContactStore');
var KeyStore = require('../stores/KeyStore');
var CryptoUtil = require('../utils/CryptoUtil');
module.exports = {
// Change this if you want to use some third party server
API_HOST: '',
getEventStream: function() {
var source = new EventSource(this.API_HOST + "/stream");
source.addEventListener(EventTypes.CONTACTS, this._eventRecvContacts);
source.addEventListener(EventTypes.CREDENTIALS, this._eventRecvCreds);
source.addEventListener(EventTypes.RECEIVED_MSG, this._eventRecvMsg);
source.addEventListener(EventTypes.ACKED_MSG, this._eventAcked);
source.onerror = function(e) {
console.log(e);
humane.log("Failed to reach server!");
};
return source;
},
sendMessage: function(message) {
this._postData(
'/api/message/send',
this.formatRequest(1, JSON.stringify(message)),
function(response) {
var js = JSON.parse(response);
ChatAction.updateMessageId(message.id, js.id);
}
);
},
formatRequest: function(user_id, body) {
var encrypted = JSON.stringify(CryptoUtil.encrypt(body));
var signature = CryptoUtil.sign(encrypted);
var msg = {
'user_id': KeyStore.getUserId(),
'body': encrypted,
'signature': signature
};
return msg;
},
_postData: function(endpoint, body, cb) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: this.API_HOST + endpoint,
data: JSON.stringify(body),
dataType: "json",
}).done(function(data) {
if (cb) {
cb(data.body);
}
});
},
_eventAcked: function(eventData) {
// TODO: decrypt message here
var msg = JSON.parse(eventData.data);
ChatAction.ackMessage(msg.id);
},
_eventRecvContacts: function(eventData) {
var encrypted = JSON.parse(eventData.data);
var decrypted = CryptoUtil.decrypt(encrypted);
if (decrypted === null) {
humane.log('Failed to decrypt contact list...');
return;
}
humane.log('Received most recent contacts list');
ContactStore.setContacts(JSON.parse(decrypted));
},
_eventRecvMsg: function(eventData) {
var encrypted = JSON.parse(eventData.data);
var decrypted = CryptoUtil.decrypt(encrypted);
if (decrypted === null) {
humane.log('Failed to decrypt message received...');
return;
}
var msg = JSON.parse(decrypted);
// TODO: more message receive-y things
msg.sender = msg.sender || 'other';
ChatAction.receiveMessage(msg);
},
_eventRecvCreds: function(eventData) {
var creds = JSON.parse(eventData.data);
humane.log('Received credentials for ' + creds.email);
var storedCreds = KeyStore.getCredentials();
$.extend(storedCreds, creds);
KeyStore.setCredentials(storedCreds);
}
};
<file_sep>var React = require('react');
var ChatMessage = React.createClass({
render: function() {
var message = this.props.message;
var senderCls = 'sender-' + message.sender;
var ackedCls = message.acked ? 'acked' : 'unacked';
return (
<div className={['message', ackedCls, senderCls].join(' ')}>
<div className="message-author-name">{message.author}
<abbr className="timeago" title={new Date(message.timestamp).toISOString()}>
</abbr>
</div>
{ message.acked ? '' : <div className="loader">...</div> }
<div className="text"> { message.text } </div>
</div>
);
}
});
module.exports = ChatMessage;
<file_sep>var React = require('react');
window.React = React;
var App = require('./components/App.react');
var SetupApp = require('./components/SetupApp.react');
var KeyStore = require('./stores/KeyStore');
var app = KeyStore.isInitialized() ? <App /> : <SetupApp />;
React.render(app, document.getElementById('react'));
<file_sep>var React = require('react');
var ChatMessageList = require('../components/ChatMessageList.react');
var ChatInput = require('../components/ChatInput.react');
var ChatList = require('../components/ChatList.react');
var KeyStore = require('../stores/KeyStore');
var Settings = React.createClass({
componentDidMount: function () {
var that = this;
$('#settings').modal('show');
$('#settings').on('hidden.bs.modal', function () {
that._onClose();
});
var creds = KeyStore.getCredentials();
$.extend(creds, {
'server': window.location.origin
});
$('#qrcode').empty();
$('#qrcode').qrcode(JSON.stringify(creds));
},
render: function() {
return (
<div id="settings" className="modal fade">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button"
className="close"
data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 className="modal-title">Settings</h3>
</div>
<div className="modal-body">
<p>
<div id="qrcode" />
</p>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
);
},
_onClose: function() {
React.unmountComponentAtNode(document.getElementById('modal'));
}
});
module.exports = Settings;
<file_sep>import flask
import hmac
import json
from flask import abort, g, request
from functools import wraps
from smiegel import db, util, publisher
from smiegel.models import User, Message
app = flask.Blueprint('api', __name__)
# API Definitions
# ---------------
# All authenticated requests are wrapped in a signature. The general
# format is as follows:
#
# `{
# "signature": base64(hmac-sha256(body)),
# "body": "a string, content varies",
# "user_id": who is sending this request?
# }`
#
#
# POST /message/receive
# {"sender": string, "body": string, "timestamp": int}
#
# POST /message/send
# {"recipient": string, "body": string, "timestamp": int}
#
# POST /message/ack
# {"id": int}
#
# ...
REQUIRED_KEYS = ['body', 'signature', 'user_id']
def authentication_required(func):
"""For routes that require messages be authenticated"""
@wraps(func)
def decorator(*args, **kwargs):
json = request.get_json(silent=True)
if not (json and validate_signature(json)):
abort(401)
return func(*args, **kwargs)
return decorator
# TODO: validate data types
def validate_signature(json):
if not all([k in json for k in REQUIRED_KEYS]):
return False
g.api_user = User.query.get(json['user_id'])
if not g.api_user:
return False
client_sig = json['signature']
expected_sig = util.authenticate(g.api_user.auth_token, json['body'])
# Prevent timing attacks
return hmac.compare_digest(client_sig, expected_sig)
def sign_response(message):
response = {
'body': message,
'signature': util.authenticate(g.api_user.auth_token, message)
}
return json.dumps(response, indent=4)
@app.route('/contacts', methods=['POST'])
@authentication_required
def contacts():
contacts = request.get_json()['body']
g.api_user.contacts = contacts
db.session.commit()
event = util.Event('CONTACTS', contacts)
publisher.publish(g.api_user.id, event)
return sign_response('sent')
@app.route('/message/receive', methods=['POST'])
@authentication_required
def recv_message():
event = util.Event('RECEIVED_MSG', request.get_json()['body'])
publisher.publish(g.api_user.id, event)
print('hey it worked')
return sign_response('hey great')
@app.route('/message/send', methods=['POST'])
@authentication_required
def send_message():
req_msg = request.get_json()['body']
print('>> sending message: ' + req_msg)
msg = Message(g.api_user.id, req_msg, acked=False)
db.session.add(msg)
db.session.commit()
print(msg.id)
# TODO: route to phone
resp = {'id': str(msg.id)}
return sign_response(json.dumps(resp))
@app.route('/message/ack', methods=['POST'])
@authentication_required
def ack_message():
json = request.get_json()['body']
msg = Message.query.get(json['id'])
if msg is None:
abort(404)
msg.acked = True
db.session.commit()
publisher.publish(g.api_user, util.Event('ACKED_MSG', msg.id))
return sign_response('cool dude')
@app.route('/ping', methods=['POST'])
def ping():
json = request.get_json(silent=True)
if not json:
# TODO: better response
abort(400)
if not validate_signature(json):
return sign_response('bad signature')
return sign_response(json['body'])
<file_sep>import collections
import threading
class CyclicQueue:
"""
A simple fixed-size queue that blocks on pop.
There can be multiple writers, but only one thread should be calling pop at
a time (since pop is a destructive operation)
"""
DEFAULT_SIZE = 1000
def __init__(self, size=DEFAULT_SIZE):
self.queue = collections.deque([], size)
self.event = threading.Event()
def put(self, item):
self.queue.append(item)
self.event.set()
def pop(self):
try:
self.event.clear()
return self.queue.popleft()
except IndexError:
self.event.wait()
return self.pop()
def __iter__(self):
return self
def __next__(self):
if len(self.queue) > 0:
return self.pop()
raise StopIteration
def __len__(self):
return len(self.queue)
<file_sep>import requests
import flask
import json
import queue
from flask import render_template, session, request, abort, g, flash
import smiegel.util as util
from smiegel import db, publisher
from smiegel.models import User
app = flask.Blueprint('ui', __name__, template_folder='templates/',
static_folder='static', static_url_path='/assets')
def create_new_user(email):
user = User(email)
db.session.add(user)
db.session.commit()
return user
@app.before_request
def get_current_login():
uid = session.get('user_id')
if uid:
g.user = User.query.get(uid)
else:
g.user = None
@app.route('/')
def index():
if not g.user:
return flask.redirect('/login')
return render_template('index.html')
@app.route('/stream', methods=['GET'])
def event_stream():
if not g.user:
abort(401)
uid = g.user.id
q = queue.Queue()
# Push credential information first
q.put(util.Event('CREDENTIALS', json.dumps({
'user_id': str(uid),
'auth_token': util.b64_encode(g.user.auth_token),
'email': g.user.login_email
})))
# Push contacts list
q.put(util.Event('CONTACTS', g.user.contacts or {}))
def sse_stream():
try:
publisher.subscribe(uid, q)
while True:
yield q.get().encodeSse()
except GeneratorExit:
publisher.unsubscribe(uid, q)
return flask.Response(sse_stream(),
mimetype='text/event-stream')
@app.route('/login', methods=['GET', 'POST'])
def login():
if g.user:
return flask.redirect('/')
return render_template('login.html', user=g.user)
@app.route('/_auth/login', methods=["GET", "POST"])
def login_handler():
resp = requests.post(flask.current_app.config['PERSONA_VERIFIER'], data={
'assertion': request.form['assertion'],
'audience': request.host_url
}, verify=True)
data = resp.json()
if not resp.ok or data['status'] != 'okay':
flash("Don't you try to spoof me", 'error')
abort(401)
user = User.query.filter_by(login_email=data['email']).first()
if user is None:
user = create_new_user(data['email'])
flash('Welcome to Smiegel!', 'success')
if not user:
abort(500)
flash(str(user.id) + ' ' + util.b64_encode(user.auth_token) + ' ' + user.login_email, 'success')
session['user_id'] = user.id
flash('You logged in', 'success')
return flask.jsonify({'status': 'okay'})
@app.route('/_auth/logout', methods=["GET", "POST"])
def logout_handler():
session.clear()
flash('You logged out', 'success')
return flask.redirect('/')
<file_sep>from smiegel import app, db
if __name__ == '__main__':
app.config.update(
DEBUG=True,
SECRET_KEY='my development key1',
PERSONA_JS='https://login.persona.org/include.js',
PERSONA_VERIFIER='https://verifier.login.persona.org/verify',
SQLALCHEMY_DATABASE_URI='sqlite:////tmp/tmp.db'
)
db.create_all()
app.run('0.0.0.0', threaded=True)
<file_sep>from setuptools import setup
setup(
name='smiegel',
version='0.0',
long_description=__doc__,
packages=['smiegel'],
include_package_data=True,
author='<NAME>',
description='Self hosted SMS mirroring service',
license='MIT',
install_requires=open('requirements.txt').readlines(),
entry_points={
'console_scripts': [
'smiegel = smiegel.__main__:main'
],
}
)
<file_sep>var React = require('react');
var ChatInput = require('../components/ChatInput.react');
var ChatList = require('../components/ChatList.react');
var ChatMessageList = require('../components/ChatMessageList.react');
var Navbar = require('../components/Navbar.react');
var APIUtil = require('../utils/APIUtil.js');
var App = React.createClass({
componentWillMount: function () {
this.listen();
},
render: function() {
return (
<div className="app">
<Navbar />
<div className="row">
<div className="col-sm-3" id="chat-list">
<ChatList />
</div>
<div className="col-sm-9">
<ChatMessageList />
<ChatInput />
</div>
</div>
</div>
);
},
listen: function () {
var eventSource;
return function() {
if (eventSource) { eventSource.close(); }
eventSource = APIUtil.getEventStream();
};
}()
});
module.exports = App;
<file_sep>var Reflux = require('reflux');
var ChatAction = require('../actions/ChatAction');
var MessageStore = require('../stores/MessageStore');
var store = require('../vendor/store');
var _currentId = null;
var ChatStore = Reflux.createStore({
init: function() {
this.listenTo(ChatAction.receiveMessage, this._receiveMessage);
if (!store.get('threads')) {
store.set('threads', {});
}
},
addChat: function(id, name) {
var threads = store.get('threads');
if (!(id in threads)) {
threads[id] = {
'id': id,
'name': name,
'unread': 0
};
store.set('threads', threads);
}
},
getAll: function() {
var threads = store.get('threads');
return Object.keys(threads).map(function(k) {
return threads[k];
});
},
setCurrentId: function(id) {
_currentId = id;
if (_currentId !== null) {
var threads = store.get('threads');
threads[_currentId].unread = 0;
store.set('threads', threads);
}
this.trigger();
MessageStore.trigger();
},
getCurrentId: function() {
return _currentId;
},
_receiveMessage: function(message) {
this.addChat(message.author, message.author);
if (message.author !== _currentId) {
var threads = store.get('threads');
threads[message.author].unread += 1;
store.set('threads', threads);
}
message.thread = message.author;
message.acked = true;
MessageStore.addMessage(message);
this.trigger();
}
});
module.exports = ChatStore;
<file_sep>from smiegel.models.user import User
from smiegel.models.message import Message
<file_sep>import base64
import hmac
import os
from hashlib import sha256
def authenticate(token, message):
"""Generate a HMAC for the given message using the token.
Args:
token (bytearray): The shared authentication token to use.
message (str): The text to authenticate.
Returns:
str: base64 encoded HMAC
"""
msg_bytes = bytearray(message, 'utf-8')
mac = hmac.new(token, msg_bytes, sha256).digest()
return b64_encode(mac)
def generate_auth_token(byte_len=32):
"""Securely generate an authentication token of the appropriate length.
Returns:
bytearray: token
"""
return os.urandom(byte_len)
def b64_encode(msg):
"""Return the base64 representation of msg.
TODO: types and whatnot
"""
return base64.b64encode(msg).decode('utf-8')
def b64_decode(b64):
"""Returns bytes representing given b64 encoded string"""
return base64.b64decode(b64.decode('utf-8'))
# from http://flask.pocoo.org/snippets/116/
class Event:
def __init__(self, event, data):
self.event = event
self.data = data
def encodeSse(self):
if not self.data:
return ""
event = [
("event", self.event),
("data", self.data)
]
lines = ["%s: %s" % (k, v) for k, v in event if v]
return "%s\n\n" % "\n".join(lines)
<file_sep>var React = require('react');
var Reflux = require('reflux');
var KeyStore = require('../stores/KeyStore');
var APIUtil = require('../utils/APIUtil');
var CryptoUtil = require('../utils/CryptoUtil');
var SetupApp = React.createClass({
mixins: [Reflux.ListenerMixin],
componentWillMount: function () {
this._listen();
this.listenTo(KeyStore, this._updateQr);
},
componentDidMount: function() {
this._regenerate('secret_key')();
},
_renderSecret: function(ref, name) {
return (
<p key={ref}>
<div className="input-group">
<div className="input-group-btn">
<button type="button"
className="btn btn-default dropdown-toggle"
data-toggle="dropdown"
aria-expanded="false">
{ name }
<span className="caret" />
</button>
<ul className="dropdown-menu" role="menu">
<li>
<a onClick={this._regenerate(ref)}>
Regenerate { name }
</a>
</li>
</ul>
</div>
<input ref={ref}
onChange={this._updateQr}
type="text"
className="form-control" />
</div>
</p>
);
},
render: function() {
return (
<div className="app row">
<div className="col-sm-12">
<div className="page-header">
<h1>hey lets go ahead and set this up. <small>yeah bro</small></h1>
</div>
<h2>Step 0. Install the app. <small>Which doesnt exist yet sorry.</small></h2>
<a href="https://github.com/erik/smiegel-android">
<img alt="Get it on Google Play"
src="https://developer.android.com/images/brand/en_generic_rgb_wo_60.png" />
</a>
<h2>Step 1. Make sure Im not evil. <small>Or dont see if I care</small></h2>
<p> If you have an existing configuration somewhere copy paste the values in here</p>
{ this._renderSecret('secret_key', 'Secret Key') }
<h2>Step 2. Scan the QR Code <small>With the app, dummy</small></h2>
<div className="well">
<div id="qrcode" />
</div>
</div>
</div>
);
},
_regenerate: function(ref) {
var that = this;
return function() {
var key = CryptoUtil.genRandomBytes(32);
var key_b64 = CryptoUtil.arrayToBase64(key);
that.refs[ref].getDOMNode().value = key_b64;
var creds = KeyStore.getCredentials();
KeyStore.setCredentials({ shared_key: key_b64 });
};
},
_updateQr: function() {
var creds = KeyStore.getCredentials();
$.extend(creds, {
'server': window.location.origin
});
$('#qrcode').empty();
$('#qrcode').qrcode(JSON.stringify(creds));
},
_listen: function () {
var eventSource;
return function() {
if (eventSource) { eventSource.close(); }
eventSource = APIUtil.getEventStream();
};
}()
});
module.exports = SetupApp;
<file_sep>var Reflux = require('reflux');
var ChatAction = require('../actions/ChatAction');
var APIUtil = require('../utils/APIUtil');
var store = require('../vendor/store');
var MessageStore = Reflux.createStore({
init: function() {
this.listenTo(ChatAction.ackMessage, this._ackMessage);
this.listenTo(ChatAction.createMessage, this._createMessage);
this.listenTo(ChatAction.updateMessageId, this._updateMessageId);
},
addMessage: function(message) {
var msgs = store.get('messages') || [];
msgs.push(message);
store.set('messages', msgs);
this.trigger();
},
formatCreatedMessage: function(message) {
var ChatStore = require('../stores/ChatStore');
var timestamp = Date.now();
return {
id: 'tmp_' + timestamp,
author: 'me',
sender: 'self',
timestamp: new Date(timestamp),
acked: false,
thread: ChatStore.getCurrentId(),
text: message
};
},
getAll: function() {
return store.get('messages') || [];
},
getAllForChat: function(chatId) {
var messages = store.get('messages') || [];
return messages.filter(function(msg) {
return msg.thread === chatId;
});
},
_ackMessage: function(id) {
var msgs = store.get('messages') || [];
msgs = msgs.map(function(msg) {
if (msg.id === id) {
msg.acked = true;
}
return msg;
});
store.set('messages', msgs);
this.trigger();
},
_createMessage: function(text) {
var message = this.formatCreatedMessage(text);
this.addMessage(message);
APIUtil.sendMessage(message);
this.trigger();
},
_updateMessageId: function(oldId, newId) {
var msgs = store.get('messages') || [];
msgs = msgs.map(function(msg) {
if (msg.id === oldId) {
msg.id = newId;
}
return msg;
});
store.set('messages', msgs);
this.trigger();
}
});
module.exports = MessageStore;
<file_sep>import datetime
from smiegel import db
class Message(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime)
text = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
acked = db.Column(db.Boolean)
def __init__(self, user_id, text, acked=True, timestamp=None):
if timestamp is None:
timestamp = datetime.datetime.utcnow()
self.timestamp = timestamp
self.user_id = user_id
self.text = text
self.acked = acked
<file_sep>var React = require('react');
var Reflux = require('reflux');
var ContactList = require('../components/ContactList.react');
var ChatStore = require('../stores/ChatStore');
var ChatItem = React.createClass({
onClick: function() {
ChatStore.setCurrentId(this.props.chat.id);
},
render: function() {
var chat = this.props.chat;
var cls = "list-group-item";
if (chat.id == ChatStore.getCurrentId()) {
cls += " active";
}
var unread = '';
if (chat.unread > 0) {
unread = <span className="badge"> { chat.unread } </span>;
}
var id = '';
if (chat.id != chat.name) {
id = <em> { chat.id } </em>;
}
return (
<a onClick={this.onClick}
className={ cls }>
{ chat.name }
{ unread }
{ id }
</a>
);
}
});
var ChatList = React.createClass({
mixins: [Reflux.ListenerMixin],
getInitialState: function() {
return this._getStateFromStores();
},
componentDidMount: function() {
this.listenTo(ChatStore, this._onChange);
},
componentDidUpdate: function() {},
render: function() {
var chats = this.state.chats.map(this._getChat);
return (
<div className="chat-list">
<div className="list-group">
<a onClick={this._openContactList}
href="#"
className="list-group-item">
<span className="glyphicon glyphicon-plus" aria-hidden="true"></span>
Start conversation
</a>
{ chats }
</div>
</div>
);
},
_getChat: function(chat) {
return <ChatItem key={ chat.id } chat={ chat } />;
},
_getStateFromStores: function() {
return {
chats: ChatStore.getAll()
};
},
_openContactList: function() {
React.render(<ContactList />, document.getElementById('modal'));
},
_onChange: function() {
this.setState(this._getStateFromStores());
}
});
module.exports = ChatList;
<file_sep>from smiegel.queue import CyclicQueue
class Publisher:
"""TODO: documentation"""
def __init__(self):
self.topics = {}
def publish(self, topic, msg):
if topic not in self.topics:
self.topics[topic] = {
'queue': CyclicQueue(),
'subs': []
}
topic = self.topics[topic]
if len(topic['subs']) > 0:
for sub in topic['subs']:
sub.put(msg)
else:
topic['queue'].put(msg)
def subscribe(self, topic, queue):
if topic not in self.topics:
self.topics[topic] = {
'queue': CyclicQueue(),
'subs': []
}
topic = self.topics[topic]
for msg in topic['queue']:
queue.put(msg)
topic['subs'].append(queue)
def unsubscribe(self, topic, queue):
if topic not in self.topics:
return
self.topics[topic]['subs'].remove(queue)
<file_sep>var React = require('react');
var Reflux = require('reflux');
var ChatAction = require('../actions/ChatAction');
var ChatStore = require('../stores/ChatStore');
var ChatInput = React.createClass({
mixins: [Reflux.ListenerMixin],
getInitialState: function() {
return { active: this._haveActiveChat() };
},
componentDidMount: function() {
this.listenTo(ChatStore, this._onChange);
},
_haveActiveChat: function() {
return ChatStore.getCurrentId() !== null;
},
_onChange: function() {
this.setState({ active: this._haveActiveChat() });
},
_onSubmit: function(e) {
e.preventDefault();
var msg = this.refs.text.getDOMNode().value.trim();
// Do nothing on blank messages.
if (msg === '') {
return;
}
ChatAction.createMessage(msg);
this.refs.text.getDOMNode().value = '';
},
render: function() {
if (!this.state.active) {
return (
<div className="inputbox">
<form>
<input disabled
type="text"
className="text-field form-control"
aria-describedby="basic-addon2"
placeholder="Choose or create a chat" />
</form>
</div>
);
}
return (
<div className="inputbox">
<form onSubmit={this._onSubmit}>
<input autofocus
type="text"
ref="text"
className="text-field form-control"
aria-describedby="basic-addon2"
placeholder="Say something" />
</form>
</div>
);
}
});
module.exports = ChatInput;
<file_sep>from smiegel import db
from smiegel.util import generate_auth_token
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
auth_token = db.Column(db.String(32), unique=True)
login_email = db.Column(db.String(256), unique=True)
contacts = db.Column(db.Text)
messages = db.relationship('Message', backref='user', lazy='dynamic')
def __init__(self, login_email, auth_token=None):
self.login_email = login_email
if auth_token is None:
auth_token = generate_auth_token()
self.auth_token = auth_token
<file_sep>var Reflux = require('reflux');
module.exports = Reflux.createActions([
"ackMessage",
"createMessage",
"receiveMessage",
"updateMessageId",
]);
<file_sep>var React = require('react');
var Settings = require('../components/Settings.react');
var Navbar = React.createClass({
_openSettingsPane: function() {
React.render(<Settings />, document.getElementById('modal'));
},
render: function() {
return (
<nav className="navbar navbar-default navbar-static-top">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand">Smiegel</a>
</div>
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul className="nav navbar-nav">
</ul>
<ul className="nav navbar-nav navbar-right">
<li className="dropdown">
<a className="dropdown-toggle"
data-toggle="dropdown"
role="button"
aria-expanded="false">
<span className="glyphicon glyphicon-cog" aria-hidden="true" />
<span className="caret" />
</a>
<ul className="dropdown-menu" role="menu">
<li><a onClick={this._openSettingsPane}>Settings</a></li>
<li className="divider"></li>
<li><a>Sign out</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
);
}
});
module.exports = Navbar;
<file_sep>var React = require('react');
var ChatInput = require('../components/ChatInput.react');
var ChatMessageList = require('../components/ChatMessageList.react');
var ChatStore = require('../stores/ChatStore.js');
var ContactStore = require('../stores/ContactStore.js');
var APIUtil = require('../utils/APIUtil.js');
var ContactList = React.createClass({
getInitialState: function() {
return this._getStateFromStores();
},
componentDidMount: function () {
var that = this;
$('#contact-list').modal('show');
$('#contact-list').on('hidden.bs.modal', function () {
that._onClose();
});
},
componentWillUnmount: function () {
},
render: function () {
var contacts = this.state.contacts.map(this._renderContact);
return (
<div id="contact-list" className="modal fade">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button"
className="close"
data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 className="modal-title">Contacts</h3>
</div>
<div className="modal-body">
<p>
<div className="input-group input-group-lg" id="contact-search">
<span className="input-group-addon glyphicon glyphicon-search"
aria-hidden="true"
id="search-span" />
<input type="text"
ref="contactSearch"
className="form-control typeahead"
placeholder="Find contact."
onKeyUp={this._updateSearch}
aria-describedby="search-span" />
</div>
</p>
<p>
<div className="contact-list-group list-group">
{ contacts }
</div>
</p>
</div>
<div className="modal-footer">
<span className="badge">{ contacts.length }</span> found.
</div>
</div>
</div>
</div>
);
},
_getStateFromStores: function(query) {
return {
contacts: ContactStore.getAllMatching(query || '')
};
},
_selectContactOnClick: function(contact, number) {
var that = this;
return function() { that._selectContact(contact, number); };
},
_selectContact: function(contact, number) {
ChatStore.addChat(number, contact.name);
ChatStore.setCurrentId(number);
$('#contact-list').modal('hide');
},
_renderContact: function(contact) {
var that = this;
var numbers = contact.numbers.map(function(n) {
return (
<p className="list-group-item-text"
onClick={that._selectContactOnClick(contact, n.number)}>
<em>{ n.type }</em> — { n.number }
</p>
);
});
return (
<a href="#"
key={ contact.name + contact.numbers }
className="list-group-item">
<h4 className="list-group-item-heading"> { contact.name } </h4>
{ numbers }
</a>
);
},
_updateSearch: function() {
var query = this.refs.contactSearch.getDOMNode().value;
this.setState(this._getStateFromStores(query));
},
_onClose: function() {
React.unmountComponentAtNode(document.getElementById('modal'));
}
});
module.exports = ContactList;
<file_sep>module.exports = {
EventTypes: {
CONTACTS: "CONTACTS",
CREDENTIALS: "CREDENTIALS",
RECEIVED_MSG: "RECEIVED_MSG",
ACKED_MSG: "ACKED_MSG"
}
};
<file_sep>/**
* Description : This is a jQuery client library for the BrowserID Protocol.
* Created by <NAME> (alexw.me) .
*/
(function ($) {
var options = {
assertion : null,
email : null,
login_button_class : 'browserid-login',
logout_button_class : 'browserid-logout',
onlogin : null,
onfail : null,
onlogout : null,
server : 'login.php'
}
var methods = {
init : function (settings) {
if (typeof settings === 'object'){
$.extend(options, settings);
}
this.addClass(options.login_button_class).on('click.login', _login);
}
}
var _login = function () {
var $el = $(this);
navigator.id.get(function (assertion) {
if (assertion) {
options.assertion = assertion;
//got an assertion, now send it up to the server for verification
_verify_assertion.apply($el);
}else{
if(typeof options.onfail === 'function') {
options.onfail.apply(this);
}
}
});
}
var _logout = function () {
navigator.id.logout();
options.assertion = null;
options.email = null;
$(this).removeClass(options.logout_button_class).removeClass(options.login_button_class);
methods.init.apply($(this));
if(typeof options.onlogout === 'function') {
options.onlogout.apply(this);
}
}
var _verify_assertion = function(){
$.post(options.server, {assertion:options.assertion}, function (data) {
window.location = '/';
});
}
$.fn.browserID = function (method) {
// Method calling logic
if (methods[method]) {
return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
}
}
})(jQuery);
| 886dc2e058e7c7b109f80558e0c52f5942855a5c | [
"Markdown",
"Python",
"JavaScript"
] | 29 | Markdown | erik/smiegel | 34e9d132e241f2db4e96e84295588cd11d7c0164 | ea4e82ea9676465a3b0b52e3fc66097f36e5aba9 |
refs/heads/master | <file_sep># react-native-dropbox-chooser
## What is this?
For more details check out [https://www.dropbox.com/developers/chooser#ios](https://www.dropbox.com/developers/chooser#ios) for an explanation.
## Only Works On Device
This will only work on Device. This will open up a window prompting you to install the Dropbox app on the Simulator.
## Install
`npm install react-native-dropbox-chooser --save`
## Sign up
You'll need to sign up and get an app key from Dropbox.
First go here [https://www.dropbox.com/developers/apps/create](https://www.dropbox.com/developers/apps/create).
* Select "Dropbox API"
* Select what you need access to
* Name your app
* Agree to TOS
* Submit
You'll see a section where it says "App key" and a series of numbers/letters. We'll need this in a second.
## Setup
First off add it to your project. How to link native modules can be found here. [http://facebook.github.io/react-native/docs/linking-libraries-ios.html#content](http://facebook.github.io/react-native/docs/linking-libraries-ios.html#content).
This will use LinkingIOS so we'll need to add this code to your `AppDelegate.m`
At the top of the file you will need to add `#import "RCTLinkingManager.h"`
Should look like
```
#import "AppDelegate.h"
#import "RCTRootView.h"
#import "RCTLinkingManager.h"
```
Then before the `@end` you need to add this code.
```
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [RCTLinkingManager application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
}
```
Explanation can be found here [https://facebook.github.io/react-native/docs/linkingios.html#content](https://facebook.github.io/react-native/docs/linkingios.html#content).
This will now start complaining that `RCTLinkingManager` doesn't exist.
We'll need to add header search paths for the Libraries.
Go to `Build Settings`, find `Header Search Paths`, and add `$(SRCROOT)/../node_modules/react-native/Libraries`. Set it to `recursive`.
Because we are using the chooser we'll need to add the below configuration to the `Info.plist`
What this will allow us to do is throw over the the Dropbox app and have it send us the links back.
```
<key>LSApplicationQueriesSchemes</key>
<array>
<string>dbapi-1</string>
<string>dbapi-3</string>
</array>
```
Now go to the `Info` tab.
At the bottom it will have a section called `URL Types`.
Open it and press the `+`.
Add `db-APPKEYHERE` into the `URL Schemes` input box.
## How to use
Require the module.
```
var DropboxClient = require('react-native-dropbox-chooser');
```
```
componentDidMount() {
DropboxClient.init({
appId: 'YOURAPPIDHERE',
onFiles: this.handleFiles //Callback that receives file(s) when they are selected
});
},
componentWillUnmount() {
DropboxClient.remove(); //Don't forge to remove it
},
```
## Done
We should be good to go!<file_sep>var React = require('react-native');
var FileIcon = require('./FileIcon.js');
var _ = require('lodash');
var {
StyleSheet,
View,
Text,
Image,
} = React;
var DropboxFile = React.createClass({
getDefaultProps() {
return {
file: null,
};
},
render () {
if (!this.props.file) return null;
return (
<View style={styles.container}>
<FileIcon
thumb={_.get(this.props, 'file.thumbnails.200x200')}
type={this.getFileExtension(_.get(this.props, 'file.name'))}
/>
<Text
style={styles.name}
numberOfLines={1}>
{this.props.file.name}
</Text>
</View>
);
},
getFileExtension (name) {
return _.last(name.split('.'));
}
});
var styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
margin: 5,
},
name: {
color: '#666',
}
});
module.exports = DropboxFile;
<file_sep>//
// RNDropboxChooserManager.h
// RNDropboxChooser
//
// Created by <NAME> on 11/12/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
#ifndef RNDropboxChooserManager_h
#define RNDropboxChooserManager_h
#endif /* RNDropboxChooserManager_h */
<file_sep>var React = require('react-native');
var ICON_COLORS = {
'psd': ['#69d0d0', '#41a8a8'],
'pdf': ['#e14b4e', '#dd9698'],
'dxf': ['#23a9db', '#45c7f7'],
'ai' : ['#fdb53f', '#f0592a'],
'zip': ['#81c48f', '#b7dbbe'],
'jpg': ['#f4d17e', '#fdb53f'],
'default': ['#e0dad1', '#bdb9b4'],
};
var {
StyleSheet,
View,
Text,
Image,
} = React;
var FileIcon = React.createClass({
getDefaultProps() {
return {
type: null,
thumb: null,
};
},
render () {
if (!this.props.type) return null;
var thumbElement;
var colors = ICON_COLORS[this.props.type.toLowerCase()] || ICON_COLORS['default'];
var baseStyle = { tintColor: colors[0] };
var cornerStyle = { tintColor: colors[1] };
return (
<View style={styles.container}>
<Image
source={require('./images/file-icon-base.png')}
style={[styles.base, baseStyle]}
/>
<Image
source={require('./images/file-icon-corner.png')}
style={[styles.corner, cornerStyle]}
/>
<Text style={styles.extension}>
{(this.props.type).toUpperCase()}
</Text>
{thumbElement}
</View>
);
}
});
var styles = StyleSheet.create({
container: {
position: 'relative',
width: 40,
height: 50,
marginRight: 5,
flexDirection: 'row',
justifyContent: 'center',
},
base: {
tintColor: '#ccc',
position: 'absolute',
top: 0,
left: 0,
},
corner: {
tintColor: '#00ff00',
position: 'absolute',
top: 0,
left: 25,
backgroundColor: 'transparent',
},
thumb: {
width: 31,
height: 31,
borderRadius: 2,
position: 'absolute',
top: 15,
left: 4,
},
extension: {
backgroundColor: 'transparent',
color: '#fff',
marginTop: 20,
fontSize: 10,
fontWeight: 'bold',
}
});
module.exports = FileIcon;
<file_sep>rootProject.name = 'DropboxChooser'
include ':app'
<file_sep>'use strict';
var React = require('react-native');
var DropboxClient = require('react-native-dropbox-chooser');
var DropboxFile = require('./DropboxFile.js');
var {
AppRegistry,
StyleSheet,
Text,
View,
NativeModules,
TouchableOpacity,
} = React;
var DropboxExample = React.createClass({
getInitialState() {
return {
files: [
{
bytes: 432543,
icon: 'https://www.dropbox.com/static/images/icons64/page_white_picture.png',
is_dir: false,
link: 'https://www.dropbox.com/s/nt59841gty931yp/IMG_6122%202.JPG?dl=0',
name: 'IMG_6122 2.JPG',
thumbnails: {
"64x64": "https://photos-1.dropbox.com/t/2/AAD11Eoyv8MC80FN_8KTpIhuF97HhQctCyQclbUJT6w-5A/12/2163104/jpeg/64x64/1/_/0/4/IMG_6122%202.JPG/CKCDhAEgASACIAMgBCAFIAYgBygCKAc/nt59841gty931yp/AAD-J-e1Gvxj1ILM35Gg5uzqa/IMG_6122%202.JPG",
"200x200": "https://photos-3.dropbox.com/t/2/AAD11Eoyv8MC80FN_8KTpIhuF97HhQctCyQclbUJT6w-5A/12/2163104/jpeg/200x200/1/_/0/4/IMG_6122%202.JPG/CKCDhAEgASACIAMgBCAFIAYgBygCKAc/nt59841gty931yp/AAD-J-e1Gvxj1ILM35Gg5uzqa/IMG_6122%202.JPG",
"640x480": "https://photos-5.dropbox.com/t/2/AAD11Eoyv8MC80FN_8KTpIhuF97HhQctCyQclbUJT6w-5A/12/2163104/jpeg/640x480/1/_/0/4/IMG_6122%202.JPG/CKCDhAEgASACIAMgBCAFIAYgBygCKAc/nt59841gty931yp/AAD-J-e1Gvxj1ILM35Gg5uzqa/IMG_6122%202.JPG",
}
}
],
};
},
componentDidMount() {
DropboxClient.init({
appId: 'YOURAPPSECRETHERE',
onFiles: this.handleFiles
});
},
componentWillUnmount() {
DropboxClient.remove();
},
render () {
var filesElements = this.state.files.map((file)=><DropboxFile file={file} key={file.link} />);
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.handlePress} style={styles.button}>
<Text style={styles.buttonText}>
Add file from Dropbox
</Text>
</TouchableOpacity>
<View style={styles.fileContainer}>
{filesElements}
</View>
</View>
);
},
handlePress(){
DropboxClient.openChooser();
},
handleFiles(files){
var newFiles = [].concat(this.state.files, files);
this.setState({ files: newFiles });
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
fileContainer: {
justifyContent: 'flex-start',
},
button: {
backgroundColor: '#007ee6',
borderRadius: 4,
margin: 10,
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 15,
paddingRight: 15,
},
buttonText: {
color: '#fff',
fontSize: 20,
textAlign: 'center',
},
});
AppRegistry.registerComponent('DropboxChooser', () => DropboxExample);
| c39c4affa8f88c8aa8f7c9e043215c7ebffad0c8 | [
"Markdown",
"C",
"JavaScript",
"Gradle"
] | 6 | Markdown | tinycreative/react-native-dropbox-chooser | d8071a05a739ae4d57398f64eff9e0c910eef1b6 | 3f51d1750e8575e3427d82b7e294c039d7f38dfa |
refs/heads/master | <file_sep>import Vue from 'https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.esm.browser.js'
import { animals, links } from './data.js';
var app = new Vue({
el: '#app',
data: {
nodes: animals,
textElements: {},
linkElements: {},
nodeElements: {},
selectedItem: {
name: "",
neighbors: [],
color:""
}
},
mounted() {
this.generateNodes();
},
computed: {
},
methods: {
generateNodes() {
const width = window.innerWidth / 1.4;
const height = window.innerHeight;
const svg = d3.select('svg')
.attr('width', width)
.attr('height', height);
// STRENGTH & FORCE SIMULATION
const simulation = d3.forceSimulation(animals)
.force('charge', d3.forceManyBody().strength(-100))
.force('center', d3.forceCenter(width / 2, height / 2))
.force('link', d3.forceLink(links)
.id(link => link.id)
.distance(0)
.strength(link => link.strength))
// DRAG AND DROP HANDLER
const dragDrop = d3.drag()
.on('start', node => {
node.fx = node.x
node.fy = node.y
})
.on('drag', node => {
simulation.alphaTarget(0.7).restart()
node.fx = d3.event.x
node.fy = d3.event.y
})
.on('end', node => {
if (!d3.event.active) {
simulation.alphaTarget(0)
}
node.fx = null
node.fy = null
});
this.textElements = svg.append('g')
.selectAll('text')
.data(animals)
.enter().append('text')
.text(node => node.label)
.attr('font-size', 18)
.attr('dx', 15)
.attr('dy', 4);
this.linkElements = svg.append('g')
.selectAll('line')
.data(links)
.enter().append('line')
.attr('stroke-width', 1)
.attr('stroke', '#f95f40');
this.nodeElements = svg.append('g')
.selectAll('circle')
.data(animals)
.enter().append('circle')
.attr('r', 10)
.attr('fill', this.getNodeColor)
.attr('data-id', d => d.id)
.on('click', this.getNodeInfo)
.call(dragDrop)
// THICK SIMULATION
simulation.nodes(animals).on("tick", () => {
this.nodeElements
.attr("cx", node => node.x)
.attr("cy", node => node.y)
this.textElements
.attr("x", node => node.x)
.attr("y", node => node.y);
this.linkElements
.attr('x1', link => link.source.x)
.attr('y1', link => link.source.y)
.attr('x2', link => link.target.x)
.attr('y2', link => link.target.y)
})
this.nodeElements.on('click', this.getNodeInfo);
},
getNodeInfo(e) {
this.selectedItem.name = e.id;
this.selectedItem.color = this.getNodeColor(e);
this.selectNode(e)
},
selectNode(selectedNode) {
const neighbors = this.getNeighbors(selectedNode)
this.selectedItem.neighbors = neighbors;
this.nodeElements
.attr('fill', node => this.getNodeColors(node, neighbors));
this.textElements
.attr('fill', node => this.getTextColor(node, neighbors));
this.linkElements
.attr('stroke', link => this.getLinkColor(selectedNode, link));
},
getNeighbors(node) {
return links.reduce((neighbors, link) => {
if (link.target.id === node.id) {
neighbors.push(link.source.id)
} else if (link.source.id === node.id) {
neighbors.push(link.target.id)
} return neighbors
}, [node.id])
},
getNodeColors(node, neighbors) {
console.log(node.id);
if (node.level === 0) return 'rgb(112, 81, 35)';
if (neighbors.indexOf(node.id)) return node.level === 1 ? 'blue' : 'green';
return node.level === 1 ? 'red' : 'gray';
},
getTextColor(node, neighbors) {
return neighbors.indexOf(node.id) ? 'green' : 'black'
},
getLinkColor(node, link) {
return this.isNeighborLink(node, link) ? 'green' : '#E5E5E5';
},
isNeighborLink(node, link) {
return link.target.id === node.id || link.source.id === node.id
},
getNodeColor(node) {
if (node.level === 0) return 'rgb(112, 81, 35)';
if (node.level === 1) return 'rgb(175, 134, 71)';
if (node.level === 2) return 'rgb(8, 134, 18)';
}
}
})<file_sep>
// function updateData(selectedNode) {
// const neighbors = getNeighbors(selectedNode);
// const newNodes = baseNodes.filter(node => neighbors.indexOf(node.id) > -1 || node.level === 1);
// const diff = {
// removed: nodes.filter(node => newNodes.indexOf(node) === -1),
// added: newNodes.filter(node => nodes.indexOf(node) === -1)
// }
// diff.removed.forEach(node => nodes.splice(nodes.indexOf(node), 1))
// diff.added.forEach(node => nodes.push(node))
// links = baseLinks.filter(link => {
// return link.target.id === selectedNode.id ||
// link.source.id === selectedNode.id
// })
// }
const linkGroup = svg.append('g').attr('class', 'links');
const nodeGroup = svg.append('g').attr('class', 'nodes');
const textGroup = svg.append('g').attr('class', 'texts');
// function updateGraph() {
// // links
// linkElements = linkGroup.selectAll('line').data(links, link => link.target.id + link.source.id)
// linkElements.exit().remove()
// const linkEnter = linkElements.enter().append('line').attr('stroke-width', 1).attr('stroke', 'rgba(50, 50, 50, 0.2)')
// linkElements = linkEnter.merge(linkElements)
// // nodes
// nodeElements = nodeGroup.selectAll('circle').data(animals, node => node.id)
// nodeElements.exit().remove()
// const nodeEnter = nodeElements
// .enter()
// .append('circle')
// .attr('r', 10)
// .attr('fill', node => node.level === 1 ? 'red' : 'gray')
// .call(dragDrop)
// // we link the selectNode method here
// // to update the graph on every click
// .on('click', selectNode)
// nodeElements = nodeEnter.merge(nodeElements)
// // texts
// textElements = textGroup.selectAll('text').data(animals, node => node.id)
// textElements.exit().remove()
// const textEnter = textElements
// .enter()
// .append('text')
// .text(node => node.label)
// .attr('font-size', 15)
// .attr('dx', 15)
// .attr('dy', 4)
// textElements = textEnter.merge(textElements)
// }
// function updateSimulation() {
// updateGraph()
// simulation.nodes(animals).on('tick', () => {
// nodeElements.attr('cx', node => node.x).attr('cy', node => node.y)
// textElements.attr('x', node => node.x).attr('y', node => node.y)
// linkElements
// .attr('x1', link => link.source.x)
// .attr('y1', link => link.source.y)
// .attr('x2', link => link.target.x)
// .attr('y2', link => link.target.y)
// })
// simulation.force('link')
// simulation.restart()
// }
// // last but not least, we call updateSimulation
// // to trigger the initial render
// updateSimulation() | fc5f1f49c6fe4a4735a161dd36b57d7356c6e4d8 | [
"JavaScript"
] | 2 | JavaScript | PawFV/D3-Force-Tree-Graph | 1a876e68b6c42d834f0be9b5a99ac959ed0af212 | 1ea408ac963c04c58d26943abf73500144a03d62 |
refs/heads/master | <file_sep>#%%
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import json
#%%
data = pd.read_excel('./P3PRIB01.xls', sheetname='celková výška sněhu', skiprows=3)
d = data[(data['měsíc'] == 11) | (data['měsíc'] == 12)]
d = d.to_dict(orient='index')
#%%
out = {}
for v in d.values():
if v['rok'] not in out:
out[v['rok']] = []
out[v['rok']].extend(list(v.values())[2:])
for rok in out.values():
del rok[30]
#%%
for rok in out.values():
plt.plot(list(range(0, 61)), rok, color='skyblue', linewidth=0.3)
#%%
with open('snih.js', 'w', encoding='utf-8') as f:
f.write('var snih = ' + json.dumps(out) + ';')
#%%
j = 0
for o in out.values():
x = 0
for v in o[20:31]:
if v > 15:
x = 1
j += x
#%%
j
#%%
(j / len(out)) * 100
#%%
days = []
for i in range(1, 31):
days.append(str(i) + '. 11.')
for i in range(1, 32):
days.append(str(i) + '. 12.')
days
| 564d1575db9487dd54b2de307f4b655b66752e72 | [
"Python"
] | 1 | Python | DataRozhlas/tok-snih | a01b5db8e3734f7323337cd6bc8f83341aa0f1ab | 13fae9919be87c1ba28b5da5fe1986053e690e33 |
refs/heads/master | <repo_name>tozu/ba-2fa-daemon<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>at.fhooe.mc.zubertobias</groupId>
<artifactId>my-app</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>pyx4j-web-snapshot</id>
<url>http://repository.pyx4j.com/maven2-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<dependencies>
<!-- Spark Java Framework -->
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.3</version>
</dependency>
<!-- Jackson - used for JSON parsing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.3</version>
</dependency>
<!-- Commons IO - used for reading Content from a file -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- Diffie Hellman Support - Key exchange -->
<dependency>
<groupId>com.madgag.spongycastle</groupId>
<artifactId>core</artifactId>
<version>1.54.0.0</version>
</dependency>
<dependency>
<groupId>com.madgag.spongycastle</groupId>
<artifactId>prov</artifactId>
<version>1.54.0.0</version>
</dependency>
</dependencies>
</project><file_sep>/src/main/java/models/BTToken.java
package models;
/**
* Created by Tobias on 24.04.2016.
*/
public class BTToken {
private Token[] btTokens;
BTToken() {
}
public static class Token {
private String device;
private String otp;
private String publicKey;
private byte[] IV;
private byte[] salt;
public Token() {
}
public String getDevice() {
return device;
}
public void setDevice(String _device) {
device = _device;
}
public String getOtp() {
return otp;
}
public void setOtp(String _otp) {
otp = _otp;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String _publicKey) {
publicKey = _publicKey;
}
public byte[] getSalt() {
return salt;
}
public void setSalt(byte[] _salt) {
salt = _salt;
}
public byte[] getIV() {
return IV;
}
public void setIV(byte[] IV) {
this.IV = IV;
}
}
public Token[] getBtTokens() {
return btTokens;
}
public void setBtTokens(Token[] btTokens) {
this.btTokens = btTokens;
}
}
<file_sep>/src/main/java/managers/PasswordManager.java
package managers;
import Utils.Encryption;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* Created by Tobias on 7/6/2016.
*/
public class PasswordManager {
private final String pwdFilePath = "./pwd.txt";
private File pwdFile = new File(pwdFilePath);
private Encryption encManager;
private static PasswordManager mInstance;
private String mPwdHash = null;
public static PasswordManager getInstance() {
if (mInstance == null) {
mInstance = new PasswordManager();
}
return mInstance;
}
private PasswordManager() {
loadFile();
encManager = Encryption.getInstance();
}
private boolean loadFile() {
if (!pwdFile.exists()) {
try {
return pwdFile.createNewFile();
} catch (IOException e) {
System.out.println("[ERROR] creating pwd file" + "\n" + e.getMessage());
}
} else {
try {
mPwdHash = FileUtils.readFileToString(pwdFile);
return true;
} catch (IOException e) {
System.out.println("[ERROR] reading pwd file" + "\n" + e.getMessage());
}
}
return false;
}
public boolean savePasswordToFile(String _pwd) {
try {
String pwdHash = encManager.createHASH_SHA256(_pwd);
FileWriter fileWriter = new FileWriter(pwdFile);
fileWriter.write(pwdHash);
fileWriter.close();
return true;
} catch (IOException e) {
System.out.println("[ERROR] writing pwd file" + "\n" + e.getMessage());
}
return false;
}
public String getPasswordHash() {
return mPwdHash;
}
}
<file_sep>/README.md
# ba-2fa-daemon<file_sep>/src/main/java/Utils/JsonUtils.java
package Utils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import java.io.IOException;
public class JsonUtils {
private static final ObjectMapper defaultObjectMapper = new ObjectMapper();
private static volatile ObjectMapper objectMapper = null;
// taken from Play framework (play.libs.Json)
private static ObjectMapper mapper() {
if (objectMapper == null) {
defaultObjectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return defaultObjectMapper;
} else {
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return objectMapper;
}
}
// taken from Play framework (play.libs.Json)
public static JsonNode toJson(final Object data) {
try {
return mapper().valueToTree(data);
} catch (Exception e) {
return null;
}
}
// credit goes to <NAME> (from appmixture.io)
public static <T> T fromJson(String srcJson, Class<T> destType) {
try {
ObjectMapper mapper = new ObjectMapper();
// Note: this is needed to ignore deserialization on certain annotatated properties
mapper.configure(MapperFeature.USE_GETTERS_AS_SETTERS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(srcJson, destType);
} catch (IOException e) {
System.out.println("JsonUtils - fromJson(String, Class<T>) failed\n caught " + e);
}
return null;
}
// credit goes to <NAME> (from appmixture.io)
public static <T> T fromJson(String srcJson, TypeReference<T> destType) {
try {
return new ObjectMapper()
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
.readValue(srcJson, destType);
} catch (IOException e) {
System.out.println("JsonUtils - fromJson(String, TypeReference<T>) failed\n caught " + e);
}
return null;
}
}
<file_sep>/src/main/java/Utils/Encryption.java
package Utils;
import models.BTToken;
import org.spongycastle.util.encoders.Base64;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
public class Encryption {
public enum OSType {
Windows, MacOS, Linux, Other
}
private OSType detectedOS;
private Process process = null;
private String mEncKey;
private int IV_OTP = 1337;
private KeyPair keyPair;
private final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";
private final String KEY_PATH = "./";
private static Encryption mInstance;
static {
Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
}
public static Encryption getInstance() {
if (mInstance == null) {
mInstance = new Encryption();
}
return mInstance;
}
private Encryption() {
if (!loadKeypair(KEY_PATH)) {
System.out.println("Couldn't load keypair...");
RSAKeyGen();
loadKeypair(KEY_PATH);
}
}
public void setEncKey(String _key) {
mEncKey = _key;
}
private String getEncKey() {
return mEncKey;
}
// # OTP Generation
public String createHASH_SHA256(String msg) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashedBytes = digest.digest(msg.getBytes("UTF-8"));
StringBuffer stringBuffer = new StringBuffer();
for (byte hashedByte : hashedBytes) {
stringBuffer.append(Integer.toString((hashedByte & 0xff) + 0x100, 16)
.substring(1));
}
return stringBuffer.toString();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
ex.printStackTrace();
}
return null;
}
public String createHMAC_SHA256(String msg, String keyString) {
String digest = null;
try {
SecretKeySpec key = new SecretKeySpec((keyString).getBytes(StandardCharsets.UTF_8), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(key);
byte[] bytes = mac.doFinal(msg.getBytes(StandardCharsets.US_ASCII));
StringBuilder hash = new StringBuilder();
for (byte aByte : bytes) {
String hex = Integer.toHexString(0xFF & aByte);
if (hex.length() == 1) {
hash.append('0');
}
hash.append(hex);
}
digest = hash.toString(); // Base64.toBase64String(bytes);
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
return digest;
}
// AES-128 (IV randomly from library)
public String encryptAES128(String plaintext, BTToken.Token token) {
try {
byte[] salt = saltGeneration();
token.setSalt(salt);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(getEncKey().toCharArray(), salt, 65536, 256);
SecretKey tmp = keyFactory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters parms = cipher.getParameters();
byte[] iv = parms.getParameterSpec(IvParameterSpec.class).getIV();
token.setIV(iv);
byte[] encrypted = cipher.doFinal(plaintext.getBytes());
return Base64.toBase64String(encrypted);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException | InvalidKeySpecException | InvalidParameterSpecException e) {
e.printStackTrace();
}
return null;
}
public String decryptAES128(String encrypted, BTToken.Token token) {
try {
byte[] iv = token.getIV();
byte[] salt = token.getSalt();
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(getEncKey().toCharArray(), salt, 65536, 256);
SecretKey tmp = keyFactory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
byte[] plain = cipher.doFinal(Base64.decode(encrypted));
return new String(plain);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException | InvalidKeySpecException | InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return null;
}
private byte[] saltGeneration() {
SecureRandom random = new SecureRandom();
return random.generateSeed(8);
}
// RSA
private KeyPair RSAKeyGen() {
System.out.println("...generate new keypair");
keyPair = null;
try {
KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA" /*, PROVIDER */);
System.out.println("provider of keygen: " + keygen.getProvider().getName());
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keygen.initialize(2048, random);
keyPair = keygen.generateKeyPair();
System.out.println("Keys successfully generated");
saveKeypair(KEY_PATH, keyPair);
} catch (NoSuchAlgorithmException e) {
System.out.println("Keys NOT successfully generated");
e.printStackTrace();
}
return keyPair;
}
private boolean saveKeypair(String path, KeyPair _keyPair) {
try {
KeyFactory factory = KeyFactory.getInstance("RSA" /*, PROVIDER */);
X509EncodedKeySpec x509EncodedKeySpec = factory.getKeySpec(_keyPair.getPublic(), X509EncodedKeySpec.class);
String strPub = Base64.toBase64String(x509EncodedKeySpec.getEncoded());
System.out.println("Public Key: " + strPub);
FileOutputStream out = new FileOutputStream(new File(path + "/daemon.pub"));
out.write(strPub.getBytes());
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = factory.getKeySpec(_keyPair.getPrivate(), PKCS8EncodedKeySpec.class);
byte[] bytesPriv = pkcs8EncodedKeySpec.getEncoded();
String strPriv = Base64.toBase64String(bytesPriv);
System.out.println("Private Key: " + strPriv);
Arrays.fill(bytesPriv, (byte) 0);
out = new FileOutputStream(new File(path + "/daemon.priv"));
out.write(strPriv.getBytes());
System.out.println("Saved keypair sucessfully to file");
return true;
} catch (InvalidKeySpecException | NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
System.out.println("Could NOT save keypair sucessfully to file");
return false;
}
}
public PublicKey convertPublicKey(String publicKey) {
PublicKey pubKey = null;
try {
byte[] encodedPB = Base64.decode(publicKey);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encodedPB);
KeyFactory kf = KeyFactory.getInstance("RSA" /*, PROVIDER */);
pubKey = kf.generatePublic(x509EncodedKeySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
return pubKey;
}
private boolean loadKeypair(String path) {
try {
File filePub = new File(path + "/daemon.pub");
FileInputStream fileIn = new FileInputStream(filePub);
byte[] encodedPublicKey = new byte[(int) filePub.length()];
fileIn.read(encodedPublicKey);
fileIn.close();
File filePriv = new File(path + "/daemon.priv");
fileIn = new FileInputStream(filePriv);
byte[] encodedPrivateKey = new byte[(int) filePriv.length()];
fileIn.read(encodedPrivateKey);
fileIn.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] dataEncodedPublicKey = Base64.decode(encodedPublicKey);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(dataEncodedPublicKey);
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
byte[] dataEncodedPrivateKey = Base64.decode(encodedPrivateKey);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(dataEncodedPrivateKey);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Arrays.fill(dataEncodedPrivateKey, (byte) 0);
keyPair = new KeyPair(publicKey, privateKey);
System.out.println("Could load keys successfully");
return true;
} catch (NoSuchAlgorithmException | IOException | InvalidKeySpecException e) {
e.printStackTrace();
System.out.println("Could NOT load keys successfully");
return false;
}
}
public KeyPair getKeyPair() {
return keyPair;
}
public byte[] encryptRSA(String _plain, PublicKey _pubKey) {
final Cipher cipher;
try {
cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, _pubKey);
return cipher.doFinal(_plain.getBytes());
} catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException e) {
e.printStackTrace();
return null;
}
}
public String dectryptRSA(byte[] _encrypted, PrivateKey _privKey) {
final Cipher cipher;
try {
cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, _privKey);
return new String(cipher.doFinal(_encrypted));
} catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException e) {
e.printStackTrace();
return null;
}
}
public byte[] signRSA(String _data, PrivateKey _privKey) {
final Signature signature;
try {
signature = Signature.getInstance("SHA256withRSA" /*, PROVIDER */);
signature.initSign(_privKey);
signature.update(_data.getBytes());
return signature.sign();
} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
e.printStackTrace();
return null;
}
}
public byte[] signRSA(byte[] _data, PrivateKey _privKey) {
final Signature signature;
try {
signature = Signature.getInstance("SHA256withRSA" /*, PROVIDER */);
signature.initSign(_privKey);
signature.update(_data);
return signature.sign();
} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
e.printStackTrace();
return null;
}
}
public boolean verifyRSA(byte[] _data, byte[] _signData, PublicKey _pubKey) {
final Signature signature;
try {
signature = Signature.getInstance("SHA256withRSA" /*, PROVIDER */);
signature.initVerify(_pubKey);
signature.update(_data);
return signature.verify(_signData);
} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
e.printStackTrace();
return false;
}
}
// OTP Generation - WINDOWS
public String generateKeyForWindows() {
return getBiosSN() + //SerialNumber
getMainboardSN() + //SerialNumber
getOSSN() + //SerialNumber
getMemchipPN() + //PartNumber
IV_OTP; //adding random initialization vector
// equals (bios SN + mainboard SN + OS SN + MEMChip (1st) PN) of current device
}
private String getSerialNumber(String device, String searchnumber) {
String serialNumber = "";
try {
process = Runtime.getRuntime().exec("wmic " + device + " get " + searchnumber);
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outStream = process.getOutputStream();
InputStream inStream = process.getInputStream();
try {
outStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
Scanner scanner = new Scanner(inStream);
try {
while (scanner.hasNext()) {
String next = scanner.next();
if ("SerialNumber".equals(next)) {
serialNumber = scanner.next().trim();
break;
} else if ("PartNumber".equals(next)) {
serialNumber = scanner.next().trim();
}
}
} finally {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//System.out.println("Found SN: " + serialNumber);
return serialNumber;
}
private String getBiosSN() {
return getSerialNumber("bios", "serialnumber");
}
private String getMainboardSN() {
return getSerialNumber("baseboard", "serialnumber");
}
private String getOSSN() {
return getSerialNumber("os", "serialnumber");
}
private String getMemchipPN() {
return getSerialNumber("memorychip", "partnumber");
}
// OTP Generation - LINUX
public String generateKeyForLinux() {
// TODO linux
return "";
}
public void incrementIV() {
System.out.println("\t[increment IV]");
IV_OTP += 1;
}
public OSType getOperatingSystemType() {
if (detectedOS == null) {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if ((OS.contains("mac")) || (OS.contains("darwin"))) {
detectedOS = OSType.MacOS;
} else if (OS.contains("win")) {
detectedOS = OSType.Windows;
} else if (OS.contains("nux")) {
detectedOS = OSType.Linux;
} else {
detectedOS = OSType.Other;
}
}
return detectedOS;
}
}<file_sep>/src/main/java/main/Main.java
package main;
import Utils.BTDiscovery;
import Utils.Encryption;
import managers.BTTokenManager;
import managers.BluetoothManager;
import managers.OTPManager;
import managers.PasswordManager;
import models.BTToken;
import org.eclipse.jetty.server.Response;
import spark.Filter;
import spark.Request;
import javax.bluetooth.RemoteDevice;
import java.io.IOException;
import java.util.Scanner;
import java.util.Vector;
import static spark.Spark.*;
public class Main {
private static final String keystoreFile = "keystore.jks";
private static final String truststoreFile = "truststore";
private BTDiscovery btDiscovery;
private BTTokenManager btTokenManager;
private BluetoothManager btManager;
private OTPManager otpManager;
private PasswordManager pwdManager;
private Encryption encManager;
private static int tries = 0;
private static Main cInstance;
private static Main getInstance() {
if (cInstance == null) {
cInstance = new Main();
}
return cInstance;
}
private static void enableCORS(final String origin, final String methods, final String headers) {
options("/*", (request, response) -> {
// Access-Control-Expose-Headers
String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
response.header("Access-Control-Allow-Origin", accessControlRequestHeaders);
}
String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if (accessControlRequestMethod != null) {
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
return "OK";
});
before((request, response) -> {
response.header("Access-Control-Allow-Origin", origin);
response.header("Access-Control-Request-Method", methods);
response.header("Access-Control-Allow-Headers", headers);
response.header("Access-Control-Expose-Headers", "foundBT");
});
}
private Main() {
secure(keystoreFile, "13371337", null, null); // truststoreFile, "changeit");
enableCORS("*", "*", "*");
btDiscovery = BTDiscovery.getInstance();
btTokenManager = BTTokenManager.getInstance();
btManager = BluetoothManager.getInstance();
otpManager = OTPManager.getInstance();
pwdManager = PasswordManager.getInstance();
encManager = Encryption.getInstance();
}
public static void main(String[] args) {
Main BTDaemon = getInstance();
if (BTDaemon.pwdManager.getPasswordHash() == null) {
System.out.println("[SETUP]"
+ "\nPlease enter a password to protect your Daemon and its tokens");
System.out.print("Password: ");
// check on input
Scanner cmdLine = new Scanner(System.in);
String input = cmdLine.nextLine();
while (input.length() <= 0) {
input = cmdLine.nextLine();
}
if (BTDaemon.pwdManager.savePasswordToFile(input)) {
BTDaemon.encManager.setEncKey(input);
} else {
System.out.println("[ERROR] setting up Encryption key");
return;
}
} else {
System.out.println("[SETUP]" + "\nPlease enter the password of the daemon!");
System.out.print("Password: ");
// check on input
Scanner cmdLine = new Scanner(System.in);
String input = cmdLine.nextLine();
while (input.length() <= 0) {
input = cmdLine.nextLine();
}
String hashInput = BTDaemon.encManager.createHASH_SHA256(input);
if (!hashInput.equals(BTDaemon.pwdManager.getPasswordHash())) {
return;
} else {
BTDaemon.encManager.setEncKey(input);
System.out.println("password correct!");
}
}
if (BTDaemon.btTokenManager.getBtTokens().size() == 0) {
BTDaemon.setupNewDevice();
}
// test page
get("/hello", (req, res) -> "Hello World");
get("/addNewDevice", (request, response) -> {
BTDaemon.setupNewDevice();
return "";
});
// scans for nearby BT devices
get("/scanForBT", (req, res) -> {
System.out.println("---- /scanForBT executed");
BTDaemon.btDiscovery.findBTDevices();
return "";
});
// Check if authorized token is nearby
get("/checkForAuthToken", (req, res) -> {
String level = req.queryParams("level");
int lvl = Integer.parseInt(level);
System.out.println("---- /checkForAuthToken executed with Sec. Level: " + lvl);
String hmac = req.queryParams("hmac");
System.out.println("---- /checkForAuthToken with hmac: " + hmac);
if (BTDaemon.checkAuthentication(lvl, hmac)) {
res.header("foundBT", "true");
System.out.println("SUCCESSFUL");
// res.status(Response.SC_OK);
return "SUCCESSFUL";
} else {
res.header("foundBT", "false");
// res.status(Response.SC_BAD_REQUEST);
return "FAIL";
}
});
}
private boolean checkAuthentication(int securityLevel, String clientHMACKey) {
btDiscovery.findBTDevices();
Vector<RemoteDevice> currentBTDevices = btDiscovery.getBTDevices();
RemoteDevice currentBTDevice;
BTToken.Token btToken;
switch (securityLevel) {
case 1:
return btTokenManager.isKnownToken(currentBTDevices);
case 2:
currentBTDevice = btTokenManager.returnDeviceIfKnown(currentBTDevices);
btToken = btTokenManager.getTokenForBTDevice(currentBTDevice);
if (currentBTDevice != null && btToken != null) {
String receivedOTP = btManager.requestFromDevice(currentBTDevice, BluetoothManager.REQUESTS.DAEMON_REQUESTS_OTP);
return otpManager.verifyOTP(currentBTDevice, btToken, receivedOTP);
}
return false;
case 3:
if (clientHMACKey == null) {
return false;
}
currentBTDevice = btTokenManager.returnDeviceIfKnown(currentBTDevices);
btToken = btTokenManager.getTokenForBTDevice(currentBTDevice);
if (currentBTDevice != null && btToken != null) {
String receivedHMAC = btManager.requestFromDevice(currentBTDevice, BluetoothManager.REQUESTS.DAEMON_REQUESTS_HMAC);
return otpManager.verifyHMAC(currentBTDevice, btToken, receivedHMAC, clientHMACKey);
}
return false;
default:
return false;
}
}
private void setupNewDevice() {
System.out.println("---- /Setup");
try {
Vector<RemoteDevice> currentBTDevices;
btDiscovery.findBTDevices();
currentBTDevices = btDiscovery.getBTDevices();
if (currentBTDevices.size() == 0) {
System.out.println("Couldn't find a BT Devices - Retry (" + tries + ")");
while (tries <= 2) {
btDiscovery.findBTDevices();
currentBTDevices = btDiscovery.getBTDevices();
tries++;
if (currentBTDevices.size() == 0) {
System.out.println("Couldn't find a BT Devices - Retry (" + tries + ")");
} else {
// no more looping needed found some
break;
}
}
// tries are over, check the result
if (currentBTDevices.size() == 0) {
System.out.println("Couldn't find a BT Devices - after " + (tries + 1) + " tries");
return;
} else {
// could find a bt device
tries = 1;
}
}
System.out.println("Choose device from List: \n");
int n = 0;
for (RemoteDevice device : currentBTDevices) {
System.out.println((n + 1) + ". " + device.getFriendlyName(false));
n++;
}
System.out.print("Chosen device: ");
Scanner scanner = new Scanner(System.in);
int position;
try {
position = Integer.valueOf(scanner.nextLine());
} catch (NumberFormatException e) {
position = 0;
}
while (position <= 0 || position > currentBTDevices.size()) {
System.out.println("Please enter a VALID Number!");
System.out.print("Chosen device: ");
position = Integer.valueOf(scanner.nextLine());
}
RemoteDevice device = currentBTDevices.elementAt(position - 1);
System.out.println("Choose Level of Security: ");
System.out.print("\t(1) Proximity Auth. only\n");
System.out.print("\t(2) Proximity Auth. + OTP\n");
System.out.print("\t(3) Proximity Auth. + OTP + HMAC\n");
System.out.print("Security Level: ");
int level;
try {
level = Integer.valueOf(scanner.nextLine());
} catch (NumberFormatException e) {
level = 0;
}
while (level <= 0 || level >= 4) {
System.out.println("Please choose a VALID Security Level!");
System.out.print("Security Level: ");
level = Integer.valueOf(scanner.nextLine());
}
scanner.close();
BTToken.Token btToken = new BTToken.Token();
String token = btTokenManager.createEncryptedHashForBTDevice(device.getBluetoothAddress(), btToken);
btToken.setDevice(token);
switch (level) {
case 2:
case 3:
String pb_bt = btManager.requestFromDevice(device, BluetoothManager.REQUESTS.DAEMON_REQUEST_PUBLIC_KEY);
if (pb_bt == null) {
System.out.println("[ERROR] Failure requesting Public Key from BT Device");
break;
} else {
btToken.setPublicKey(pb_bt);
}
String otp = otpManager.createOTP();
if (btManager.sendOTPToDevice(device, otp, btToken)) {
btToken.setOtp(otp);
break;
} else {
System.out.println("could NOT set level 2 security. are you sure it is supported?");
break;
}
default:
break;
}
if (!btTokenManager.saveToken(btToken)) {
System.out.println("ERROR while saving token to file!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}<file_sep>/src/main/java/Utils/BTDiscovery.java
package Utils;
import com.intel.bluetooth.BlueCoveConfigProperties;
import com.intel.bluetooth.BlueCoveImpl;
import javax.bluetooth.*;
import java.io.IOException;
import java.util.Vector;
public class BTDiscovery implements DiscoveryListener {
private Vector<RemoteDevice> mDiscoveredDevices;
private Vector<String> serviceFound;
private UUID my_uuid = new UUID("4e5d48e075df11e3981f0800200c9a66", false);
private Object serviceSearchCompletedEvent = new Object();
private final Object inquiryCompletedEvent = new Object();
private static BTDiscovery mInstance;
public static BTDiscovery getInstance() {
if (mInstance == null) {
mInstance = new BTDiscovery();
}
return mInstance;
}
private BTDiscovery() {
BlueCoveImpl.setConfigProperty(BlueCoveConfigProperties.PROPERTY_CONNECT_TIMEOUT, "5000");
mDiscoveredDevices = new Vector<>();
serviceFound = new Vector<>();
}
public Vector<RemoteDevice> getBTDevices() {
return mDiscoveredDevices;
}
public Vector<String> getServiceFound() {
return serviceFound;
}
public void findBTDevices() {
mDiscoveredDevices.clear();
synchronized (inquiryCompletedEvent) {
boolean started;
try {
started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, this);
if (started) {
System.out.println("wait for device inquiry to complete...");
inquiryCompletedEvent.wait();
}
} catch (BluetoothStateException | InterruptedException e) {
e.printStackTrace();
}
}
}
public void searchServiceForDevice(RemoteDevice _device) {
UUID[] searchUUIDSet = new UUID[]{my_uuid};
int[] attrIDs = new int[]{0x0003};
synchronized (serviceSearchCompletedEvent) {
try {
// System.out.println("search services on: " + _device.getFriendlyName(false) + " (" + _device.getBluetoothAddress() + ")");
LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUUIDSet, _device, this);
serviceSearchCompletedEvent.wait();
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}
// Device search
@Override
public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
try {
mDiscoveredDevices.addElement(remoteDevice);
System.out.println("Device " + remoteDevice.getFriendlyName(false) + " found");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void inquiryCompleted(int discType) {
synchronized (inquiryCompletedEvent) {
System.out.println("Device inquiry completed");
inquiryCompletedEvent.notifyAll();
}
}
// Service search
@Override
public void servicesDiscovered(int transID, ServiceRecord[] serviceRecords) {
serviceFound.clear();
for (ServiceRecord record : serviceRecords) {
String url = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
if (url == null) {
continue;
}
serviceFound.add(url);
DataElement serviceName = record.getAttributeValue(0x0003);
// if (serviceName != null) {
// System.out.println("service " + serviceName.getValue() + " found: " + url);
// //hasOBEXFileTransfer = true;
// } else {
// System.out.println("service found: " + url);
// }
}
}
@Override
public void serviceSearchCompleted(int transID, int respID) {
// System.out.println(" --- serviceSearchCompleted - transID: " + transID + " - respID: " + respID);
synchronized (serviceSearchCompletedEvent) {
serviceSearchCompletedEvent.notifyAll();
}
}
}
| b3449bae2806445438d56beeeb7564292404f171 | [
"Markdown",
"Java",
"Maven POM"
] | 8 | Maven POM | tozu/ba-2fa-daemon | ce3b37add7fcb574cbe171ec7abe866de9afd650 | 85d8eaee9997584d68c086207a655587961a182c |
refs/heads/main | <file_sep>from fastapi import FastAPI
import requests
import json
app=FastAPI()
@app.get('/groups')
def masterList(masterName):
url = 'https://mobius-test.nat.bt.com/cjoc/job/'+masterName.lower()+'/groups/api/json'
querystring = {"tree":"groups[name]"}
headers = {
'authorization': "Basic <KEY>
'cache-control': "no-cache"}
response = requests.request("GET", url, headers=headers, params=querystring)
jsonList=json.loads(response.text)
return jsonList["groups"]
#Add Users to groups
@app.post('/addMembers')
async def addUser(masterName,group,ein):
url = "https://mobius-test.nat.bt.com/cjoc/job/"+masterName.lower()+"/groups/"+group.lower()+"/addMember"
headers = {
'authorization': "Basic <KEY>
'cache-control': "no-cache"}
eins=ein.split(';')
i=0
for number in eins:
querystring = {'name':number}
response = requests.request("POST", url, headers=headers, params=querystring)
i+=1
if(i==len(eins)):
return 200
else:
return 400
@app.post('/createGroup')
def createGroup(masterName,groupName):
url="https://mobius-test.nat.bt.com/cjoc/job/"+masterName+"/groups/createGroup"
headers = {
'authorization': "Basic <KEY>
'cache-control': "no-cache"}
querystring = {'name':groupName}
response = requests.request("POST",url,headers=headers,params=querystring)
return response.text
@app.delete('/removeMember')
async def removeUser(masterName,group,ein):
url = "https://mobius-test.nat.bt.com/cjoc/job/"+masterName.lower()+"/groups/"+group.lower()+"/removeMember"
headers = {
'authorization': "Basic N<KEY>
'cache-control': "no-cache"}
eins=ein.split(';')
i=0
for number in eins:
querystring = {'name':number}
response = requests.request("POST", url, headers=headers, params=querystring)
i+=1
if(i==len(eins)):
return 200
else:
return 400
@app.delete('/deleteGroup')
def deleteGroup(masterName,groupName):
url="https://mobius-test.nat.bt.com/cjoc/job/"+masterName+"/groups/deleteGroup"
headers = {
'authorization': "Basic N<KEY>
'cache-control': "no-cache"}
querystring = {'name':groupName}
response = requests.request("POST",url,headers=headers,params=querystring)
return response.text
<file_sep># fastApiApp
This is a test fast api app
| 16d5909e727324ae648cc3c12ca9f12576027a95 | [
"Markdown",
"Python"
] | 2 | Python | maheedhar132/fastApiApp | eae0332f76dccdecff45a9c289685ab0842b9e62 | f25508dee27ef1a998383a28b7a7f8c6fb3bbe3a |
refs/heads/master | <repo_name>gabeoh/FCND-P01-Backyard-Flyer<file_sep>/backyard_flyer.py
import argparse
import time
from enum import Enum
import numpy as np
from udacidrone import Drone
from udacidrone.connection import MavlinkConnection, WebSocketConnection # noqa: F401
from udacidrone.messaging import MsgID
# Debug message level - 0:None, 1:Critical, 2:Info, 3:Debug, 4:Misc
debug_level = 3
# Define control parameters
mission_altitude = 3.0
mission_box_length = 10.0
velocity_threshold = 0.05
location_threshold = 0.3
class States(Enum):
MANUAL = 0
ARMING = 1
TAKEOFF = 2
WAYPOINT = 3
LANDING = 4
DISARMING = 5
class BackyardFlyer(Drone):
def __init__(self, connection):
super().__init__(connection)
self.target_position = np.array([0.0, 0.0, 0.0])
self.all_waypoints = []
self.in_mission = True
self.check_state = {}
# initial state
self.flight_state = States.MANUAL
self.register_callback(MsgID.LOCAL_POSITION, self.local_position_callback)
self.register_callback(MsgID.LOCAL_VELOCITY, self.velocity_callback)
self.register_callback(MsgID.STATE, self.state_callback)
def local_position_callback(self):
"""
This triggers when `MsgID.LOCAL_POSITION` is received and self.local_position contains new data
"""
self.print_position(msg_level=4)
if self.flight_state == States.TAKEOFF:
if self.is_at_target_location() and self.is_hovering():
self.all_waypoints = self.calculate_box()
self.waypoint_transition()
elif self.flight_state == States.WAYPOINT:
if self.is_at_target_location() and self.is_hovering():
if len(self.all_waypoints) > 0:
self.waypoint_transition()
else:
self.landing_transition()
def velocity_callback(self):
"""
This triggers when `MsgID.LOCAL_VELOCITY` is received and self.local_velocity contains new data
"""
self.print_velocity(msg_level=4)
if self.flight_state == States.LANDING:
if self.is_at_target_location() and self.is_hovering():
self.disarming_transition()
def state_callback(self):
"""
This triggers when `MsgID.STATE` is received and self.armed and self.guided contain new data
"""
if not self.in_mission:
return
if self.flight_state == States.MANUAL:
self.arming_transition()
elif self.flight_state == States.ARMING:
if self.armed:
self.takeoff_transition()
elif self.flight_state == States.DISARMING:
if not self.armed:
self.manual_transition()
def calculate_box(self):
"""
1. Return waypoints to fly a box
"""
n, e, d = self.local_position
waypoints = [
(n + mission_box_length, e, d),
(n + mission_box_length, e + mission_box_length, d),
(n, e + mission_box_length, d),
(n, e, d)
]
return waypoints
def arming_transition(self):
"""
1. Take control of the drone
2. Pass an arming command
3. Set the home location to current position
4. Transition to the ARMING state
"""
print("arming transition")
self.take_control()
self.arm()
print_debug_message("Setting home position")
self.set_home_as_current_position()
self.flight_state = States.ARMING
def takeoff_transition(self):
"""
1. Set target_position altitude to 3.0m
2. Command a takeoff to 3.0m
3. Transition to the TAKEOFF state
"""
print("takeoff transition")
self.target_position[0:3] = self.local_position
self.target_position[2] -= mission_altitude
self.print_position(msg_level=3)
with np.printoptions(precision=3, suppress=True):
print_debug_message("Takeoff Target Position: {}".format(self.target_position), msg_level=2)
self.takeoff(mission_altitude)
self.flight_state = States.TAKEOFF
def waypoint_transition(self):
"""
1. Command the next waypoint position
2. Transition to WAYPOINT state
"""
print("waypoint transition")
if len(self.all_waypoints) < 1:
return
waypoint = self.all_waypoints.pop(0)
self.target_position[0:3] = waypoint
self.print_position(msg_level=3)
with np.printoptions(precision=3, suppress=True):
print_debug_message("Move to Waypoint: {}".format(self.target_position), msg_level=2)
self.cmd_position(self.target_position[0], self.target_position[1], -self.target_position[2], 0.0)
self.flight_state = States.WAYPOINT
def landing_transition(self):
"""
1. Command the drone to land
2. Transition to the LANDING state
"""
print("landing transition")
self.target_position[0:3] = self.local_position[0:3]
self.target_position[2] = 0.0
self.land()
self.flight_state = States.LANDING
def disarming_transition(self):
"""
1. Command the drone to disarm
2. Transition to the DISARMING state
"""
print("disarm transition")
self.disarm()
self.flight_state = States.DISARMING
def manual_transition(self):
"""This method is provided
1. Release control of the drone
2. Stop the connection (and telemetry log)
3. End the mission
4. Transition to the MANUAL state
"""
print("manual transition")
self.release_control()
self.stop()
self.in_mission = False
self.flight_state = States.MANUAL
def start(self):
"""This method is provided
1. Open a log file
2. Start the drone connection
3. Close the log file
"""
print("Creating log file")
self.start_log("Logs", "NavLog.txt")
print("starting connection")
self.connection.start()
print("Closing log file")
self.stop_log()
def is_hovering(self):
return np.linalg.norm(self.local_velocity) < velocity_threshold
def is_at_target_location(self):
return np.linalg.norm(self.local_position - self.target_position) < location_threshold
def print_position(self, msg_level=3):
if msg_level > debug_level:
return
with np.printoptions(precision=3, suppress=True):
print("Local Position: {}".format(self.local_position))
def print_velocity(self, msg_level=3):
if msg_level > debug_level:
return
with np.printoptions(precision=3, suppress=True):
print("Local Velocity: {}".format(self.local_velocity))
def print_debug_message(msg, msg_level=3):
'''
:param msg:
:param msg_level: 1:Critical, 2:Info, 3:Debug, 4:Misc
'''
if msg_level > debug_level:
return
print(msg)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--port', type=int, default=5760, help='Port number')
parser.add_argument('--host', type=str, default='127.0.0.1', help="host address, i.e. '127.0.0.1'")
args = parser.parse_args()
conn = MavlinkConnection('tcp:{0}:{1}'.format(args.host, args.port), threaded=False, PX4=False)
#conn = WebSocketConnection('ws://{0}:{1}'.format(args.host, args.port))
drone = BackyardFlyer(conn)
time.sleep(2)
drone.start()
<file_sep>/README.md
# FCND-P01-Backyard-Flyer
FCND-P01-Backyard-Flyer implements a state machine using event-driven
programming to autonomously fly a unmanned aerial vehicle (UAV) on
simulated environment.
The communication with the UAV is done using MAVLink. This implementation
can be used to control PX4 quadcopter autopilot with little modification.
## File Structure
### Project Source Files
* [`backyard_flyer.py`](backyard_flyer.py) - event-driven program
that autonomously flies UAV for a given mission
## Getting Started
### [Download ZIP](https://github.com/gabeoh/FCND-P01-Backyard-Flyer/archive/master.zip) or Git Clone
```
git clone https://github.com/gabeoh/FCND-P01-Backyard-Flyer.git
```
### Setup Environment
You can set up the environment following
[FCND-Term1-Starter-Kit - Miniconda](https://github.com/udacity/FCND-Term1-Starter-Kit/blob/master/docs/configure_via_anaconda.md).
This will install following packages required to run this application.
- Miniconda
- Python
Packages included through Miniconda:
- [`Matplotlib`](https://matplotlib.org/) - Python 2D plotting library
- [`Jupyter Notebook`](http://jupyter.org/) - Open-source web application
that allows you to create and share documents that contain live code,
equations, visualizations and narrative text
* [`UdaciDrone API`](https://github.com/udacity/udacidrone) - Udacity Drone
Python API, which provides protocol agnostic API for communicating with
a quadcopter
- To update, `pip install --upgrade udacidrone`
* [`Visdom`](https://github.com/facebookresearch/visdom/) - A flexible tool for creating,
organizing, and sharing visualizations of live, rich data
### Using Anaconda
**Activate** the `fcnd` environment:
#### OS X and Linux
```sh
$ source activate fcnd
```
#### Windows
Depending on shell either:
```sh
$ source activate fcnd
```
or
```sh
$ activate fcnd
```
### Download Simulator
- Download Udacity Flying Car Simulator from
[this repository](https://github.com/udacity/FCND-Simulator-Releases/releases)
### Usage
#### Run Backyard Flyer Simulation
First, run _**Backyard Flyer**_ module from Flying Car Simulator.
Then, run the following command to perform the mission flight.
```
$ python backyard_flyer.py
```
#### Log Manual Fly
First, run _**Backyard Flyer**_ module from Flying Car Simulator.
Then, run the following command to perform the mission flight.
```
$ python backyard_flyer.py
```
## Project Report
### State Diagram

### Results
* Simlation Recording
* [FC_BackyardFlyer_Recording_2019-11-14.mp4](results/FC_BackyardFlyer_Recording_2019-11-14.mp4)

* Flight Logs
* [TLog_2019-11-14_01.txt](results/TLog_2019-11-14_01.txt)
### Reference
* [Udacity Backyard Flyer Project Intro](https://github.com/udacity/FCND-Backyard-Flyer)
## License
Licensed under [MIT](LICENSE) License.
| 586fd29e191f3e4d47074a6a7a620b2d3ed80f10 | [
"Markdown",
"Python"
] | 2 | Python | gabeoh/FCND-P01-Backyard-Flyer | 6471f1916c50300dfe0d0d18aaaa98d5aa18adbd | c77e95e4c6affdddc4073a27ef7d2de1b1a5f35f |
refs/heads/master | <file_sep>//routes sauces
//router express
const express = require('express')
const router = express.Router()
//import depuis controllers/sauces
const sauceCtrl = require('../controllers/sauces')
//import depuis les middlewares auth et multer-config
const auth = require('../middleware/auth')//authentification JsonWebToken
const multer = require('../middleware/multer-config')//gestion des images
router.get('/', auth, sauceCtrl.getAllSauces)
router.post('/', auth, multer, sauceCtrl.createSauce)
router.get('/:id', auth, sauceCtrl.getOneSauce)
router.put('/:id', auth, multer, sauceCtrl.modifySauce)
router.delete('/:id', auth, sauceCtrl.deleteSauce)
router.post('/:id/like', auth, sauceCtrl.likeSauce);
module.exports = router
| 9fb24226275c2853a7543079e910189fa6730866 | [
"JavaScript"
] | 1 | JavaScript | vinceny-hub/P6_robert_vincent | ce9cf05f0df1fbca1e577d51fd25c4690e4fec9b | 4146ba267da950ea7bfeebc6f1db993bc2081688 |
refs/heads/master | <file_sep>using Commonality;
using GenController.Uwp.Platform;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace GenController.Uwp
{
/// <summary>
/// Main screen
/// </summary>
/// <remarks>
/// Service Dependencies:
/// * ILogger
/// </remarks>
public sealed partial class MainPage : Page
{
public Portable.ViewModels.MainViewModel VM = new Portable.ViewModels.MainViewModel();
public MainPage()
{
try
{
this.InitializeComponent();
}
catch (Exception ex)
{
ex.Source = "MX0";
Logger?.LogErrorAsync(ex);
VM_ExceptionRaised(this, ex);
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
VM.ExceptionRaised += VM_ExceptionRaised;
App.Current.Tick += App_Tick;
VM.Update();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
VM.ExceptionRaised -= VM_ExceptionRaised;
App.Current.Tick -= App_Tick;
base.OnNavigatedFrom(e);
}
private void VM_ExceptionRaised(object sender, Exception ex)
{
string message = ex.Message;
if (!string.IsNullOrEmpty(ex.Source))
message += $" (Code {ex.Source})";
var ignore = new MessageDialog(message, "SORRY").ShowAsync();
}
private void App_Tick(object sender, object e)
{
VM.Update();
}
private void Button_Settings_Click(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(Screens.Settings));
}
private void Button_Logs_Click(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(Screens.Logs));
}
private void Button_Add_Click(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(Screens.EditSchedule));
}
private void PeriodsView_ItemClick(object sender, ItemClickEventArgs e)
{
Frame.Navigate(typeof(Screens.EditSchedule),e.ClickedItem);
}
private ILogger Logger => Service.TryGet<ILogger>();
}
}
<file_sep>using System;
using Windows.UI.Xaml;
using Commonality.Converters;
namespace GenController.Uwp.Converters
{
public class DefaultToVisibilityConverter : DefaultConverter<Visibility>
{
public DefaultToVisibilityConverter(): base(Visibility.Collapsed, Visibility.Visible)
{}
}
public class DefaultVisibleXaml: XamlValueConverter<DefaultToVisibilityConverter>
{
}
public class DefaultToHiddenConverter : DefaultConverter<Visibility>
{
public DefaultToHiddenConverter(): base(Visibility.Visible, Visibility.Collapsed)
{ }
}
public class DefaultHiddenXaml : XamlValueConverter<DefaultToHiddenConverter>
{
}
}
<file_sep>using Windows.UI.Xaml.Controls;
namespace GenController.Uwp.Platform
{
/// <summary>
/// IoT doesn't have Windows.UI.Popups, so we need this
/// </summary>
public class MessageDialog: ContentDialog
{
public MessageDialog(string message, string title)
{
Title = title;
Content = new TextBlock() { Text = message };
PrimaryButtonText = "OK";
IsPrimaryButtonEnabled = true;
}
}
}
<file_sep>namespace GenController.Portable.Models
{
/// <summary>
/// Defines the hardware interface to the generator
/// </summary>
public interface IGenerator: IVoltage
{
/// <summary>
/// Status of the "Start" output line, true = high
/// </summary>
bool StartOutput { get; set; }
/// <summary>
/// Status of the "Stop" output line, true = high
/// </summary>
bool StopOutput { get; set; }
/// <summary>
/// Status of the "Run" input line, true = high
/// </summary>
bool RunInput { get; }
/// <summary>
/// Status of the "Panel Light" input line, true = high
/// </summary>
bool PanelLightInput { get; }
/// <summary>
/// Status of the "Comms" light on the control board
/// </summary>
bool CommsLight { set; }
/// <summary>
/// Status of the "Warn" light on the control board
/// </summary>
bool WarningLight { set; }
}
}
<file_sep>using System;
using System.Threading.Tasks;
using IotFrosting;
using Commonality;
namespace GenController.Uwp.Platform
{
/// <summary>
/// Wraps the DS3231 controller in an IClock interface so the rest of the system can use it
/// </summary>
class HardwareClock : IClock
{
private DS3231 ds;
public DateTime Now
{
get
{
return ds?.Now ?? DateTime.MinValue;
}
set
{
if (ds != null)
ds.Now = value;
}
}
public static async Task<HardwareClock> Open()
{
var result = new HardwareClock();
result.ds = await DS3231.Open();
return result;
}
public async Task Delay(TimeSpan t)
{
var start = ds.Now;
while (ds.Now - start < t)
{
int ms = Math.Max(20, (int)((ds.Now - start).TotalMilliseconds * 0.9));
await Task.Delay((int)ms);
}
}
public void Tick()
{
ds.Tick();
}
}
}
<file_sep>using Catnap.Server;
using Commonality;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Web.Http;
namespace GenController.Uwp.Controllers
{
/// <summary>
/// Web controller for "logs" page
/// </summary>
/// <remarks>
/// Service Dependencies:
/// * ILogger
/// </remarks>
[RoutePrefix("logs")]
class LogsController : Controller
{
[HttpGet]
[Route]
public async Task<HttpResponse> Get()
{
await Logger?.LogEventAsync("Web.Logs");
var htmlBuilder = new StringBuilder();
htmlBuilder.AppendLine("<html>");
htmlBuilder.AppendLine("<head>");
htmlBuilder.AppendLine("<meta name=\"viewport\" content=\"width=device-width, user-scalable=no\"/>");
htmlBuilder.AppendLine("<style>");
htmlBuilder.AppendLine("body { margin: 0; padding: 0; margin-left: 10px; background-color: rgb(197, 204, 211); -webkit-text-size-adjust:none; }");
htmlBuilder.AppendLine("h1 { margin:0; margin-left: auto; margin-right: auto; width: 350px; padding-top:10px; padding-right:10px; padding-bottom:10px; padding-left:10px; font-size:30px; font-family: Helvetica; font-weight:bold; color: rgb(76,86,108); }");
htmlBuilder.AppendLine("h1 span.big { float:right; }");
htmlBuilder.AppendLine(".button { display: block; line-height: 46px; width: 350px; font-size: 20px; font-weight: bold; font-family: Helvetica, sans-serif; color: #fff; text-decoration: none; text-align: center; margin: 10px auto; }");
htmlBuilder.AppendLine(".red { background-color: red }");
htmlBuilder.AppendLine(".green { background-color: green }");
htmlBuilder.AppendLine("ul { padding: 0; margin-top:0; margin-left: auto; margin-right: auto; margin-bottom:17px; font-size:17px; font-family: Helvetica; font-weight:bold; color:black; width: 350px; background-color: white; border-width: 1px; border-style:solid ; border-color:rgb(217,217,217); -webkit-border-radius: 8px; }");
htmlBuilder.AppendLine("li { list-style-type: none; border-top-width:1px; border-top-style:solid; border-top-color:rgb(217,217,217); padding:10px; }");
htmlBuilder.AppendLine("</style>");
htmlBuilder.AppendLine("</head>");
htmlBuilder.AppendLine("<body>");
htmlBuilder.AppendLine("<h1>Logs</h1>");
htmlBuilder.AppendLine("<ul>");
var logs = FileSystemLogger.GetLogs();
var sorted = logs.ToList();
sorted.Sort((x, y) => y.CompareTo(x));
foreach (var log in sorted)
{
htmlBuilder.AppendLine($"<li><a href=\"logs/log/{log.ToBinary().ToString()}\">{log}</a>");
}
htmlBuilder.AppendLine("</ul>");
htmlBuilder.AppendLine("</body>");
htmlBuilder.AppendLine("</html>");
htmlBuilder.AppendLine();
return new HttpResponse(HttpStatusCode.Ok, htmlBuilder.ToString());
}
[HttpGet]
[Route("log/{param1}")]
public async Task<HttpResponse> WithParam(string param1)
{
long binary = Convert.ToInt64(param1, 16);
DateTime dt = DateTime.FromBinary(binary);
await Logger?.LogEventAsync("Web.GetLog", $"Log={dt}");
var htmlBuilder = new StringBuilder();
htmlBuilder.AppendLine("<html>");
htmlBuilder.AppendLine("<head>");
htmlBuilder.AppendLine("</head>");
htmlBuilder.AppendLine("<body>");
htmlBuilder.AppendLine($"<h1>{dt}</h1>");
var lines = await FileSystemLogger.ReadContents(dt);
foreach(var line in lines)
htmlBuilder.AppendLine($"<p>{line}</p>");
htmlBuilder.AppendLine("</body>");
htmlBuilder.AppendLine("</html>");
htmlBuilder.AppendLine();
return new HttpResponse(HttpStatusCode.Ok, htmlBuilder.ToString());
}
#region Service Locator services
private ILogger Logger => Service.TryGet<ILogger>();
#endregion
}
}
<file_sep>using Commonality;
using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Storage;
namespace GenController.Uwp.Platform
{
/// <summary>
/// Windows platform-specific way to get settings
/// </summary>
public class WindowsSettings : ISettings
{
public IEnumerable<string> GetCompositeKey(string name)
{
List<string> result = new List<string>();
var ApplicationSettings = ApplicationData.Current.LocalSettings.Values;
if (ApplicationSettings.ContainsKey(name))
{
var composite = (ApplicationDataCompositeValue)ApplicationSettings[name];
if (composite.ContainsKey("count"))
{
int count = (int)composite["count"];
for (int i = 0; i < count; i++)
{
result.Add(composite[i.ToString()] as string);
}
}
}
return result;
}
public string GetKey(string key)
{
var ApplicationSettings = ApplicationData.Current.LocalSettings.Values;
string result = null;
if (ApplicationSettings.Keys.Contains(key))
{
result = ApplicationSettings[key] as string;
}
return result;
}
public void SetCompositeKey(string name, IEnumerable<string> values)
{
ApplicationDataCompositeValue composite =
new ApplicationDataCompositeValue();
composite["count"] = values.Count();
int i = 0;
foreach (var value in values)
composite[i++.ToString()] = value;
var ApplicationSettings = ApplicationData.Current.LocalSettings.Values;
if (!ApplicationSettings.Keys.Contains(name))
{
ApplicationSettings.Add(name, composite);
}
else
{
ApplicationSettings[name] = composite;
}
}
public void SetKey(string name, string value)
{
var ApplicationSettings = ApplicationData.Current.LocalSettings.Values;
if (!ApplicationSettings.Keys.Contains(name))
{
ApplicationSettings.Add(name, value);
}
else
{
ApplicationSettings[name] = value;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenController.Portable.Models
{
/// <summary>
/// Describes a period of time during the day when the generator should be on
/// </summary>
public class GenPeriod: IComparable<GenPeriod>
{
/// <summary>
/// Offset from midnight when the generator should start
/// </summary>
public TimeSpan StartAt { get; set; }
/// <summary>
/// Offset from midnight when the generator should stop
/// </summary>
public TimeSpan StopAt { get; set; }
/// <summary>
/// Voltage we should be under for this period to start, or 0.0
/// means "start no matter the voltage"
/// </summary>
public double Voltage { get; set; } = 14.0;
public GenPeriod(TimeSpan start, TimeSpan stop, double voltage)
{
StartAt = start;
StopAt = stop;
Voltage = voltage;
}
public GenPeriod(string serializekey)
{
var split = serializekey.Split(' ');
StartAt = TimeSpan.Parse(split[0]);
StopAt = TimeSpan.Parse(split[1]);
if (split.Length >= 3)
Voltage = double.Parse(split[2]);
}
public string Label => StartAt.ToString("hh\\:mm") + Environment.NewLine + StopAt.ToString("hh\\:mm");
public string SerializeKey => StartAt.ToString("hh\\:mm") + " " + StopAt.ToString("hh\\:mm") + " " + Voltage.ToString("0.0");
public int CompareTo(GenPeriod other)
{
var result = StartAt.CompareTo(other.StartAt);
if (result == 0)
result = StopAt.CompareTo(other.StopAt);
return result;
}
public override bool Equals(object obj)
{
if (!(obj is GenPeriod))
return false;
return 0 == CompareTo(obj as GenPeriod);
}
public override int GetHashCode() => StartAt.GetHashCode() ^ StopAt.GetHashCode();
static public string Serialize(GenPeriod x) => x.SerializeKey;
static public GenPeriod Deserialize(string x) => new GenPeriod(x);
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GenController.Portable.Tests.Mocks;
using GenController.Portable.Models;
using Commonality;
using System.Threading.Tasks;
namespace IotHello.Portable.Tests.Tests
{
[TestClass]
public class RemoteControlTest
{
private RemoteControlLogic RC;
private MockController Controller;
private MockRemoteControlHWI RemoteControlHWI;
[TestInitialize]
public void SetUp()
{
Controller = new MockController();
RemoteControlHWI = new MockRemoteControlHWI();
RC = new RemoteControlLogic(RemoteControlHWI,Controller);
}
[TestMethod]
public void Empty()
{
Assert.IsNotNull(RC);
}
[TestMethod]
public async Task StartFromStopped()
{
await Controller.Stop();
RemoteControlHWI.SetPressed(1, true);
Assert.AreEqual(GenStatus.Confirming, Controller.Status);
}
[TestMethod]
public async Task StopFromRunning()
{
await Controller.Start();
Controller.Confirm();
RemoteControlHWI.SetPressed(2, true);
Assert.AreEqual(GenStatus.Stopped, Controller.Status);
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GenController.Portable.Models;
using System.Collections.Generic;
using System.Linq;
namespace GenController.Portable.Tests.Tests
{
[TestClass]
public class GenPeriodTest
{
[TestMethod]
public void Deserialize()
{
var expected = new GenPeriod(TimeSpan.FromHours(2.5), TimeSpan.FromHours(21.25),0.0);
var serialize = expected.SerializeKey;
var actual = new GenPeriod(serialize);
Assert.AreEqual(expected.StartAt, actual.StartAt);
Assert.AreEqual(expected.StopAt, actual.StopAt);
}
[TestMethod]
public void Bulk()
{
var expected = new List<GenPeriod>();
var current = TimeSpan.FromHours(5);
var period = TimeSpan.FromMinutes(10);
var ending = TimeSpan.FromHours(22);
while (current < ending)
{
expected.Add(new Portable.Models.GenPeriod(current, current + period,0.0));
current += period + period;
}
var storage = expected.Select(GenPeriod.Serialize);
var actual = storage.Select(GenPeriod.Deserialize).ToList();
Assert.AreEqual(expected.Count, actual.Count);
int i = expected.Count;
while (i-- > 0)
{
Assert.AreEqual(expected[i], actual[i]);
}
}
}
}
<file_sep>using IotFrosting.Pimoroni;
using System;
using System.Threading.Tasks;
namespace GenController.Uwp.Platform
{
/// <summary>
/// Controls the actual generator hooked up to real hardware, using a Pimoroni Automation Hat
/// </summary>
public class HardwareGenerator : Portable.Models.IGenerator, IDisposable
{
/// <summary>
/// Reads the 'F' line: Whether the generator is sufficiently primed to start
/// </summary>
public bool PanelLightInput
{
get
{
return Hat.Input[2].State;
}
}
/// <summary>
/// Reads the 'E' line: Whether the generator is running
/// </summary>
public bool RunInput
{
get
{
return Hat.Input[1].State;
}
}
/// <summary>
/// Connects 'C' to 'A' to start the generator
/// </summary>
public bool StartOutput
{
get
{
return Hat.Relay[1].State;
}
set
{
Hat.Relay[1].State = value;
// Also set the output. Testing to see if I can use outputs instead of relays.
Hat.Output[1].State = value;
}
}
/// <summary>
/// Connects 'B' to 'A' to stop the generator
/// </summary>
public bool StopOutput
{
get
{
return Hat.Relay[0].State;
}
set
{
Hat.Relay[0].State = value;
// Also set the output. Testing to see if I can use outputs instead of relays.
Hat.Output[0].State = value;
}
}
/// <summary>
/// Status of the "Comms" light on the control board
/// </summary>
public bool CommsLight
{
set
{
Hat.Light.Comms.State = value;
}
}
/// <summary>
/// Status of the "Warn" light on the control board
/// </summary>
public bool WarningLight
{
set
{
Hat.Light.Warn.State = value;
}
}
/// <summary>
/// Current voltage sensed in the system
/// </summary>
public double Voltage => Hat.Analog[0].Voltage;
protected HardwareGenerator()
{
}
public static async Task<HardwareGenerator> Open()
{
var result = new HardwareGenerator();
result.Hat = await AutomationHat.Open();
// These lights are SO bright! Tone them down a bit
result.Hat.Light.Power.Value = 0.2;
result.Hat.Light.Warn.Value = 0.2;
result.Hat.Light.Comms.Brightness = 0.2;
result.Hat.Light.Power.Value = 0.2;
result.Hat.Relay[0].NO.Light.Brightness = 0.2;
result.Hat.Relay[1].NO.Light.Brightness = 0.2;
result.Hat.Input[1].Light.Brightness = 0.2;
result.Hat.Input[2].Light.Brightness = 0.2;
result.Hat.Output[0].Light.Brightness = 0.2;
result.Hat.Output[1].Light.Brightness = 0.2;
return result;
}
public void Dispose()
{
((IDisposable)Hat).Dispose();
}
private AutomationHat Hat;
}
}
<file_sep>using System;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.System.Threading;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using System.Threading.Tasks;
using Commonality;
using GenController.Portable.Models;
namespace GenController.Uwp
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application, IApplicationInfo
{
/// <summary>
/// Will be raised every second. Attach anything to this you want updated
/// regularly.
/// </summary>
public event EventHandler<object> Tick;
/// <summary>
/// Reference to the singleton app instance
/// </summary>
public static new App Current { get; private set; }
/// <summary>
/// Timer to run scheduled program logic and UI updates
/// </summary>
private DispatcherTimer Timer;
/// <summary>
/// High-resolutoin timer only for hardware timing
/// </summary>
private ThreadPoolTimer HardwareTimer;
/// <summary>
/// The hardware clock we are using to keep time. Null if we are using
/// a software clock
/// </summary>
private Platform.HardwareClock HardwareClock;
/// <summary>
/// Task running our HTTPD server
/// </summary>
private static IAsyncAction ServerTask;
/// <summary>
/// The current schedule we are follwoing
/// </summary>
private static Schedule ScheduleCurrent;
/// <summary>
/// The current logic controller
/// </summary>
public static Controller ControllerCurrent;
private static RemoteControlLogic RemoteControlCurrent;
private Catnap.Server.HttpServer httpServer;
public string Title
{
get
{
var package = Package.Current;
return package?.DisplayName ?? string.Empty;
}
}
public string Version
{
get
{
var package = Package.Current;
var packageid = package?.Id;
var version = packageid?.Version;
var result = string.Empty;
if (version != null)
{
result = $"{version.Value.Major}.{version.Value.Minor}.{version.Value.Build}";
}
return result;
}
}
public ILogger Logger => Service.TryGet<ILogger>();
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
this.Resuming += App_Resuming;
Current = this;
}
private void App_Resuming(object sender, object e)
{
Logger?.LogInfoAsync("Resuming");
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
try
{
var settings = new Platform.WindowsSettings();
Service.Set<ISettings>(settings);
IClock clock = null;
try
{
// Try to create a hardware clock (DS3231), or fall back to no clock
var hc = await Platform.HardwareClock.Open();
hc.Tick();
Service.Set<IClock>(hc);
clock = HardwareClock = hc;
// No logger yet!!
//await Logger?.LogInfoAsync("Hardware clock started.");
}
catch
{
// Nevermind, no hardware clock available
// There is no logger yet!
//await Logger?.LogInfoAsync("Hardware clock failed, using built-in clock.");
// We'll use a software clock instead
Service.Set<IClock>(clock = new Clock(settings));
}
// Set up services to be located by other components
Service.Set<ILogger>(new Portable.Models.FileSystemLoggerWithVoltage(clock,Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\"));
Service.Set<IApplicationInfo>(this);
await Logger.StartSessionAsync();
await Logger.LogInfoAsync($"{Title} {Version}");
try
{
// Try to open a connection to the hardware generator line
var gen = await Platform.HardwareGenerator.Open();
Service.Set<Portable.Models.IGenerator>(gen);
Service.Set<Portable.Models.IVoltage>(gen);
}
catch (Exception)
{
// If there is no hardware generator controller, we'll mock it up in
// sofware. This is helpful for UI and logic testing.
var mg = new Portable.Models.MockGenerator();
Service.Set<Portable.Models.IGenerator>(mg);
Service.Set<Portable.Models.IVoltage>(mg);
}
ScheduleCurrent = new Schedule();
Commonality.Service.Set<ISchedule>(ScheduleCurrent);
ScheduleCurrent.Load();
if (ScheduleCurrent.Periods.FirstOrDefault() == null)
{
var current = TimeSpan.FromHours(5);
var period = TimeSpan.FromHours(2);
var ending = TimeSpan.FromHours(22);
while (current < ending)
{
ScheduleCurrent.Periods.Add(new GenPeriod(current, current + period,0.0));
current += period + period;
}
}
ControllerCurrent = new Controller();
Service.Set<IController>(ControllerCurrent);
// Try to open the hardware remote
try
{
var remote = new Platform.HardwareRemote();
RemoteControlCurrent = new RemoteControlLogic(remote, ControllerCurrent);
}
catch
{
// OK if it fails. We just won't get any inputs from the remote
await Logger.LogInfoAsync("No hardware remote.");
}
Timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
Timer.Tick += Timer_Tick;
Timer.Start();
HardwareTimer = ThreadPoolTimer.CreatePeriodicTimer(HardwareTick, TimeSpan.FromMilliseconds(50));
httpServer = new Catnap.Server.HttpServer(1339);
httpServer.restHandler.RegisterController(new Controllers.StatusController());
httpServer.restHandler.RegisterController(new Controllers.LogsController());
ServerTask =
ThreadPool.RunAsync(async (w) =>
{
try
{
await httpServer.StartServer();
}
catch (Exception ex)
{
ex.Source = "AP3";
if (Logger != null)
await Logger.LogErrorAsync(ex);
}
});
}
catch (Exception ex)
{
ex.Source = "AP2";
if (Logger != null)
await Logger.LogErrorAsync(ex);
}
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
}
/// <summary>
/// Execute the high-resolution timer for hardware timing
/// </summary>
/// <param name="timer"></param>
private void HardwareTick(ThreadPoolTimer timer)
{
ControllerCurrent.FastTick();
}
private async void Timer_Tick(object sender, object e)
{
try
{
HardwareClock?.Tick();
var t = ScheduleCurrent.Tick();
if (t != null)
await t;
this.Tick?.Invoke(this, e);
ControllerCurrent.SlowTick();
}
catch (Exception ex)
{
ex.Source = "AP1";
Logger?.LogErrorAsync(ex);
}
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
e.Exception.Source = "AP4";
Logger?.LogErrorAsync(e.Exception);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
Logger?.LogInfoAsync("Suspending");
deferral.Complete();
}
protected override void OnActivated(IActivatedEventArgs args)
{
Logger?.LogInfoAsync("Activated");
base.OnActivated(args);
}
}
}
<file_sep>using Commonality;
using System;
using System.Windows.Input;
namespace GenController.Portable.ViewModels
{
/// <summary>
/// View model for use with the settings screen
/// </summary>
/// <remarks>
/// Service Dependencies:
/// * IClock
/// * ILogger
/// </remarks>
public class SettingsViewModel: ViewModelBase
{
public SettingsViewModel(): base(Service.TryGet<ILogger>())
{
}
/// <summary>
/// DateTime currently being edited
/// </summary>
public DateTime DT
{
get
{
return Clock.Now + Delta;
}
set
{
Delta = value - Clock.Now;
}
}
/// <summary>
/// How much we have changed the time since we started
/// </summary>
private TimeSpan Delta = TimeSpan.Zero;
/// <summary>
/// Add time to the DT
/// </summary>
public ICommand AddCommand => new DelegateCommand((x) =>
{
try
{
string what = x as string;
char direction = what[0];
int add = 1;
if (direction == '-')
add = -1;
switch (what.Substring(1))
{
case "year":
DT = DT.AddYears(add);
break;
case "month":
DT = DT.AddMonths(add);
break;
case "day":
DT = DT.AddDays(add);
break;
case "hour":
DT = DT.AddHours(add);
break;
case "minute":
DT = DT.AddMinutes(add);
break;
case "second":
DT = DT.AddSeconds(add);
break;
}
base.SetProperty(nameof(DT));
}
catch (Exception ex)
{
base.SetError("SV1", ex);
}
});
public void Commit()
{
try
{
Clock.Now = DT;
DT = Clock.Now;
}
catch (Exception ex)
{
base.SetError("SV2", ex);
}
}
/// <summary>
/// Service Locator for the clock
/// </summary>
private IClock Clock => Service.TryGet<IClock>();
}
}
<file_sep>using Commonality;
using GenController.Portable.Models;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace GenController.Uwp.Controls
{
/// <summary>
/// A common title bar control so all the screens look the same
/// </summary>
/// <remarks>
/// Uses these services:
/// * IController
/// </remarks>
public sealed partial class TitleBar : UserControl
{
public Controller Controller => App.ControllerCurrent;
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(String), typeof(TitleBar), new PropertyMetadata(string.Empty));
public String Title
{
get { return (String)GetValue(TitleProperty); }
set
{
SetValue(TitleProperty, value);
}
}
public string DisplayTitle
{
get
{
var pagetitle = string.Empty;
if (!string.IsNullOrEmpty(Title))
{
pagetitle = $": {Title}";
}
return $"{ApplicationInfo.Title} {ApplicationInfo.Version}{pagetitle}";
}
}
public TitleBar()
{
this.InitializeComponent();
}
#region Service Locator services
private IApplicationInfo ApplicationInfo => Service.Get<IApplicationInfo>();
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using Windows.ApplicationModel.Background;
using Windows.System.Threading;
using IotFrosting.Pimoroni;
// The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409
namespace GenController.MockHardware
{
public sealed class StartupTask : IBackgroundTask
{
BackgroundTaskDeferral Deferral;
ThreadPoolTimer Timer;
ThreadPoolTimer StopButtonTimer;
ThreadPoolTimer StartButtonTimer;
Input StopButton;
Input StartButton;
DirectLight PanelLight;
DirectLight RunSignalLight;
DirectLight PowerLight;
const int SIGNAL_START = 16;
const int SIGNAL_POWER = 12;
const int SIGNAL_STOP = 7;
const int IN_STOP = 25;
const int IN_START = 24;
const int OUT_RUN = 23;
const int OUT_PANEL = 18;
public void Run(IBackgroundTaskInstance taskInstance)
{
Deferral = taskInstance.GetDeferral();
var StopAutoLight = new DirectLight(SIGNAL_STOP,false) { State = false };
var StartAutoLight = new DirectLight(SIGNAL_START,false) { State = false };
RunSignalLight = new DirectLight(OUT_RUN,false) { State = false };
PanelLight = new DirectLight(OUT_PANEL,false) { State = false };
PowerLight = new DirectLight(SIGNAL_POWER,false) { State = true };
StopButton = new Input(IN_STOP,StopAutoLight,false);
StopButton.Updated += (s, e) =>
{
// If pressed
if (StopButton.State == false)
{
RunSignalLight.State = false;
PanelLight.State = false;
StopButtonTimer = ThreadPoolTimer.CreateTimer((a) =>
{
PanelLight.State = true;
}, TimeSpan.FromSeconds(5));
}
else
{
if (StopButtonTimer != null)
{
StopButtonTimer.Cancel();
StopButtonTimer = null;
}
}
};
StartButton = new Input(IN_START,StartAutoLight,false);
StartButton.Updated += (s, e) =>
{
// If pressed
if (StartButton.State == false)
{
StartButtonTimer = ThreadPoolTimer.CreateTimer((a) =>
{
RunSignalLight.State = true;
PanelLight.State = true;
}, TimeSpan.FromSeconds(5));
}
else
{
if (StartButtonTimer != null)
{
StartButtonTimer.Cancel();
StartButtonTimer = null;
}
}
};
Timer = ThreadPoolTimer.CreatePeriodicTimer(Tick, TimeSpan.FromMilliseconds(100));
}
private void Tick(ThreadPoolTimer timer)
{
// Maintain the autolight for the start/stop buttons
StopButton.Tick();
StartButton.Tick();
}
}
}
<file_sep># GenController.Portable
This project contains all the application logic in a portable class library.
Where possible, I've put as much as I can into this portable project.
This has two benefits:
1. Makes it easier to port to another platform
1. Makes it possible to run unit tests using the .NET Framework which is MUCH FASTER than Windows
unit tests.<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Commonality;
namespace GenController.Portable.Models
{
/// <summary>
/// Specialized version of the file system logger, which outputs
/// the current voltage to each logged line
/// </summary>
public class FileSystemLoggerWithVoltage: FileSystemLogger
{
public FileSystemLoggerWithVoltage(IClock clock, string homedir = null): base(clock, homedir)
{
}
protected override string FormattedLine(string originalline) => Time.ToString("u") + " " + VoltageStr + originalline;
private string VoltageStr => Voltage?.Voltage.ToString("0.0") + "V " ?? string.Empty;
private IVoltage Voltage => Service.TryGet<IVoltage>();
}
}
<file_sep>using Commonality;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GenController.Portable.Models
{
/// <summary>
/// The overall schedule of the generator, containing all the schedule blocks
/// </summary>
/// <remarks>
/// Service Dependencies:
/// * ILogger
/// * IClock
/// * ISettings
/// * IController
/// </remarks>
public class Schedule : ISchedule
{
/// <summary>
/// The actual schedule blocks
/// </summary>
private RangeObservableCollection<GenPeriod> _Periods { get; } = new RangeObservableCollection<GenPeriod>();
public IObservableCollection<GenPeriod> Periods => _Periods;
/// <summary>
/// Schedule is free to start and stop generator according to schedule
/// </summary>
public bool Enabled
{
get
{
return Boolean.Parse(Settings.GetKey("Enabled") ?? "True");
}
set
{
Settings.SetKey("Enabled", value.ToString());
}
}
public Schedule()
{
_Periods.CollectionChanged += Periods_CollectionChanged;
}
/// <summary>
/// Load schedule from storage
/// </summary>
public void Load()
{
var storage = Settings.GetCompositeKey("Schedule");
_Periods.AddRange(storage.Select(GenPeriod.Deserialize));
Logger?.LogEventAsync("Schedule.Loaded", $"Schedule={string.Join(",",storage)}");
}
/// <summary>
/// Call this regularly to test the schedule to see if it's time to change
/// state.
/// </summary>
/// <remarks>
/// This method is the heart of the entire application logic. The whole purpose
/// to the app is to start and stop the generator based on a set schedule.
/// Here is where we do that.
/// </remarks>
public Task Tick()
{
// If tehre is no clock yet, we can't do anything
if (Clock == null)
return null;
Task result = null;
var now = Clock.Now;
var elapsed = now - LastTick;
var status = Controller.Status;
// Managed failed starts
if (status == GenStatus.Confirming)
{
// Confirm whether the generator is running now
Controller.Confirm();
// If this is the first we've heard about it, start the timer
if (StartedConfirmingAt == null)
StartedConfirmingAt = now;
else
{
var elapsedfailed = now - StartedConfirmingAt;
if (elapsedfailed > TimeSpan.FromMinutes(2))
{
// Try again!!
Log("Schedule.RetryStart");
StartedConfirmingAt = null;
result = Controller.Start();
}
}
}
else if (StartedConfirmingAt != null)
{
Log("Schedule.ConfirmedStart");
StartedConfirmingAt = null;
}
// Don't take action if we are currently TRYING to start or stop
if (status != GenStatus.Starting && status != GenStatus.Stopping && status != GenStatus.Confirming && status != GenStatus.Initializing && Enabled)
{
// First, figure out what should be happening right now.
var found = InternalSchedule.BinarySearch(new ScheduleItem() { Time = now.TimeOfDay });
if (found < 0)
found = (~found) - 1;
var item = InternalSchedule[found];
var desiredstate = item.DesiredState;
// If the desired state is 'invalid', then we are in a schedule override mode, so we are ignoring
// the schedule as long as that lasts.
if (desiredstate != status && desiredstate != GenStatus.Invalid)
{
if (_Override != null)
{
_Override = null;
Periods_CollectionChanged();
}
// Take action!!
if (desiredstate == GenStatus.Running)
{
// If we want to start, let's check the voltage levels to understand what we need
if (item.Voltage < 1.0 || Controller.Voltage < item.Voltage)
{
Log("Schedule.Start");
result = Controller.Start();
}
}
else if (desiredstate == GenStatus.Stopped)
{
Log("Schedule.Stop");
result = Controller.Stop();
}
}
}
return result;
}
/// <summary>
/// Replaces the given old scehdule with the provided replacement
/// </summary>
/// <exception cref="System.ArgumentException">
/// Thrown if replacing this would cause overlapping schedules
/// </exception>
/// <param name="old"></param>
/// <param name="replacement"></param>
public void Replace(GenPeriod old, GenPeriod replacement)
{
if (replacement.StartAt < TimeSpan.Zero || replacement.StartAt >= TimeSpan.FromDays(1) ||
replacement.StopAt < TimeSpan.Zero || replacement.StartAt >= TimeSpan.FromDays(1))
{
throw new ArgumentException("Invalid start or stop time", nameof(replacement));
}
if (replacement.StopAt - replacement.StartAt < TimeSpan.FromMinutes(30))
throw new ArgumentException("Generator must run at least 30 minutes", nameof(replacement));
var proposed = Periods.ToList();
if (old != null)
proposed.Remove(old);
proposed.Add(replacement);
proposed.Sort();
TimeSpan laststop = TimeSpan.FromDays(-1);
foreach(var p in proposed)
{
if (p.StartAt < laststop)
throw new ArgumentException("Replacement period overlaps an existing period", nameof(replacement));
if (p.StartAt - laststop < TimeSpan.FromMinutes(30))
throw new ArgumentException("Generator must wait 30 minutes before starting again", nameof(replacement));
laststop = p.StopAt;
}
_Periods.Clear();
_Periods.AddRange(proposed);
Settings.SetCompositeKey("Schedule",Periods.Select(GenPeriod.Serialize));
}
/// <summary>
/// Add this block to the schedule
/// </summary>
/// <param name="item"></param>
public void Add(GenPeriod item) => Replace(null, item);
/// <summary>
/// Override the schedule until the next scheduled start time
/// </summary>
public void Override()
{
// If tehre is no clock yet, we can't do anything
if (Clock == null)
return;
_Override = new ScheduleItem() { Time = Clock.Now.TimeOfDay, DesiredState = GenStatus.Invalid };
Periods_CollectionChanged();
}
/// <summary>
/// Remove this block from the schedule
/// </summary>
/// <param name="old"></param>
public void Remove(GenPeriod old)
{
Periods.Remove(old);
Settings.SetCompositeKey("Schedule", Periods.Select(GenPeriod.Serialize));
}
#region Internals
private DateTime LastTick = DateTime.MinValue;
private DateTime? StartedConfirmingAt = null;
private ScheduleItem _Override;
private void Log(string what) => Logger?.LogEventAsync(what);
#endregion
#region Service Locator services
private IClock Clock => Service.TryGet<IClock>();
private ILogger Logger => Service.TryGet<ILogger>();
private ISettings Settings => Service.Get<ISettings>();
private IController Controller => Service.Get<IController>();
#endregion
#region The actual schedule
class ScheduleItem : IComparable<ScheduleItem>, IComparable<TimeSpan>
{
public TimeSpan Time;
public GenStatus DesiredState;
public double Voltage;
public int CompareTo(ScheduleItem other) => Time.CompareTo(other.Time);
public int CompareTo(TimeSpan other) => Time.CompareTo(other);
}
/// <summary>
/// This is a decomposed copy of the schedule periods. It is stored in a format making it
/// easy to test.
/// </summary>
private List<ScheduleItem> InternalSchedule = new List<ScheduleItem>();
/// <summary>
/// When the schedule changes, make sure to update our internal representation of the schedule
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Periods_CollectionChanged(object sender = null, System.Collections.Specialized.NotifyCollectionChangedEventArgs e = null)
{
// Reorganize the schedule into a format that's easy for the scheduler to quickly determine what should be
// happening right now
InternalSchedule.Clear();
if (Periods.FirstOrDefault() != null)
{
InternalSchedule.AddRange(Periods.Select(x => new ScheduleItem() { Time = x.StartAt, DesiredState = GenStatus.Running, Voltage = x.Voltage }));
InternalSchedule.AddRange(Periods.Select(x => new ScheduleItem() { Time = x.StopAt, DesiredState = GenStatus.Stopped }));
if (_Override != null)
InternalSchedule.Add(_Override);
InternalSchedule.Sort();
// Add tomorrow's first at the end, and yesterday's last at the start
var first = InternalSchedule.First();
var last = InternalSchedule.Last();
InternalSchedule.Add(new ScheduleItem() { Time = first.Time + TimeSpan.FromDays(1), DesiredState = first.DesiredState, Voltage = first.Voltage });
InternalSchedule.Insert(0, new ScheduleItem() { Time = last.Time - TimeSpan.FromDays(1), DesiredState = last.DesiredState, Voltage = last.Voltage });
}
}
#endregion
}
}
<file_sep>using System;
using Commonality.Converters;
using Windows.UI.Xaml.Data;
namespace GenController.Uwp.Converters
{
/// <summary>
/// Generic class to convert Portable valueconverters into Xaml-specific valueconverters
/// </summary>
/// <typeparam name="T"></typeparam>
public class XamlValueConverter<T> : IValueConverter where T : IBaseValueConverter, new()
{
T converter = new T();
object IValueConverter.Convert(object value, Type targetType, object parameter, string culture)
=> converter.Convert(value, targetType, parameter);
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, string culture)
=> converter.ConvertBack(value, targetType, parameter);
}
}
<file_sep># GenController.Portable.Models
This folder contains portable models which contain the application's logic.
These are the domain-specific, but platform-agnostic.<file_sep>using System;
using System.Collections.Generic;
using System.Windows.Input;
using Commonality;
using GenController.Portable.Models;
namespace GenController.Portable.ViewModels
{
/// <summary>
/// Viewmodel for the main screen
/// </summary>
/// <remarks>
/// Service Dependencies:
/// * IClock
/// * ISchedule
/// * IController
/// * ILogger
/// </remarks>
public class MainViewModel : ViewModelBase
{
public MainViewModel(): base(Service.TryGet<ILogger>())
{
}
public DateTime CurrentTime => Clock?.Now ?? DateTime.MinValue;
public IController Controller => Service.Get<IController>();
public IObservableCollection<Models.GenPeriod> Periods => Schedule.Periods;
public ICommand StartCommand => new DelegateCommand(async _ =>
{
try
{
Schedule.Override();
await Controller.Start();
}
catch (Exception ex)
{
base.SetError("MV1", ex);
}
});
public ICommand StopCommand => new DelegateCommand(async _ =>
{
try
{
Schedule.Override();
await Controller.Stop();
}
catch (Exception ex)
{
base.SetError("MV2", ex);
}
});
public ICommand EnableCommand => new DelegateCommand(_ =>
{
try
{
Controller.Enabled = true;
}
catch (Exception ex)
{
base.SetError("MV4", ex);
}
});
public ICommand DisableCommand => new DelegateCommand(_ =>
{
try
{
Controller.Enabled = false;
}
catch (Exception ex)
{
base.SetError("MV5", ex);
}
});
public void Update()
{
try
{
base.SetProperty((nameof(CurrentTime)));
}
catch (Exception ex)
{
base.SetError("MV3", ex);
}
}
private IClock Clock => Service.TryGet<IClock>();
private ISchedule Schedule => Service.Get<ISchedule>();
}
}
<file_sep>using Commonality;
using GenController.Uwp.Platform;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace GenController.Uwp.Screens
{
/// <summary>
/// Screen view for settings page
/// </summary>
/// <remarks>
/// Service Dependencies:
/// * ILogger
/// </remarks>
public sealed partial class Settings : Page
{
public Portable.ViewModels.SettingsViewModel VM { get; } = new Portable.ViewModels.SettingsViewModel();
public Settings()
{
try
{
this.InitializeComponent();
}
catch (Exception ex)
{
ex.Source = "SX0";
Logger?.LogErrorAsync(ex);
VM_ExceptionRaised(this, ex);
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
VM.ExceptionRaised += VM_ExceptionRaised;
Logger?.LogEventAsync("Screen.Settings");
App.Current.Tick += App_Tick;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
VM.ExceptionRaised -= VM_ExceptionRaised;
App.Current.Tick -= App_Tick;
base.OnNavigatedFrom(e);
}
private void VM_ExceptionRaised(object sender, Exception ex)
{
string message = ex.Message;
if (!string.IsNullOrEmpty(ex.Source))
message += $" (Code {ex.Source})";
var ignore = new MessageDialog(message, "SORRY").ShowAsync();
}
private void App_Tick(object sender, object e)
{
Bindings.Update();
}
private void Back_Button_Click(object sender, RoutedEventArgs e)
{
Frame.GoBack();
}
private void OK_Button_Click(object sender, RoutedEventArgs e)
{
VM.Commit();
Logger?.LogEventAsync("Time.Set", $"Time={VM.DT}");
Frame.GoBack();
}
private ILogger Logger => Service.TryGet<ILogger>();
}
}
<file_sep>using GenController.Portable.Models;
using System;
namespace GenController.Portable.Tests.Mocks
{
public class MockRemoteControlHWI : IRemote
{
public bool IsPressed(int line)
{
if (line < 1 || line > 4)
throw new ArgumentException("Argument out of range", nameof(line));
return LineStatus[line-1];
}
public void SetPressed(int line,bool value)
{
if (line < 1 || line > 4)
throw new ArgumentException("Argument out of range", nameof(line));
if (value != LineStatus[line-1])
{
LineStatus[line - 1] = value;
LineChanged.Invoke(this, line);
}
}
public event EventHandler<int> LineChanged;
private bool[] LineStatus = new bool[] { false, false, false, false };
}
}
<file_sep>using Commonality;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GenController.Portable.Models
{
public interface ISchedule
{
IObservableCollection<GenPeriod> Periods { get; }
bool Enabled { get; set; }
void Add(GenPeriod item);
void Load();
void Override();
void Remove(GenPeriod old);
void Replace(GenPeriod old, GenPeriod replacement);
Task Tick();
}
}<file_sep>using Commonality;
using System;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace GenController.Uwp.Screens
{
/// <summary>
/// Screen for Edit Schedule page
/// </summary>
/// <remarks>
/// Service Dependencies:
/// * ILogger
/// </remarks>
public sealed partial class EditSchedule : Page
{
Portable.ViewModels.EditScheduleViewModel VM = new Portable.ViewModels.EditScheduleViewModel();
private string Purpose => VM.WillAdd ? "Add Schedule Block" : "Edit Schedule";
public EditSchedule()
{
try
{
this.InitializeComponent();
}
catch (Exception ex)
{
ex.Source = "EX0";
Logger?.LogErrorAsync(ex);
VM_ExceptionRaised(this, ex);
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
VM.ExceptionRaised += VM_ExceptionRaised;
if (e.Parameter != null && e.Parameter is Portable.Models.GenPeriod)
{
VM.Original = e.Parameter as Portable.Models.GenPeriod;
}
Logger?.LogEventAsync("Screen.EditSchedule", $"Add={VM.WillAdd}");
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
VM.ExceptionRaised -= VM_ExceptionRaised;
base.OnNavigatedFrom(e);
}
private void VM_ExceptionRaised(object sender, Exception ex)
{
string message = ex.Message;
if (!string.IsNullOrEmpty(ex.Source))
message += $" (Code {ex.Source})";
var ignore = new MessageDialog(message, "SORRY").ShowAsync();
}
private void Back_Button_Click(object sender, RoutedEventArgs e)
{
Frame.GoBack();
}
private void OK_Button_Click(object sender, RoutedEventArgs e)
{
try
{
VM.Commit();
Logger?.LogEventAsync("Schedule.Commit", $"Start={VM.Period.SerializeKey}",$"Delete={VM.WillDelete}");
Frame.GoBack();
}
catch (Exception ex)
{
Logger?.LogEventAsync("Schedule.CommitFailed",$"Reason={ex.Message}");
var ignore = new MessageDialog(ex.Message, "SORRY").ShowAsync();
}
}
private ILogger Logger => Service.TryGet<ILogger>();
}
}
<file_sep># GenController.Portable.ViewModels
This folder contains portable viewmodels which contain the application's interface between the
user and the logic.
These are the domain-specific, but platform-agnostic.
There is one ViewModel for each screen shown to the user. This approach keeps application-specific data
and logic out of the platform-specific app.<file_sep>using Commonality;
using GenController.Portable.ViewModels;
using GenController.Uwp.Platform;
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace GenController.Uwp.Screens
{
/// <summary>
/// Log viewer screen
/// </summary>
/// <remarks>
/// Service Dependencies:
/// * ILogger
/// </remarks>
public sealed partial class Logs : Page
{
public LogsViewModel VM { get; } = new LogsViewModel();
public Logs()
{
try
{
this.InitializeComponent();
}
catch (Exception ex)
{
ex.Source = "LX0";
Logger?.LogErrorAsync(ex);
VM_ExceptionRaised(this, ex);
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
Logger?.LogEventAsync("Screen.Logs");
var ignore = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
VM.Load();
await Task.Delay(200);
await VM.SelectSession(VM.Sessions.First());
});
VM.ExceptionRaised += VM_ExceptionRaised;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
VM.ExceptionRaised -= VM_ExceptionRaised;
base.OnNavigatedFrom(e);
}
private void VM_ExceptionRaised(object sender, Exception ex)
{
string message = ex.Message;
if (!string.IsNullOrEmpty(ex.Source))
message += $" (Code {ex.Source})";
var ignore = new MessageDialog(message, "SORRY").ShowAsync();
}
private async void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
var dt = e?.ClickedItem as DateTime?;
if (dt.HasValue == true)
await VM.SelectSession(dt.Value);
}
private void Back_Button_Click(object sender, RoutedEventArgs e)
{
Frame.GoBack();
}
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var lv = sender as ListView;
if (e.AddedItems?.FirstOrDefault() != null)
{
lv.ScrollIntoView(e.AddedItems.First());
}
}
private ILogger Logger => Service.TryGet<ILogger>();
}
}
<file_sep>namespace GenController.Portable.Models
{
/// <summary>
/// Use this if you don't have generator hardware hooked up
/// </summary>
public class MockGenerator : IGenerator
{
public bool PanelLightInput { get; set; }
public bool RunInput { get; set; }
public bool StartOutput
{
get
{
return _StartOutput;
}
set
{
_StartOutput = value;
if (value)
RunInput = true;
}
}
private bool _StartOutput;
public bool StopOutput
{
get
{
return _StopOutput;
}
set
{
_StopOutput = value;
if (_StopOutput)
{
RunInput = false;
PanelLightInput = true;
}
else
PanelLightInput = false;
}
}
public bool CommsLight { get; set; } = false;
public bool WarningLight { get; set; } = true;
public double Voltage { get; set; } = 13.9;
private bool _StopOutput;
}
}
<file_sep>namespace GenController.Portable.Models
{
/// <summary>
/// Defines a platform-dependent service to retrieve the current system voltage
/// </summary>
public interface IVoltage
{
double Voltage { get; }
}
}
<file_sep>using Commonality;
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
namespace GenController.Portable.Models
{
/// <summary>
/// Provides a logical interface to the generator
/// </summary>
/// <remarks>
/// The hardware interface to the generator is found in an IGenerator.
/// This should already be set in the service locator.
/// However, if there is no IGenerator (perhaps because the app is running
/// natively with no actual GPIO), this class will simply maintain
/// what the status would be.
///
/// Service Dependencies:
/// * ILogger
/// * IClock
/// * IGenerator
/// * ISchedule
///
/// </remarks>
public class Controller : IController, INotifyPropertyChanged, IVoltage
{
public GenStatus Status
{
get
{
return _Status;
}
private set
{
_Status = value;
DoPropertyChanged(nameof(Status));
Logger?.LogEventAsync(_Status.ToString());
if (Generator != null)
{
Generator.WarningLight = GenStatus.Initializing == value;
Generator.CommsLight = GenStatus.Starting == value || GenStatus.Stopping == value;
}
if (value == GenStatus.Initializing)
{
StartedAt = null;
}
}
}
private GenStatus _Status = GenStatus.Initializing;
public async Task Start()
{
// Already running? Don't do another stop/start cycle
if (Status == GenStatus.Running && RunSignal)
return;
// Already processing a starting/stopping operation? Or disabled? Skip it
if (Status == GenStatus.Starting || Status == GenStatus.Stopping || Status == GenStatus.Initializing)
return;
// If tehre is no clock yet, we can't do anything
if (Clock == null)
return;
Status = GenStatus.Starting;
StopLine = true;
await Clock.Delay(StopPinHighDuration);
StopLine = false;
await Clock.Delay(DelayBetweenStartAndStop);
StartLine = true;
await Clock.Delay(StartPinHighDuration);
StartLine = false;
Status = GenStatus.Confirming;
}
public async Task Stop()
{
// Already processing a starting/stopping operation? Or Disabled? Skip it
if (Status == GenStatus.Starting || Status == GenStatus.Stopping || Status == GenStatus.Initializing)
return;
// If tehre is no clock yet, we can't do anything
if (Clock == null)
return;
Status = GenStatus.Stopping;
StopLine = true;
await Clock.Delay(StopPinHighDuration);
StopLine = false;
Status = GenStatus.Stopped;
}
/// <summary>
/// Generator should be running, let's check on it
/// </summary>
public void Confirm()
{
if (Status == GenStatus.Confirming && RunSignal)
Status = GenStatus.Running;
}
/// <summary>
/// Whether the schedule is enabled
/// </summary>
/// <remarks>
/// This is kept here for simplicity because all other system status is here.
/// TODO: Unfortunately, this makes for a cyclic dependency between schedule and controller.
/// Will need to refactor the users of this.
/// </remarks>
public bool Enabled
{
get
{
return Schedule.Enabled;
}
set
{
Schedule.Enabled = value;
DoPropertyChanged(nameof(Enabled));
}
}
#region Hardware Interface
// See wiring and timing diagram here:
// http://www.magnum-dimensions.com/sites/default/files/MagAGS/ME-AGS-Onan-Models-HGJAD-HGJAE-HGJAF-Rev-12-02-08.pdf
private readonly TimeSpan StopPinHighDuration = TimeSpan.FromSeconds(10);
private readonly TimeSpan StartPinHighDuration = TimeSpan.FromSeconds(10);
private readonly TimeSpan DelayBetweenStartAndStop = TimeSpan.FromSeconds(4);
private readonly TimeSpan DelayBetweenStartAttempts = TimeSpan.FromMinutes(2);
private readonly TimeSpan DelayBetweenStartAndCheck = TimeSpan.FromSeconds(10);
/// <summary>
/// Controls the hardware output pin to close the 'stop' line to the generator
/// </summary>
public bool StopLine
{
get { return Generator?.StopOutput ?? false; }
private set
{
if (null != Generator && value != Generator.StopOutput)
{
Generator.StopOutput = value;
DoPropertyChanged(nameof(StopLine));
}
}
}
/// <summary>
/// Controls the hardware output pin to close the 'start' line to the generator
/// </summary>
public bool StartLine
{
get { return Generator?.StartOutput ?? false; }
private set
{
if (null != Generator && value != Generator.StartOutput)
{
Generator.StartOutput = value;
DoPropertyChanged(nameof(StartLine));
}
}
}
/// <summary>
/// The hardware input line coming from the generator indicating the generator
/// is running
/// </summary>
public bool RunSignal => Generator?.RunInput ?? false;
/// <summary>
/// The hardware input line coming from the generator indicating the generator
/// panel light should be lit
/// </summary>
public bool PanelLightSignal => Generator?.PanelLightInput ?? false;
/// <summary>
/// Current voltage on the "voltage sense" line
/// </summary>
/// <remarks>
/// Rounded to the lowest tenth of a volt, for display purposes
/// </remarks>
public double Voltage => Math.Floor((Generator?.Voltage ?? 0.0) * 10.0) / 10.0;
/// <summary>
/// Call this very frequently. This will debounce the runsignal line. It looks for
/// 31 consecutive readings opposite the previous reading.
/// </summary>
/// <remarks>
/// This is a very conservative approach. While the underlying GPIO pin has debounce
/// as well, we want a really CERTAIN indication that the run signal is changed.
/// This smooths out variance which can exist in the hostile environment where the
/// generator operates.
/// </remarks>
public void FastTick()
{
RunSignalBits <<= 1;
RunSignalBits |= (RunSignal ? 1u : 0);
if (RunSignalBits == SignalOffEdge || RunSignalBits == SignalOnEdge)
DoPropertyChanged(nameof(RunSignal));
PanelLightSignalBits <<= 1;
PanelLightSignalBits |= (PanelLightSignal ? 1u : 0);
if (PanelLightSignalBits == SignalOffEdge || PanelLightSignalBits == SignalOnEdge)
DoPropertyChanged(nameof(PanelLightSignal));
if (Status == GenStatus.Initializing)
{
if (Clock != null)
{
if (!StartedAt.HasValue)
{
// WARNING: Don't change the clock while initializing!!
StartedAt = Clock.Now;
}
else if (Clock.Now - StartedAt.Value > TimeSpan.FromSeconds(30))
{
Status = RunSignal ? GenStatus.Running : GenStatus.Stopped;
}
}
}
}
/// <summary>
/// Call as often as you update the UI (every second is good)
/// </summary>
public void SlowTick()
{
DoPropertyChanged(nameof(Voltage));
}
private UInt32 RunSignalBits = 0;
private UInt32 PanelLightSignalBits = 0;
private const UInt32 SignalOffEdge = 1u << 31;
private const UInt32 SignalOnEdge = UInt32.MaxValue >> 1;
private DateTime? StartedAt;
#endregion
private SynchronizationContext Context = SynchronizationContext.Current;
#region Service Locator services
private ILogger Logger => Service.TryGet<ILogger>();
private IClock Clock => Service.TryGet<IClock>();
private IGenerator Generator => Service.TryGet<IGenerator>();
private ISchedule Schedule => Service.Get<ISchedule>();
#endregion
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void DoPropertyChanged(string name)
{
if (Context != null)
Context.Post((o) =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}, null);
else
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
#endregion
}
public enum GenStatus { Invalid = 0, Stopped, Starting, Confirming, Running, Stopping, Initializing };
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using GenController.Portable.Tests.Mocks;
using Commonality;
using GenController.Portable.Models;
// Not needed to await here in the tests, because the TestController executes generator control commands
// immediately.
#pragma warning disable 1998
#pragma warning disable 4014
namespace GenController.Portable.Tests.Tests
{
[TestClass]
public class ScheduleTest
{
private MockClock Clock { get; set; }
private MockController Controller;
private Schedule ScheduleCurrent {get;set;}
[TestInitialize]
public void SetUp()
{
ScheduleCurrent = new Schedule();
Service.Set<IClock>(Clock = new MockClock());
Service.Set<ISettings>(new MockSettings());
ScheduleCurrent.Periods.Add(new Models.GenPeriod(TimeSpan.FromHours(7), TimeSpan.FromHours(9),0.0));
ScheduleCurrent.Periods.Add(new Models.GenPeriod(TimeSpan.FromHours(12), TimeSpan.FromHours(14),0.0));
ScheduleCurrent.Periods.Add(new Models.GenPeriod(TimeSpan.FromHours(17), TimeSpan.FromHours(19),0.0));
Controller = new MockController() { Status = Models.GenStatus.Invalid };
Service.Set<IController>(Controller);
}
[TestMethod]
public async Task StartingEdge()
{
Clock.Now = new DateTime(2017, 3, 1, 06, 59, 58);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 07, 00, 01);
ScheduleCurrent.Tick();
Controller.RunSignal = true;
Clock.Now = new DateTime(2017, 3, 1, 07, 00, 02);
ScheduleCurrent.Tick();
Assert.AreEqual(Models.GenStatus.Running, Controller.Status);
}
[TestMethod]
public async Task StoppingEdge()
{
Clock.Now = new DateTime(2017, 3, 1, 08, 59, 58);
ScheduleCurrent.Tick();
Controller.RunSignal = true;
Clock.Now = new DateTime(2017, 3, 1, 09, 00, 01);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 09, 00, 02);
ScheduleCurrent.Tick();
Assert.AreEqual(Models.GenStatus.Stopped, Controller.Status);
}
[TestMethod]
public async Task LastStartingEdge()
{
Clock.Now = new DateTime(2017, 3, 1, 16, 59, 58);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 17, 00, 01);
ScheduleCurrent.Tick();
Controller.RunSignal = true;
Clock.Now = new DateTime(2017, 3, 1, 17, 00, 02);
ScheduleCurrent.Tick();
Assert.AreEqual(Models.GenStatus.Running, Controller.Status);
}
[TestMethod]
public async Task LastStoppingEdge()
{
Clock.Now = new DateTime(2017, 3, 1, 18, 59, 56);
ScheduleCurrent.Tick();
Controller.RunSignal = true;
Clock.Now = new DateTime(2017, 3, 1, 18, 59, 58);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 19, 00, 01);
ScheduleCurrent.Tick();
Assert.AreEqual(Models.GenStatus.Stopped, Controller.Status);
}
[TestMethod]
public async Task Midnight()
{
Clock.Now = new DateTime(2017, 3, 1, 11, 59, 58);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 2, 00, 00, 01);
ScheduleCurrent.Tick();
Assert.AreEqual(Models.GenStatus.Stopped, Controller.Status);
}
[TestMethod]
public async Task DuringPeriodNoChange()
{
Clock.Now = new DateTime(2017, 3, 1, 07, 59, 58);
ScheduleCurrent.Tick();
Controller.RunSignal = true;
Clock.Now = new DateTime(2017, 3, 2, 08, 00, 01);
ScheduleCurrent.Tick();
Assert.AreEqual(Models.GenStatus.Running, Controller.Status);
}
[TestMethod]
public async Task StartingEdgeFails()
{
Clock.Now = new DateTime(2017, 3, 1, 06, 59, 58);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 07, 00, 01);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 07, 00, 02);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 07, 01, 03);
ScheduleCurrent.Tick();
Assert.AreEqual(Models.GenStatus.Confirming, Controller.Status);
}
[TestMethod]
public async Task StartingEdgeFailsAndRetries()
{
Clock.Now = new DateTime(2017, 3, 1, 06, 59, 58);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 07, 00, 01);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 07, 00, 02);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 07, 02, 03);
ScheduleCurrent.Tick();
Controller.RunSignal = true;
Clock.Now = new DateTime(2017, 3, 1, 07, 02, 04);
ScheduleCurrent.Tick();
Assert.AreEqual(Models.GenStatus.Running, Controller.Status);
}
[TestMethod]
public async Task RespectsManualStart()
{
// Make sure the schedule doesn't override the user's manual start
//
// I realized this is a bug in my new start/stop logic!!
// This is well within the period where the schedule says to be off
Clock.Now = new DateTime(2017, 3, 1, 10, 00, 01);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 10, 00, 02);
ScheduleCurrent.Tick();
// Start the controller
ScheduleCurrent.Override();
await Controller.Start();
Controller.RunSignal = true;
Clock.Now = new DateTime(2017, 3, 1, 10, 01, 00);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 10, 01, 02);
ScheduleCurrent.Tick();
Assert.AreEqual(Models.GenStatus.Running, Controller.Status);
}
[TestMethod]
public async Task GetsPastManualStart()
{
// Make sure the schedule doesn't override the user's manual start
//
// I realized this is a bug in my new start/stop logic!!
// This is well within the period where the schedule says to be off
Clock.Now = new DateTime(2017, 3, 1, 10, 00, 01);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 10, 00, 02);
ScheduleCurrent.Tick();
// Start the controller
ScheduleCurrent.Override();
await Controller.Start();
Controller.RunSignal = true;
Clock.Now = new DateTime(2017, 3, 1, 10, 01, 00);
ScheduleCurrent.Tick();
Clock.Now = new DateTime(2017, 3, 1, 10, 01, 02);
ScheduleCurrent.Tick();
// Now we are running
// Let's make sure we stop OK!
Clock.Now = new DateTime(2017, 3, 1, 14, 01, 02);
ScheduleCurrent.Tick();
Assert.AreEqual(Models.GenStatus.Stopped, Controller.Status);
}
}
}
#pragma warning restore<file_sep>using System.ComponentModel;
using System.Threading.Tasks;
namespace GenController.Portable.Models
{
public interface IController: INotifyPropertyChanged
{
GenStatus Status { get; }
double Voltage { get; }
bool Enabled { get; set; }
Task Start();
Task Stop();
void Confirm();
}
}<file_sep>using Commonality;
using System;
using System.Threading.Tasks;
namespace GenController.Portable.Tests.Mocks
{
public class MockClock: IClock
{
public DateTime Now { get; set; }
#pragma warning disable 1998
public async Task Delay(TimeSpan t)
{
Now += t;
}
#pragma warning restore 1998
}
}
<file_sep>using Commonality;
namespace GenController.Portable.Models
{
/// <summary>
/// Provides a way to control the generator remotely using an RF remote
/// </summary>
/// <remarks>
/// This is built with a latching RF receiver with two lines. A "start" button
/// line and a "stop" button line. We act when there are changes in those lines.
///
/// The hardware interface to the remote is found in an IRemote.
/// This should already be set in the service locator becore calling
/// AttachToHardware()
///
/// However, if there is no IRemote (perhaps because the app is running
/// natively with no actual GPIO), this class will do nothing.
///
/// </remarks>
public class RemoteControlLogic
{
public RemoteControlLogic(IRemote remote, IController controller)
{
remote.LineChanged += (s,line) =>
{
if (line == 1 && remote.IsPressed(1))
controller.Start();
else if (line == 2 && remote.IsPressed(2))
controller.Stop();
};
}
}
}
<file_sep>using Commonality;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
namespace GenController.Portable.ViewModels
{
/// <summary>
/// This makes the logs from SimpleMeasurement instrumentation visible
/// </summary>
/// <remarks>
/// Service Dependencies:
/// * ILogger
/// </remarks>
public class LogsViewModel: ViewModelBase
{
public LogsViewModel(): base(Service.TryGet<ILogger>())
{
}
/// <summary>
/// List of session logs available
/// </summary>
public RangeObservableCollection<DateTime> Sessions { get; } = new RangeObservableCollection<DateTime>();
/// <summary>
/// Details of currently-selected log
/// </summary>
public RangeObservableCollection<string> Log { get; } = new RangeObservableCollection<string>();
/// <summary>
/// Load the sessions up from disk
/// </summary>
/// <returns></returns>
public void Load()
{
try
{
List<DateTime> result = FileSystemLogger.GetLogs().ToList();
// Sort with most recent on top
result.Sort((x,y)=>y.CompareTo(x));
Sessions.Clear();
Sessions.AddRange(result);
}
catch (Exception ex)
{
SetError("LV1", ex);
}
}
/// <summary>
/// Load the details from the indicated session log into view
/// </summary>
/// <param name="session"></param>
/// <returns></returns>
public async Task SelectSession(DateTime session)
{
try
{
var result = await FileSystemLogger.ReadContents(session);
Log.Clear();
Log.AddRange(result);
SelectedItem = 0;
base.SetProperty(nameof(SelectedItem));
}
catch (Exception ex)
{
SetError("LV2", ex);
}
}
public int SelectedItem { get; set; } = -1;
public ICommand PageUpCommand => new DelegateCommand(_ =>
{
try
{
int desired = SelectedItem - 15;
if (desired < 0)
desired = 0;
if (desired != SelectedItem)
{
SelectedItem = desired;
base.SetProperty(nameof(SelectedItem));
}
}
catch (Exception ex)
{
SetError("LV3", ex);
}
});
public ICommand PageDownCommand => new DelegateCommand(_ =>
{
try
{
int desired = SelectedItem + 15;
if (desired >= Log.Count)
desired = Log.Count - 1;
if (desired != SelectedItem)
{
SelectedItem = desired;
base.SetProperty(nameof(SelectedItem));
}
}
catch (Exception ex)
{
SetError("LV4", ex);
}
});
}
}
<file_sep>using System;
using System.ComponentModel;
using System.Threading.Tasks;
using GenController.Portable.Models;
namespace GenController.Portable.Tests.Mocks
{
/// <summary>
/// Mimic the controller interface for use in testing
/// </summary>
public class MockController : IController
{
public string FullStatus
{
get
{
throw new NotImplementedException();
}
}
public GenStatus Status { get; set; } = GenStatus.Invalid;
public bool RunSignal { get; set; } = false;
public double Voltage => throw new NotImplementedException();
public bool Enabled { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
#pragma warning disable 67
public event PropertyChangedEventHandler PropertyChanged;
#pragma warning restore
#pragma warning disable 1998
public async Task Start()
{
Status = GenStatus.Confirming;
}
public async Task Stop()
{
Status = GenStatus.Stopped;
}
#pragma warning restore 1998
public void Confirm()
{
if (Status == GenStatus.Confirming && RunSignal)
Status = GenStatus.Running;
}
}
}
<file_sep>using Commonality;
using GenController.Portable.Models;
using System;
using System.Windows.Input;
namespace GenController.Portable.ViewModels
{
/// <remarks>
/// Service Dependencies:
/// * ISchedule
/// * ILogger
/// </remarks>
public class EditScheduleViewModel: ViewModelBase
{
public EditScheduleViewModel(): base(Service.TryGet<ILogger>())
{
}
public Models.GenPeriod Period { get; private set; } = new Models.GenPeriod(TimeSpan.FromHours(12), TimeSpan.FromHours(13),14.0);
public Models.GenPeriod Original
{
set
{
try
{
_Original = value;
WillAdd = false;
Period = new Models.GenPeriod(_Original.StartAt, _Original.StopAt, _Original.Voltage);
base.SetProperty(nameof(Period));
base.SetProperty(nameof(WillAdd));
}
catch (Exception ex)
{
base.SetError("EV4", ex);
}
}
}
private Models.GenPeriod _Original;
public bool WillDelete { get; set; }
public bool WillAdd { get; set; } = true;
public ICommand AddCommand => new DelegateCommand((x) =>
{
try
{
string what = x as string;
char direction = what[0];
int add = 1;
if (direction == '-')
add = -1;
switch (what.Substring(1))
{
case "Hfrom":
Period.StartAt = Period.StartAt.Add(TimeSpan.FromHours(add));
if (Period.StartAt < TimeSpan.Zero)
{
Period.StartAt += TimeSpan.FromDays(1);
}
else if (Period.StartAt >= TimeSpan.FromDays(1))
{
Period.StartAt -= TimeSpan.FromDays(1);
}
if (Period.StartAt > Period.StopAt)
{
Period.StopAt = Period.StartAt;
}
break;
case "Mfrom":
Period.StartAt = Period.StartAt.Add(TimeSpan.FromMinutes(add * 5));
if (Period.StartAt < TimeSpan.Zero)
{
Period.StartAt += TimeSpan.FromDays(1);
}
else if (Period.StartAt >= TimeSpan.FromDays(1))
{
Period.StartAt -= TimeSpan.FromDays(1);
}
if (Period.StartAt > Period.StopAt)
{
Period.StopAt = Period.StartAt;
}
break;
case "Hto":
Period.StopAt = Period.StopAt.Add(TimeSpan.FromHours(add));
if (Period.StopAt < TimeSpan.Zero)
{
Period.StopAt += TimeSpan.FromDays(1);
}
else if (Period.StopAt >= TimeSpan.FromDays(1))
{
Period.StopAt -= TimeSpan.FromDays(1);
}
if (Period.StartAt > Period.StopAt)
{
Period.StartAt = Period.StopAt;
}
break;
case "Mto":
Period.StopAt = Period.StopAt.Add(TimeSpan.FromMinutes(add * 5));
if (Period.StopAt < TimeSpan.Zero)
{
Period.StopAt += TimeSpan.FromDays(1);
}
else if (Period.StopAt >= TimeSpan.FromDays(1))
{
Period.StopAt -= TimeSpan.FromDays(1);
}
if (Period.StartAt > Period.StopAt)
{
Period.StartAt = Period.StopAt;
}
break;
case "V":
Period.Voltage += add * 0.2;
if (Period.Voltage > 0.0 && Period.Voltage < 1.0)
Period.Voltage = 12.0;
else if (Period.Voltage < 12.0)
Period.Voltage = 0.0;
else if (Period.Voltage > 14.0)
Period.Voltage = 14.0;
break;
}
base.SetProperty(nameof(Period));
}
catch (Exception ex)
{
base.SetError("EV1", ex);
}
});
public ICommand DeleteMeCommand => new DelegateCommand((x) =>
{
try
{
WillDelete = !WillDelete;
base.SetProperty(nameof(WillDelete));
}
catch (Exception ex)
{
base.SetError("EV2", ex);
}
});
public void Commit()
{
try
{
if (WillDelete)
Schedule.Remove(_Original);
else if (WillAdd)
Schedule.Add(Period);
else
Schedule.Replace(_Original, Period);
}
catch (Exception ex)
{
base.SetError("EV3", ex);
}
}
private ISchedule Schedule => Service.Get<ISchedule>();
}
}
<file_sep>using Commonality.Converters;
using System;
using Windows.UI;
using Windows.UI.Xaml.Media;
namespace GenController.Uwp.Converters
{
public class BooleanRedBrushConverter : DefaultConverter<Brush>
{
public BooleanRedBrushConverter(): base(new SolidColorBrush(Colors.Black),new SolidColorBrush(Colors.Red))
{
}
}
public class BooleanRedBrushConverterXaml : XamlValueConverter<BooleanRedBrushConverter>
{
}
}
<file_sep>using GenController.Portable.Models;
using IotFrosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenController.Uwp.Platform
{
/// <summary>
/// Hardware Interface to the physical remote
/// </summary>
/// <remarks>
/// This listens to the physical remote control receiver hardware.
/// The way the hardware is designed, there are four input lines, and one of them
/// is always 'on' at any time, where the other three are off.
/// </remarks>
public class HardwareRemote: IRemote, IDisposable
{
List<IPin> Pins = new List<IPin>() { new InputPin(1), new InputPin(2) };
public HardwareRemote()
{
foreach (var pin in Pins)
pin.Updated += Pin_Updated;
}
private void Pin_Updated(IInput sender, EventArgs args)
{
var index = Pins.IndexOf(sender as IPin);
LineChanged?.Invoke(this, index + 1);
}
/// <summary>
/// Whether the selected
/// </summary>
/// <remarks>
/// There are four lines. Any or all of them can be pressed
/// </remarks>
public bool IsPressed(int line)
{
return Pins[line - 1].State;
}
/// <summary>
/// Raised when the a line changes state
/// </summary>
public event EventHandler<int> LineChanged;
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
foreach( var pin in Pins )
{
pin.Dispose();
}
Pins.Clear();
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~HardwareRemote() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}
<file_sep>This folder contains resources used in the main repo README.<file_sep>using System;
using System.Collections.Generic;
using Commonality;
namespace GenController.Portable.Tests.Mocks
{
public class MockSettings : ISettings
{
Dictionary<string, object> Storage = new Dictionary<string, object>();
public IEnumerable<string> GetCompositeKey(string key)
{
if (Storage.ContainsKey(key))
{
return (IEnumerable<string>)Storage[key];
}
else
return null;
}
public string GetKey(string key)
{
if (Storage.ContainsKey(key))
{
return (string)Storage[key];
}
else
return null;
}
public void SetCompositeKey(string key, IEnumerable<string> values)
{
Storage[key] = values;
}
public void SetKey(string key, string value)
{
Storage[key] = value;
}
}
}
<file_sep>using System;
namespace GenController.Portable.Models
{
/// <summary>
/// Defines the hardware interface to a remote
/// </summary>
public interface IRemote
{
/// <summary>
/// Whether the selected
/// </summary>
/// <remarks>
/// There are four lines. Any or all of them can be pressed
/// </remarks>
bool IsPressed(int line);
/// <summary>
/// Raised when the a line changes state
/// </summary>
event EventHandler<int> LineChanged;
}
}
<file_sep>using System;
using Commonality.Converters;
namespace GenController.Uwp.Converters
{
public class DateFormatConverterXaml : XamlValueConverter<DateFormatConverter>
{
}
public class TimeSpanFormatConverterXaml : XamlValueConverter<TimeSpanFormatConverter>
{
}
}
<file_sep>
# Gen Controller
This project is a fully-programmable custom Auto-Generator Start (AGS) for Onan Generators.
# The Idea
In the summer of 2017, my family travelled around the West Coast in our 32-foot motorhome. One of the great advantages of motorhome travel is that you bring with you all the comforts of home wherever you go, no matter how rustic the surroundings. One of these travelling comforts, the one most germane to this discussion, is electricity. Typically, we will stay in a park or campground with power hookups where you simply plug the motorhome into the giant plug, and use all the electricity you like.
Sometimes, you'll want to stay somewhere without a convenient power hookup. For these times, the coach comes with a built-in generator capable of providing all the needed power. The downside to this is that the generator makes some noise, leading to restrictions on its use in many organized campgrounds.
The extreme example is Yosemite NP. The park has no hookups, and restricts generator hours as follows: 7am-9am, 12pm-2pm, and 5pm-7pm. Ideally, we would like to run our generator at all those times, storing all the power we can in our batteries for use at other times of day. However, we are not going to always be around our site at exactly those times. This leaves us with the problem of either restricting our time out enjoying the park, or accepting less electricity use.
This seems like a great problem to solve with technology. We need a system that will automatically turn the generator on and off at precisely the prescribed times of day, whether or not we are around. This way, we can enjoy the park to the fullest and maximize our power generation. Technology FTW!
# Hardware
* [Raspberry Pi](https://www.adafruit.com/category/105)
* [DS3231 Real-time clock module](https://www.adafruit.com/product/3013)
* [Pimoroni Automation Hat](https://www.adafruit.com/product/3289)
* [Onan remote control harness](https://www.rvupgradestore.com/Onan-Remote-Control-Panels-Wiring-Harness-p/55-8685.htm)
# Software Environment
* [Windows 10 IoT Core](https://developer.microsoft.com/en-us/windows/iot)
Perhaps my favorite thing about Windows IoT Core is how little effort is required to have a native version. One of my first rules of embedded development is to have a native version of the system, enabling much faster turns of the coding loop. Here, it's as simple as changing the compiler target to x86, and making sure any hardware-specific code is hidden behind a service locator. This means I can ensure all the logic is working right, quickly debugging if needed, without having to wait for a (slow) deployment to target hardware. Likewise, I can test the business logic in .NET unit tests on the host PC--again much faster than deploying tests and running on the target.
# Software Components
The project is comprised of these pieces:
* [GenController.Uwp](./GenController.Uwp) Universal Windows App, contains the UI screens and Windows-specific components.
* [GenController.Portable](./GenController.Portable) .NET Standard library, contains the platform-independent application logic, viewmodels.
* [GenController.Portable.Tests](./GenController.Portable.Tests) Unit tests for the application logic.
* [Commonality](./Commonality) .NET Standard library, contains domain-independent helper classes.
# Dependencies
The project consumes these dependencies:
* [IoTFrosting](https://github.com/jcoliz/Iot-Frosting): For control of the Pimoroni Automation Hat and the DS3231 real-time clock.
* [Catnap.Server](https://github.com/jcoliz/Catnap.Server): To present a web backend<file_sep>using Catnap.Server;
using Commonality;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Windows.Web.Http;
namespace GenController.Uwp.Controllers
{
/// <summary>
/// Web controller for "status" page
/// </summary>
/// <remarks>
/// Service Dependencies:
/// * ILogger
/// </remarks>
[RoutePrefix("status")]
class StatusController : Controller
{
private Portable.ViewModels.MainViewModel VM = new Portable.ViewModels.MainViewModel();
private SynchronizationContext Context = SynchronizationContext.Current;
[HttpGet]
[Route]
public HttpResponse Get()
{
Logger?.LogEventAsync("Web.Status");
var html = new List<string>()
{
"<html>",
"<head>",
//"<meta http-equiv=\"refresh\" content=\"5\"/>",
"<meta http-equiv=\"expires\" content=\"-1\"/>",
"<meta name=\"viewport\" content=\"width=device-width, user-scalable=no\"/>",
"<script src=\"https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js\"></script>",
"<script>",
"$(document).ready(function(){",
"$(\"button#start\").click(function(){ $.post(\"status/start\",{},function(data,status){ alert (data); }); });",
"$(\"button#stop\").click(function(){ $.post(\"status/stop\",{},function(data,status){ alert (data); }); });",
"$(\"button#disable\").click(function(){ $.post(\"status/disable\",{},function(data,status){ alert (data); }); });",
"});",
"</script>",
"<style>",
"body { margin: 0; padding: 0; margin-left: 10px; background-color: rgb(197, 204, 211); -webkit-text-size-adjust:none; }",
"h1 { margin:0; margin-left: auto; margin-right: auto; width: 350px; padding-top:10px; padding-right:10px; padding-bottom:10px; padding-left:10px; font-size:30px; font-family: Helvetica; font-weight:bold; color: rgb(76,86,108); }",
"h1 span.big { float:right; }",
".button { display: block; line-height: 46px; width: 350px; font-size: 20px; font-weight: bold; font-family: Helvetica, sans-serif; color: #fff; text-decoration: none; text-align: center; margin: 10px auto; }",
".red { background-color: red }",
".green { background-color: green }",
".gray { background-color: gray }",
"ul { padding: 0; margin-top:0; margin-left: auto; margin-right: auto; margin-bottom:17px; font-size:17px; font-family: Helvetica; font-weight:bold; color:black; width: 350px; background-color: white; border-width: 1px; border-style:solid ; border-color:rgb(217,217,217); -webkit-border-radius: 8px; }",
"li { list-style-type: none; border-top-width:1px; border-top-style:solid; border-top-color:rgb(217,217,217); padding:10px; }",
"</style>",
"</head>",
"<body>",
$"<h1>{VM.CurrentTime.ToString("HH\\:mm\\:ss")} <span class=\"big\">{VM.Controller.Status}</span></h1>",
"<ul>"
};
html.AddRange(VM.Periods.Take(6).Select(p => $"<li>{p.Label}</li>"));
html.AddRange(new List<string>() {
"</ul>",
"<button class=\"green button\" id=\"start\">Start</button>",
"<button class=\"red button\" id=\"stop\">Stop</button>"
});
if (VM.Controller.Enabled)
html.Add("<button class=\"gray button\" id=\"disable\">Disable</button>");
else
html.Add("<button class=\"gray button\" id=\"enable\">Enable</button>");
html.AddRange(new List<string>() {
$"<ul><li>{App.Current.Title} {App.Current.Version}</li>",
$"<li>E: {(VM.Controller.Enabled?'Y':'N')} 1:{(App.ControllerCurrent.StartLine?'Y':'N')} 0:{(App.ControllerCurrent.StopLine?'Y':'N')} R:{(App.ControllerCurrent.RunSignal?'Y':'N')} P:{(App.ControllerCurrent.PanelLightSignal?'Y':'N')} </li>",
"<li><a href=\"/logs\">View Logs</a></li></ul>",
"</body></html>"
});
var content = string.Join("\r\n", html);
Logger?.LogEventAsync("Web.StatusOK",$"Status={VM.Controller.Status}");
return new HttpResponse(HttpStatusCode.Ok, content);
}
[HttpPost]
[Route("start")]
public HttpResponse Start([Body] string postContent)
{
Logger?.LogEventAsync("Web.Start");
VM.StartCommand.Execute(this);
Logger?.LogEventAsync("Web.StartOK");
return new HttpResponse(HttpStatusCode.Ok, $"Starting...");
}
[HttpPost]
[Route("stop")]
public HttpResponse Stop([Body] string postContent)
{
Logger?.LogEventAsync("Web.Stop");
VM.StopCommand.Execute(this);
Logger?.LogEventAsync("Web.StopOK");
return new HttpResponse(HttpStatusCode.Ok, $"Stopping...");
}
[HttpPost]
[Route("disable")]
public HttpResponse Disable([Body] string postContent)
{
Logger?.LogEventAsync("Web.Disable");
VM.DisableCommand.Execute(this);
Logger?.LogEventAsync("Web.DisableOK");
return new HttpResponse(HttpStatusCode.Ok, $"Disabled.");
}
[HttpPost]
[Route("enable")]
public HttpResponse Enable([Body] string postContent)
{
Logger?.LogEventAsync("Web.Enable");
VM.EnableCommand.Execute(this);
Logger?.LogEventAsync("Web.EnableOK");
return new HttpResponse(HttpStatusCode.Ok, $"Enabled.");
}
#region Service Locator services
private ILogger Logger => Service.TryGet<ILogger>();
#endregion
}
}
| d59fd67862975e4e0c48233219ed42b4d68426f8 | [
"Markdown",
"C#"
] | 45 | C# | MollsAndHersh/OnanGeneratorController | e39ac9fb2732ee0a3f32c1a32e7299d992687590 | e87cbdeaa94844bc4d796f1a1db10459cf994353 |
refs/heads/main | <file_sep>var numFaces = 0;
var indexFace = 0;
var prevIndexFace = (indexFace - 1 + numFaces) % numFaces;
var nextIndexFace = (indexFace + 1) % numFaces;
var currentBoxContainer;
var currentAngle = 0;
var invisibleCls = "is_invisible";
var hiddenCls = "is_hidden";
var openCls = "is_open";
var throttle = false;
$(document).ready(function () {
// open origami
$(document).on('click', '.origami_container .origami_face', function () {
currentBoxContainer = $(this).closest('.origami_container');
if (!currentBoxContainer.hasClass(openCls)) {
currentBoxContainer.addClass(openCls)
numFaces = $('.is_open .origami_face').length;
currentBoxContainer.css('z-index', '99');
// all other closed origami_containers must not react to click (apparently I needed that?)
$('.origami_container').not(currentBoxContainer).css({ 'pointer-events': 'none' });
currentBoxContainer.find('.origami_header').removeClass([hiddenCls]);
currentBoxContainer.find('.project_container').removeClass([hiddenCls]);
updateSelected();
}
});
// closing through clicking the closing button
$('.origami_close').on('click', function () {
closeTheBox();
});
// closing through clicking Esc
$(document).on('keydown', function (event) {
if (event.key === 'Escape') { // Check if the pressed key is 'Escape'
closeTheBox();
}
});
//rotating with a click (slow on touch tap to fix)
$(document).on('click', '.is_open .origami_face', function () {
var prevFace = $('.is_open .origami_face').eq(prevIndexFace);
var nextFace = $('.is_open .origami_face').eq(nextIndexFace);
if (this === prevFace[0]) {
rotateBox(-1);
} else if (this === nextFace[0]) {
rotateBox(1);
}
});
$(window).on('keydown', function (event) {
if ($('.origami_container').hasClass(openCls)) {
if (!throttle) {
if (event.key === 'ArrowLeft') {
rotateBox(-1);
} else if (event.key === 'ArrowRight') {
rotateBox(1);
}
throttle = true;
throttling();
}
}
});
//scroll origami horizontally but only works outside selected scrollable project
$(window).on('wheel', function (event) {
if ($('.origami_container').hasClass(openCls)) {
if (!$('.is_open .origami_face.selected').has(event.target).length) {
if (!throttle) {
if (Math.sign(event.originalEvent.deltaY) === -1) {
rotateBox(-1);
} else if (Math.sign(event.originalEvent.deltaY) === 1) {
rotateBox(1);
}
throttle = true;
throttling();
}
}
}
});
});
function updateSelected() {
prevIndexFace = (indexFace - 1 + numFaces) % numFaces;
nextIndexFace = (indexFace + 1) % numFaces;
$('.is_open .origami_face').removeClass(['selected', 'selectable']);
$('.is_open .origami_face').eq(indexFace).addClass('selected');
$('.is_open .origami_face').eq(prevIndexFace).addClass('selectable');
$('.is_open .origami_face').eq(nextIndexFace).addClass('selectable');
}
function closeTheBox() {
currentBoxContainer = $('.origami_container.is_open');
var origami = currentBoxContainer.find('.origami')[0];
origami.style.transform = ''; // clear the transform style so that it doesn't bug
$('.project_container').scrollTop(0);
$('.origami_face').removeClass('selected');
currentBoxContainer.removeClass(openCls)
currentBoxContainer.css('z-index', '0')
currentBoxContainer.find('.origami_header').addClass(hiddenCls);
currentBoxContainer.find('.project_container').addClass(hiddenCls);
currentAngle = 0;
indexFace = 0;
$('.origami_container').not(currentBoxContainer).css({ 'pointer-events': 'auto' });
}
function rotateCarousel() {
var selectedBox = document.querySelector('.is_open .origami');
// Check in which section the opened origami is contained, if found the statement is true (has lenght = has parent)
var hasWebAncestor = $(selectedBox).parents('#web').length > 0;
var hasIlluAncestor = $(selectedBox).parents('#illu').length > 0;
var hasExtraAncestor = $(selectedBox).parents('#extra').length > 0;
var hasAboutAncestor = $(selectedBox).parents('#about').length > 0;
if (hasWebAncestor) {
selectedBox.style.transform = 'translateZ(-30vw) rotateY(' + currentAngle + 'deg) ';
} else if (hasIlluAncestor) {
selectedBox.style.transform = 'translateZ(-38vw) rotateY(' + currentAngle + 'deg) ';
} else if (hasExtraAncestor) {
selectedBox.style.transform = 'translateZ(-40vw) rotateY(' + currentAngle + 'deg) ';
} else if (hasAboutAncestor) {
selectedBox.style.transform = 'translateZ(-25vw) rotateY(' + currentAngle + 'deg) ';
}
$('.project_container').animate({
scrollTop: 0
}, 500); // 500 is the duration of the animation in milliseconds
}
// left = -1
// right = 1
function rotateBox(direction) {
numFaces = $('.is_open .origami_face').length; // add this line to update the number of faces
var rotationIndex = 360 / numFaces;
if (direction < 0) {
currentAngle += rotationIndex;
rotateCarousel();
indexFace = (indexFace - 1 + numFaces) % numFaces;
} else {
currentAngle -= rotationIndex;
rotateCarousel();
indexFace = (indexFace + 1) % numFaces;
}
updateSelected();
}
//throttling function to avoid crazy spin of the origami carousel
function throttling() {
if (throttle) {
setTimeout(() => {
throttle = false;
}, 300);
}
}
//swipe rotate (found online) --- to be converted in JQuery
document.addEventListener('touchstart', handleTouchStart, { passive: false });
document.addEventListener('touchmove', handleTouchMove, { passive: false });
var xDown = null;
var yDown = null;
function getTouches(evt) {
return evt.touches || evt.originalEvent.touches; // jQuery
}
function handleTouchStart(evt) {
if (!$('.origami_container').hasClass(openCls)) {
return;
}
const firstTouch = getTouches(evt)[0];
xDown = firstTouch.clientX;
yDown = firstTouch.clientY;
evt.target.setPointerCapture(firstTouch.pointerId);
}
function handleTouchMove(evt) {
if (!$('.origami_container').hasClass(openCls) || !xDown || !yDown) {
return;
}
var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;
var xDiff = xDown - xUp;
var yDiff = yDown - yUp;
if (Math.abs(xDiff) > Math.abs(yDiff)) {
if (xDiff > 0) {
rotateBox(1);
} else {
rotateBox(-1);
}
}
// Reset touch start coordinates
xDown = null;
yDown = null;
} | ddbaedaa2dafb6cfdff7b046e4bdc132ed559a4a | [
"JavaScript"
] | 1 | JavaScript | raggiodiluca/raggiodiluca.github.io | 9faebf577b9b3743644a1163b424298a7788af07 | 90da0357b9eea535026bc8d414fdf88c8edf478c |
refs/heads/main | <file_sep>//
// GuardianAPI.swift
// TheFood
//
// Created by <NAME> on 05/06/2021.
//
import Combine
import Foundation
class GuardianAPI: RecipesPublisher {
static let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return decoder
}()
private let session: URLSession
init(session: URLSession = URLSession.shared) {
self.session = session
}
func getLatestRecipes(currentPage: Int = 1) -> AnyPublisher<Response?, Never> {
let baseUrl = URL(string: "https://content.guardianapis.com/search?api-key=<KEY>&page-size=3&page=\(currentPage)&tag=tone/recipes&show-fields=\(Recipe.showFields)&show-tags=series")!
var request = URLRequest(url: baseUrl)
request.httpMethod = "GET"
return session
.dataTaskPublisher(for: request)
.map(\.data)
.decode(type: Response?.self, decoder: Self.decoder)
.replaceError(with: nil)
.eraseToAnyPublisher()
}
}
<file_sep>//
// GuardianAPITest.swift
// TheFoodTests
//
// Created by <NAME> on 06/06/2021.
//
import Combine
@testable import TheFood
import XCTest
class GuardianAPITest: XCTestCase {
private var api: GuardianAPI!
private let baseUrl = URL(string: "http://test.test/")
private var cancellable: AnyCancellable?
override func setUpWithError() throws {
try super.setUpWithError()
let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [MockURLProtocol.self]
let session = URLSession(configuration: configuration)
api = GuardianAPI(session: session)
}
override func tearDownWithError() throws {
try super.tearDownWithError()
api = nil
MockURLProtocol.requestHandler = nil
cancellable?.cancel()
}
func testGetRecipesWhenRequestSuccess() throws {
MockURLProtocol.requestHandler = { _ in
let response = HTTPURLResponse(url: self.baseUrl!, statusCode: 200, httpVersion: nil, headerFields: nil)!
let data = try? Data(from: "exampleResponse")
return (response, data)
}
let expectation = expectation(description: "recipes get loaded")
cancellable = api.getLatestRecipes().compactMap(\.?.results).sink { recipes in
XCTAssertEqual(recipes.count, 5)
XCTAssertEqual(recipes[0].headline, "Thomasina Miers’ recipe for clotted cream drizzle cake with macerated strawberries")
XCTAssertEqual(
recipes[0].thumbnail,
URL(string: "https://media.guim.co.uk/59a765b09fa3bb95c0d60705077fdab4900d2152/0_2784_5792_3475/500.jpg")!)
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func testGetRecipesWhenReqestFails() throws {
MockURLProtocol.requestHandler = { _ in
let response = HTTPURLResponse(url: self.baseUrl!, statusCode: 404, httpVersion: nil, headerFields: nil)!
return (response, nil)
}
let expectation = expectation(description: "result not loaded")
cancellable = api.getLatestRecipes().sink { result in
XCTAssertNil(result)
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
}
<file_sep>//
// RecipesPublisher.swift
// TheFood
//
// Created by <NAME> on 26/05/2021.
//
import Combine
import Foundation
protocol RecipesPublisher {
func getLatestRecipes(currentPage: Int) -> AnyPublisher<GuardianAPI.Response?, Never>
}
<file_sep>//
// ScrollUpButton.swift
// TheFood
//
// Created by <NAME> on 10/06/2021.
//
import Foundation
import SwiftUI
struct ScrollUpButton: View {
let proxy: ScrollViewProxy
var tag: Namespace.ID
var body: some View {
Button(
action: {
withAnimation { proxy.scrollTo(tag) }
},
label: {
Image(systemName: "arrow.up.circle")
.font(.title)
})
}
}
<file_sep>//
// TheFoodUITests.swift
// TheFoodUITests
//
// Created by <NAME> on 24/05/2021.
//
import XCTest
class TheFoodUITests: XCTestCase {
override func setUpWithError() throws {
try super.setUpWithError()
continueAfterFailure = false
}
func testExample() throws {
let app = XCUIApplication()
app.launch()
}
}
<file_sep>//
// TheFoodApp.swift
// TheFood
//
// Created by <NAME> on 24/05/2021.
//
import SwiftUI
@main
struct TheFoodApp: App {
var body: some Scene {
WindowGroup {
ContentView(recipesController: RecipesController())
}
}
}
<file_sep>//
// InMemoryRecipesProvider.swift
// TheFood
//
// Created by <NAME> on 26/05/2021.
//
import Combine
import Foundation
struct InMemoryRecipesPublisher: RecipesPublisher {
func getLatestRecipes(currentPage: Int) -> AnyPublisher<GuardianAPI.Response?, Never> {
Just(GuardianAPI.Response(results: Recipe.recipes, pageSize: 3, currentPage: 1, pages: 1)).eraseToAnyPublisher()
}
}
<file_sep># TheFood
## Description:
An application for searching and displaying recipes using the Guardian API.
Fetches the recipes using this API call.
The motivation behind this project was to use it to consolidate my knowledge about SwiftUI, Combine, XCTest. I also want to create a user-friendly interface that would allow
searching and finding recipes easy.
I try to recreate the Guardian's app design as close as possible.
## Technologies:
- SwiftUI
- Combine
- XCTest
- SwiftLint
- Kingfisher
## Features:
- Browsing the latest recipes on Discovery Page
- Searching recipes by ingredients, author or by other search keys.
## Setup
1) Clone the repository: `git clone https://github.com/jotkafomat/TheFood`
2) Go into the repository: `cd TheFood`
3) Start the app: `open TheFood.xcodeproj`
## Testing
### Unit testing
1) Open project and run the tests: 'cmd+U'
## Screenshots



<file_sep>//
// RecipeViewModel.swift
// TheFood
//
// Created by <NAME> on 09/06/2021.
//
import Foundation
import SwiftUI
struct RecipeViewModel {
static let formatter: DateFormatter = {
let formatter = DateFormatter()
// formatter.
formatter.dateFormat = "HH:mm EEEE, d MMMM y"
return formatter
}()
private let recipe: Recipe
var displayBody: String {
recipe.body.replacingOccurrences(of: "</p>", with: "\n")
.replacingOccurrences(of: "<br>", with: "\n")
.replacingOccurrences(
of: "<[^>]+>",
with: "",
options: .regularExpression)
}
var color: Color {
recipe.frameColor.color
}
var image: URL {
recipe.thumbnail
}
var tag: String {
recipe.tags.first?.series ?? recipe.byline
}
var headline: String {
recipe.headline
}
var trailText: String {
recipe.trailText
}
var byline: String {
recipe.byline
}
var firstPublicationDate: String {
let date = recipe.firstPublicationDate
return RecipeViewModel.formatter.string(from: date)
}
init(recipe: Recipe) {
self.recipe = recipe
}
}
extension RecipeViewModel: Identifiable {
var id: String {
recipe.id
}
}
<file_sep>//
// Recipe.swift
// TheFood
//
// Created by <NAME> on 25/05/2021.
//
import Foundation
struct Recipe {
static let showFields: String = FieldsKeys.allCases.map { $0.rawValue }.joined(separator: ",")
let id: String
let firstPublicationDate: Date
let headline: String
let thumbnail: URL
let trailText: String
let byline: String
let body: String
let tags: [Tag]
let frameColor = FrameColor.allCases.randomElement()!
}
extension Recipe: Decodable {
enum CodingKeys: String, CodingKey {
case id, fields, tags
}
enum FieldsKeys: String, CodingKey, CaseIterable {
case headline, thumbnail, trailText, byline, body, firstPublicationDate
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
tags = try container.decode([Tag].self, forKey: .tags)
let fieldsContainer = try container.nestedContainer(keyedBy: FieldsKeys.self, forKey: .fields)
headline = try fieldsContainer.decode(String.self, forKey: .headline)
thumbnail = try fieldsContainer.decode(URL.self, forKey: .thumbnail)
trailText = try fieldsContainer.decode(String.self, forKey: .trailText)
byline = try fieldsContainer.decode(String.self, forKey: .byline)
body = try fieldsContainer.decode(String.self, forKey: .body)
firstPublicationDate = try fieldsContainer.decode(Date.self, forKey: .firstPublicationDate)
}
}
extension Recipe: Identifiable {}
<file_sep>//
// TheFoodTests.swift
// TheFoodTests
//
// Created by <NAME> on 24/05/2021.
//
import Combine
@testable import TheFood
import XCTest
class TheFoodTests: XCTestCase {
private var recipesController: RecipesController!
private var cancellable: AnyCancellable?
override func tearDownWithError() throws {
try super.tearDownWithError()
recipesController = nil
cancellable?.cancel()
}
func testWhenPublisherSuccedToFetchRecipesArrayIsNotEmpty() throws {
let expectation = expectation(description: "expect recipes to not be empty")
let recipesController = RecipesController(recipesPublisher: MockRecipesPublisher.successLastPage)
cancellable = recipesController
.$recipes
.dropFirst()
.sink { recipes in
XCTAssertFalse(recipes.isEmpty)
expectation.fulfill()
}
waitForExpectations(timeout: 1.0)
}
func testWhenPublisherFailToFetchRecipesArrayIsEmpty() throws {
let expectation = expectation(description: "expect recipes to be empty")
let recipesController = RecipesController(recipesPublisher: MockRecipesPublisher.failure)
cancellable = recipesController
.$recipes
.sink { recipes in
XCTAssert(recipes.isEmpty)
expectation.fulfill()
}
waitForExpectations(timeout: 1.0)
}
func testWhenPublisherANy() throws {
let expectation = expectation(description: "expect recipes to be empty")
let recipesController = RecipesController(recipesPublisher: MockRecipesPublisher.any)
cancellable = recipesController
.$recipes
.sink { recipes in
XCTAssert(recipes.isEmpty)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1.0)
}
func testCanLoadMoreTrueWhenRecipesPublisherReturnsResponseWithMorePages() {
let expectation = expectation(description: "can load more is true")
let recipesController = RecipesController(recipesPublisher: MockRecipesPublisher.successHasMorePages)
cancellable = recipesController.objectWillChange
.delay(
for: RunLoop.SchedulerTimeType.Stride(0.0.nextUp),
scheduler: RunLoop.current)
.sink { _ in
XCTAssert(recipesController.canLoadMorePages)
expectation.fulfill()
}
waitForExpectations(timeout: 1.0)
}
func testCanLoadMoreFalseWhenRecipesPublisherReturnsResponseWithLastPage() {
let expectation = expectation(description: "can load more is false")
let recipesController = RecipesController(recipesPublisher: MockRecipesPublisher.successLastPage)
cancellable = recipesController.objectWillChange
.delay(
for: RunLoop.SchedulerTimeType.Stride(0.0.nextUp),
scheduler: RunLoop.current)
.sink { _ in
XCTAssertFalse(recipesController.canLoadMorePages)
expectation.fulfill()
}
waitForExpectations(timeout: 1.0)
}
}
<file_sep>//
// RecipesController.swift
// TheFood
//
// Created by <NAME> on 25/05/2021.
//
import Combine
import Foundation
class RecipesController: ObservableObject {
@Published private (set) var recipes = [RecipeViewModel]()
private let recipesPublisher: RecipesPublisher
private var cancellable = Set<AnyCancellable>()
private var currentPage: Int = 0
private(set) var canLoadMorePages = true
init(recipesPublisher: RecipesPublisher = GuardianAPI()) {
self.recipesPublisher = recipesPublisher
loadMoreRecipes()
}
func loadMoreRecipes() {
guard canLoadMorePages else {
return
}
currentPage += 1
recipesPublisher
.getLatestRecipes(currentPage: currentPage)
.compactMap { $0 }
.receive(on: RunLoop.main)
.sink { [weak self] response in
let recipes = response.results.map(RecipeViewModel.init)
self?.recipes.append(contentsOf: recipes)
self?.canLoadMorePages = response.pages > response.currentPage
}
.store(in: &cancellable)
}
}
<file_sep>//
// RecipeView.swift
// TheFood
//
// Created by <NAME> on 25/05/2021.
//
import Kingfisher
import SwiftUI
struct RecipeView: View {
let recipe: RecipeViewModel
var body: some View {
Rectangle()
.aspectRatio(0.97, contentMode: .fit)
.foregroundColor(recipe.color)
.overlay(
KFImage(recipe.image)
.resizable()
.scaledToFill()
.aspectRatio(1, contentMode: .fit)
.clipShape(Circle())
.padding(4)
)
.overlay(
VStack(alignment: .leading, spacing: 4.0) {
Text(recipe.tag)
.font(.system(.body, design: .serif))
.fontWeight(.semibold)
.foregroundColor(.black)
.multilineTextAlignment(.leading)
.padding(.leading, 4)
.padding(.trailing, 4)
.background(Color.white)
Text(recipe.headline)
.font(.system(.title, design: .serif))
.fontWeight(.semibold)
.foregroundColor(.white)
.background(Color.black)
.padding(.bottom, 4)
},
alignment: .bottomLeading
)
}
}
struct RecipeView_Previews: PreviewProvider {
static var previews: some View {
Group {
RecipeView(recipe: RecipeViewModel.all[0])
.preferredColorScheme(.light)
.previewDevice("iPhone 12 Pro Max")
RecipeView(recipe: RecipeViewModel.all[0] )
.preferredColorScheme(.dark)
.environment(\.sizeCategory, .accessibilityMedium)
.previewDevice("iPhone 12 Pro Max")
}
}
}
<file_sep>//
// Tag.swift
// TheFood
//
// Created by <NAME> on 09/06/2021.
//
import Foundation
struct Tag {
let series: String
}
extension Tag: Decodable {
enum CodingKeys: String, CodingKey {
case series = "webTitle"
}
}
<file_sep>//
// RecipesViewModelTests.swift
// TheFoodTests
//
// Created by <NAME> on 11/06/2021.
//
import SwiftUI
@testable import TheFood
import XCTest
class RecipesViewModelTests: XCTestCase {
private var recipeViewModel: RecipeViewModel!
override func setUpWithError() throws {
try super.setUpWithError()
recipeViewModel = RecipeViewModel(recipe: Recipe.recipes[0])
}
override func tearDownWithError() throws {
try super.tearDownWithError()
recipeViewModel = nil
}
func testImage() throws {
XCTAssertEqual(recipeViewModel.image, URL(string: "https://media.guim.co.uk/793f8c456f5fa74a0f8f789580fecb950a5c2cda/0_3728_5792_3475/500.jpg"))
}
func testTag() throws {
XCTAssertEqual(recipeViewModel.tag, "The simple fix")
}
func testNoTag() throws {
recipeViewModel = RecipeViewModel(recipe: Recipe.recipes[1])
XCTAssertEqual(recipeViewModel.tag, "<NAME>")
}
func testFirstPublicationDate() throws {
XCTAssertEqual(recipeViewModel.firstPublicationDate, "16:16 Thursday, 10 June 2021")
}
func testHeadline() throws {
XCTAssertEqual(recipeViewModel.headline, "<NAME>’ recipe for courgetti carbonara")
}
func testTrailtext() throws {
XCTAssertEqual(recipeViewModel.trailText, "Ribbons of courgette are a great way to get more veg into your diet – here, they lend both colour and texture to a dish of garlicky, cheesy pasta")
}
func testByline() throws {
XCTAssertEqual(recipeViewModel.byline, "<NAME>")
}
func testId() throws {
XCTAssertEqual(recipeViewModel.id, "food/2021/may/24/thomasina-miers-recipe-courgetti-carbonara")
}
}
<file_sep>//
// ContentView.swift
// TheFood
//
// Created by <NAME> on 24/05/2021.
//
import SwiftUI
struct ContentView: View {
@ObservedObject var recipesController: RecipesController
var body: some View {
NavigationView {
ScrollView(showsIndicators: false) {
LazyVStack(spacing: 2.0) {
ForEach(recipesController.recipes) { item in
NavigationLink(
destination: RecipeDetailView(recipe: item)) {
RecipeView(recipe: item)
.accessibility(hint: Text("Opens recipe details"))
}
}
if recipesController.canLoadMorePages {
ProgressView()
.onAppear {
recipesController.loadMoreRecipes()
}
}
}
}
.navigationBarHidden(true)
.ignoresSafeArea()
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(
recipesController: RecipesController(
recipesPublisher: InMemoryRecipesPublisher()))
}
}
#endif
<file_sep>//
// MockURLProtocol.swift
// MovieAPITests
//
// Created by <NAME> on 25/02/2021.
//
import Foundation
class MockURLProtocol: URLProtocol {
static var requestHandler: ((URLRequest) -> (HTTPURLResponse, Data?))!
override class func canInit(with request: URLRequest) -> Bool {
true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
request
}
override func startLoading() {
let (response, data) = MockURLProtocol.requestHandler(request)
client?.urlProtocol(
self,
didReceive: response,
cacheStoragePolicy: .notAllowed)
if let data = data {
client?.urlProtocol(self, didLoad: data)
}
client?.urlProtocolDidFinishLoading(self)
}
override func stopLoading() {}
}
<file_sep>//
// MockRecipesPublisher.swift
// TheFoodTests
//
// Created by <NAME> on 26/05/2021.
//
import Combine
import Foundation
@testable import TheFood
enum MockRecipesPublisher: RecipesPublisher {
case successLastPage
case successHasMorePages
case failure
case any
func getLatestRecipes(currentPage: Int = 1) -> AnyPublisher<GuardianAPI.Response?, Never> {
switch self {
case .successLastPage:
return Just(GuardianAPI.Response(results: Recipe.recipes, pageSize: 3, currentPage: 1, pages: 1))
.eraseToAnyPublisher()
case .failure:
return Just<GuardianAPI.Response?>(nil).eraseToAnyPublisher()
case .any:
return Empty().eraseToAnyPublisher()
case .successHasMorePages:
return Just(GuardianAPI.Response(results: Recipe.recipes, pageSize: 3, currentPage: 1, pages: 3))
.eraseToAnyPublisher()
}
}
}
<file_sep>//
// AuthorBadgeView.swift
// TheFood
//
// Created by <NAME> on 11/06/2021.
//
import SwiftUI
struct AuthorBadgeView: View {
let recipe: RecipeViewModel
var body: some View {
HStack(alignment: .center) {
Image(systemName: "person.crop.circle")
.font(.largeTitle)
.accessibility(label: Text("author's avatar"))
VStack(alignment: .leading) {
Text(recipe.byline)
.font(.system(.subheadline, design: .serif))
.fontWeight(.medium)
.foregroundColor(.pink)
.accessibility(label: Text("author's avatar"))
Text(recipe.firstPublicationDate)
.font(.system(.subheadline, design: .serif))
.fontWeight(.light)
.foregroundColor(.secondary)
.accessibility(label: Text("Publication date \(recipe.firstPublicationDate)"))
}
}
}
}
struct AuthorBadgeView_Previews: PreviewProvider {
static var previews: some View {
AuthorBadgeView(recipe: RecipeViewModel.all[0]).previewLayout(.sizeThatFits)
}
}
<file_sep>//
// GuardianAPI + Response.swift
// TheFood
//
// Created by <NAME> on 09/06/2021.
//
import Foundation
extension GuardianAPI {
struct Response {
let results: [Recipe]
let pageSize: Int
let currentPage: Int
let pages: Int
}
}
extension GuardianAPI.Response: Decodable {
enum CodingKeys: String, CodingKey {
case response
}
enum ResponseKeys: String, CodingKey {
case results, pageSize, currentPage, pages
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let responseContainer = try container.nestedContainer(keyedBy: ResponseKeys.self, forKey: .response)
results = try responseContainer.decode([Recipe].self, forKey: .results)
pageSize = try responseContainer.decode(Int.self, forKey: .pageSize)
currentPage = try responseContainer.decode(Int.self, forKey: .currentPage)
pages = try responseContainer.decode(Int.self, forKey: .pages)
}
}
<file_sep>//
// Data+Extenstion.swift
// MovieAPIUITests
//
// Created by <NAME> on 24/02/2021.
//
import Foundation
private class Token {}
extension Data {
init(from filename: String, extension type: String = "json") throws {
let bundle = Bundle(for: Token.self)
guard let url = bundle.url(forResource: filename, withExtension: type) else {
throw NSError(domain: "tests", code: 1, userInfo: [:]) }
self = try Data(contentsOf: url)
}
}
<file_sep>//
// RecipeDetailView.swift
// TheFood
//
// Created by <NAME> on 06/06/2021.
//
import Kingfisher
import SwiftUI
struct RecipeDetailView: View {
let recipe: RecipeViewModel
@Namespace var topID
var body: some View {
ScrollViewReader { proxy in
ScrollView {
VStack(alignment: .leading) {
KFImage(recipe.image)
.resizable()
.aspectRatio(contentMode: .fit)
.id(topID)
.accessibility(label: Text(recipe.headline))
RecipeHeader(recipe: recipe)
.padding(.horizontal, 6)
Dividers()
AuthorBadgeView(recipe: recipe)
.padding(.horizontal, 6)
.padding(.bottom, 3)
RecipeBody(recipe: recipe)
.padding(.horizontal, 6)
Dividers()
}
ScrollUpButton(proxy: proxy, tag: topID)
.navigationBarTitleDisplayMode(.inline)
}
}
}
}
// }
struct RecipeDetailView_Previews: PreviewProvider {
static var previews: some View {
RecipeDetailView(recipe: RecipeViewModel.all[0])
}
}
<file_sep>//
// RecipeHeader.swift
// TheFood
//
// Created by <NAME> on 10/06/2021.
//
import Foundation
import SwiftUI
struct RecipeHeader: View {
let recipe: RecipeViewModel
var body: some View {
VStack(alignment: .leading) {
Text(recipe.tag)
.font(.system(.subheadline, design: .serif))
.fontWeight(.bold)
.foregroundColor(.pink)
Text(recipe.headline)
.font(.system(.title, design: .serif))
.fontWeight(.bold)
.foregroundColor(.pink)
.padding(.bottom, 10.0)
Text(recipe.trailText)
.font(.system(.body, design: .serif))
.fontWeight(.ultraLight)
}
}
}
<file_sep>//
// GuardianAPIResponseTest.swift
// TheFoodTests
//
// Created by <NAME> on 05/06/2021.
//
@testable import TheFood
import XCTest
class GuardianAPIResponseTest: XCTestCase {
private var data: Data!
override func setUpWithError() throws {
try super.setUpWithError()
data = try Data(from: "exampleResponse")
}
override func tearDownWithError() throws {
try super.tearDownWithError()
data = nil
}
func testInitFromJson() throws {
let response = try GuardianAPI.decoder.decode(GuardianAPI.Response.self, from: data)
XCTAssertEqual(response.results.count, 5)
let recipe = try XCTUnwrap(response.results.first)
XCTAssertEqual(recipe.headline, "<NAME>’ recipe for clotted cream drizzle cake with macerated strawberries")
XCTAssertEqual(
recipe.thumbnail,
URL(string: "https://media.guim.co.uk/59a765b09fa3bb95c0d60705077fdab4900d2152/0_2784_5792_3475/500.jpg")!)
XCTAssertEqual(response.currentPage, 1)
XCTAssertEqual(response.pages, 1596)
}
}
<file_sep>//
// HtmlView.swift
// TheFood
//
// Created by <NAME> on 06/06/2021.
//
import SwiftUI
import WebKit
struct HtmlView: UIViewRepresentable {
let html: String
func makeUIView(context: Context) -> WKWebView {
let configuration = WKWebViewConfiguration()
configuration.ignoresViewportScaleLimits = true
let view = WKWebView(frame: .zero, configuration: configuration)
view.pageZoom = 2
view.scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: view.scrollView.contentSize.height)
return view
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.loadHTMLString(html, baseURL: nil)
}
}
<file_sep>//
// Dividers.swift
// TheFood
//
// Created by <NAME> on 10/06/2021.
//
import Foundation
import SwiftUI
struct Dividers: View {
var body: some View {
VStack(spacing: 4.0) {
Divider()
Divider()
Divider()
Divider()
}
.padding(.bottom, 4)
}
}
<file_sep>//
// FrameColor.swift
// TheFood
//
// Created by <NAME> on 25/05/2021.
//
import Foundation
import SwiftUI
enum FrameColor: CaseIterable {
case brown1, brown2, brown3, brown4, brown5, brown6, brown7
var color: Color {
switch self {
case .brown1:
return Color("choclate-3")
case .brown2:
return Color("choclate")
case .brown3:
return Color("choclate-1")
case .brown4:
return Color("choclate-2")
case .brown5:
return Color("choclate-3")
case .brown6:
return Color("choclate-4")
case .brown7:
return Color("choclate-5")
}
}
}
<file_sep>//
// RecipeBody.swift
// TheFood
//
// Created by <NAME> on 10/06/2021.
//
import Foundation
import SwiftUI
struct RecipeBody: View {
let recipe: RecipeViewModel
var body: some View {
Text(recipe.displayBody)
.font(.system(.body, design: .serif))
.fontWeight(.light)
.multilineTextAlignment(.leading)
}
}
| d8c5d23621e2dfc0841f99367b322c6172b1a2e7 | [
"Swift",
"Markdown"
] | 28 | Swift | jotkafomat/TheFood | 5725863ac0df11de5367a2ba06cf0a1684b276b8 | fd0f06fd7c8a0cccc4b6ff736457d13a419619d2 |
refs/heads/main | <file_sep># WM-EX-TestingRepos
testing version of the WM-Extended Mutations
| f12c1e4cce05860cdb6529f5c4dddd7ff13dfa4b | [
"Markdown"
] | 1 | Markdown | Winged-Monotone/WM-EX-TestingRepos | e28cfa80c5dfa4f268af5511f80c6ae896d2edbb | 6cc0c142abaab9bef5a970487eb55ac00e277295 |
refs/heads/master | <file_sep>(function() {
document.getElementById("movie-card-list").hidden = "hidden";
setTimeout(function() {
document.getElementById("movie-card-list").hidden = "";
document.getElementById("loader").hidden = "hidden";
}, 2000);
})();
var stars;
document.body.addEventListener("click", function(e) {
if (e.target.id.includes("star")) {
stars = e.target.value;
}
});
function addRate(film_id) {
if (stars != undefined) {
fetch("/ratefilm", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
stars,
film_id
})
})
.then(() => {
location.reload();
})
.catch(err => console.log(err));
}
}
<file_sep>const express = require("express");
const queries = require("../model/queries/queries.js");
const router = express.Router();
let combinedData;
router.get("/", (req, res) => {
Promise.all([queries.getAllMovies(), queries.getMovieRate()])
.then(data => {
combinedData = data[0].map(allMovies => {
const allRatings= data[1].filter(x=>x.movie_id===allMovies.id)[0];
return {
...allMovies,
...allRatings
}
}).sort((a,b)=> {return b.rate-a.rate});
res.render("movies", { combinedData })
})
.catch(err => console.log(err));
});
router.post("/ratefilm", (req, res) => {
let stars = req.body.stars;
let film_id = req.body.film_id;
queries
.updateRates(film_id, stars)
.then(x => res.send())
.catch(err => console.log(err));
});
module.exports = router;
<file_sep>module.exports = {
// uppercase: require('./uppercase'),
// age: require('./age')
};
| 2e8621d76f3c781ebc438818222ecce79d857846 | [
"JavaScript"
] | 3 | JavaScript | FACN7/week8_movies_AM | 8ea9577913af30916d017a41fcfd659cacd31434 | 9397d34ddc1ded388a7c8da9fadc39e16791c27e |
refs/heads/master | <file_sep>package li.company.java.client.startup;
import li.company.java.client.view.JavaClient;
public class Startup {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new JavaClient().start();
}
}
<file_sep>package li.company.java.client.view;
import java.util.Scanner;
import li.company.java.client.model.Connection;
import li.company.java.client.model.SocketClient;
public class JavaClient implements Runnable, SocketClient {
private static final String DEFAULT_SERVER = "localhost";
private static final int DEFAULT_PORT = 5000;
private boolean running = false;
private Connection connection = new Connection(this);
private final Scanner console = new Scanner(System.in);
public void start() {
if (running) {
return;
}
running = true;
new Thread(this).start();
}
@Override
public void run() {
while (running) {
String input = console.nextLine();
String[] commands = input.split(" ");
switch (commands[0]) {
case "connect":
if (commands.length > 2) {
connection.connect("http://" + commands[1] + ":" + commands[2]);
} else if (commands.length == 2) {
connection.connect("http://" + commands[1] + ":" + DEFAULT_PORT);
} else {
connection.connect("http://" + DEFAULT_SERVER + ":" + DEFAULT_PORT);
}
break;
case "exit":
connection.exit();
break;
case "results":
System.out.println("Requesting results..");
connection.requestResults();
break;
case "current":
System.out.println("Requesting current key..");
connection.requestCurrent();
break;
default:
printError("Command not found.");
break;
}
}
}
@Override
public void printMessage(String message) {
System.out.println(message);
}
@Override
public void printError(String error) {
System.err.println(error);
}
}
<file_sep># Cipher Brute Force
Program for brute forcing Vigenere ciphered Base64 strings.
Hidden messages are often encoded in Base64 and then ciphered, this makes it extremely hard for a person to crack the original message unless they know the cipher method and cipher key. This program can be used to find likely results and cipher keys for messages encoded in Base64 and then ciphered with a Vigenere cipher.
Note that there's many other cipher methods than Vigenere, this program currently only supports Vigenere ciphered Base64 strings. Vigenere is a common ciphering method so give it a try if you suspect the Base64 string is ciphered. You can assume it is ciphered if it looks like a Base64 string but it can't be decoded.
If you want to generate your own Vigenere ciphered Base64 string you can do this by first encoding a text to Base64 at [https://cryptii.com/](https://cryptii.com/) and then ciphering the Base64 encoded string at [https://www.dcode.fr/vigenere-cipher](https://www.dcode.fr/vigenere-cipher), cipher it by entering the string in the encode field, choose a key of your choice. You can then try cracking it with the program. Use the **text** command on the server to change to the new text. The longer the key is, the longer the brute force will take.
Example:
[Encode base64](https://i.gyazo.com/37584b7e7c10b480a01be018226604e5.png)
[Cipher with vigenere](https://i.gyazo.com/c13e2ff49abd4a358ba7e36d633cea13.png)
[Update to the new text on the server](https://i.gyazo.com/cb230be2330989f2c1cdfb017efbafd7.png)
A 6 character key should be found within 5 minutes depending on computer speed and amount of clients. A 7 character key can take days. The default text has a 6 character key, try running the program to see the brute force in progress, you should find the encoded string in about 1 minute, run multiple clients to increase the speed.
## Client Installation (Requires Java)
Extract the build folder from the Java client (java_client/build) to a location of your choice.
### Run Client
Navigate to the _java_client/build/_ folder.
Open run.bat on windows.
Type _java -jar java_client.jar_ in a command line on other platforms.
### Commands
**connect [server ip] [server port]** - Connects to the server. The field ip and port is optional, default is localhost and 5000.
**current** - Displays the current key that is being handled by any of the clients
**results** - Displays all found results (inclusive false positives)
**exit** - Exits the program after finishing it's current work (Always use this to prevent missing results)
## Server Installation (Requires NPM)
Extract the server folder to a location of your choice, then run install.bat on windows or _npm install_ in a command line on other platforms.
### Run Server
Navigate to the _server_ folder.
Open run.bat on windows.
Type _npm start_ in a command line on other platforms.
### Commands
**text [text]** - Changes the current text that should be cracked by the clients, text is a Base64VigenereString.
**restart** - Restarts the progress, starts cracking from zero (first key).
**padding [padding]** - Determines how many keys each client should crack at a time, padding is a Number.
**current** - Displays the currently handled key.
**performance** - Shows the current average crack speed.
**exit** - Exits the program.
<file_sep>package li.company.java.client.model;
import java.util.Base64;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Crypter {
private static final String CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final Pattern BASE64_REGEX = Pattern.compile("^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$");
private static final Pattern VALID_BASE64_REGEX = Pattern.compile("[AQgw]==$");
private static final Pattern CHAR_REGEX = Pattern.compile("^[…♥>ω<\\n\\r:;@$~=*“”\"'’\\/?!+\\-0-9().,a-zA-Z ]+$");
private static final Pattern ENCODE_REGEX = Pattern.compile("^[=@0-9a-zA-Z]+$");
private static final Pattern START_REGEX = Pattern.compile("^[<~*\"'\\-0-9(a-zA-Z]+$");
public static JSONArray crackB64VigenereCypher(String text, long start, long stop) throws JSONException {
long index = start;
JSONArray keysFound = new JSONArray();
do {
String lastKey = getKey(index);
String lastResult = VigenereCipher.decrypt(text, lastKey);
String decodedB64;
if (lastResult.substring(lastResult.length() - 2, lastResult.length()).equals("==")) {
if (VALID_BASE64_REGEX.matcher(lastResult).find()) {
decodedB64 = new String(Base64.getDecoder().decode(lastResult));
if (isValidDecode(decodedB64)) {
keysFound.put(new JSONObject()
.put("key", lastKey)
.put("value", decodedB64));
}
}
} else {
if (BASE64_REGEX.matcher(lastResult).find()) {
decodedB64 = new String(Base64.getDecoder().decode(lastResult));
if (isValidDecode(decodedB64)) {
keysFound.put(new JSONObject()
.put("key", lastKey)
.put("value", decodedB64));
}
}
}
index++;
} while (index < stop);
return keysFound;
}
private static boolean isValidDecode(String decodedB64) {
if (CHAR_REGEX.matcher(decodedB64).find()) {
if (hasWhitespace(decodedB64)) {
if (START_REGEX.matcher(String.valueOf(decodedB64.charAt(0))).find()) {
return (decodedB64.split("\"").length - 1) % 2 == 0;
}
} else {
/*if (ENCODE_REGEX.matcher(decodedB64).find()) {
return true;
}*/
return true;
}
}
return false;
}
private static boolean hasWhitespace(String text) {
return Pattern.compile("\\s").matcher(text).find();
}
private static String getKey(long n) {
return (n >= 26 ? getKey((n / 26) - 1) : "") + CHARSET.charAt((int) (n % 26));
}
}
<file_sep>package li.company.java.client.model;
import io.socket.client.IO;
import io.socket.client.Socket;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Connection {
private Socket socket = null;
private boolean connected = false;
private SocketClient client;
private String curServer = "";
private boolean exit = false;
public Connection(SocketClient client) {
this.client = client;
}
public void connect(String server) {
if (socket != null) {
socket.disconnect();
}
try {
socket = IO.socket(server);
curServer = server;
socket.on(Socket.EVENT_CONNECT, (Object... args) -> {
connected = true;
client.printMessage("Successfully connected to " + curServer);
socket.emit("request_decode");
client.printMessage("Brute force started");
}).on("decode_this", (Object... args) -> {
try {
JSONObject data = (JSONObject) args[0];
JSONArray results = Crypter.crackB64VigenereCypher(data.getString("text"), data.getLong("start"), data.getLong("stop"));
socket.emit("decode_result", new JSONObject()
.put("text", data.getString("text"))
.put("result", results)
.put("start", data.getString("start"))
.put("stop", data.getString("stop")));
if (exit) {
disconnect();
System.exit(0);
} else {
socket.emit("request_decode");
}
} catch (JSONException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
}).on("decode_found", (Object... args) -> {
try {
JSONObject data = (JSONObject) args[0];
JSONArray results = data.getJSONArray("result");
client.printMessage("Potential keys found:");
for (int i = 0; i < results.length(); i++) {
client.printMessage(
results.getJSONObject(i).getString("key") + ": "
+ results.getJSONObject(i).getString("value"));
}
} catch (JSONException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
}).on("results", (Object... args) -> {
try {
JSONObject data = (JSONObject) args[0];
if (data.length() == 0) {
client.printMessage("No results found");
}
Iterator<String> keys = data.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
client.printMessage(key + ": " + data.getString(key));
}
} catch (JSONException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
}).on("current", (Object... args) -> {
client.printMessage("Current key: " + args[0]);
}).on("exit", (Object... args) -> {
System.exit(0);
}).on(Socket.EVENT_DISCONNECT, (Object... args) -> {
connected = false;
client.printError("Disconnected");
});
socket.connect();
} catch (URISyntaxException ex) {
client.printError("Failed to connect to socket");
}
}
public boolean isConnected() {
return connected;
}
public void exit() {
if (isConnected()) {
exit = true;
} else {
System.exit(0);
}
}
private void disconnect() {
socket.disconnect();
}
public void requestResults() {
socket.emit("request_results");
}
public void requestCurrent() {
socket.emit("request_current");
}
}
<file_sep>const http = require('http').createServer();
const socketio = require('socket.io')(http);
var fs = require('fs');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
/* Charset */
var charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* Text to decode */
var text = "<KEY>";
/* Regex */
var numberRegex = /^\d+$/;
var keyRegex = /^[A-Z]+$/;
/* Results */
var foundResults = {};
/* General */
var current = 0;
var padding = 10000;
/* Performance compare */
var performance = 0;
var old = current;
/* Empty results on start */
fs.truncate('results.txt', 0, () => {});
readline.on('line', function (input) {
var commands = input.split(' ');
switch (commands[0]) {
case 'exit':
exitHandler({cleanup: true});
break;
case 'restart':
restart();
break;
case 'text':
if (commands[1]) {
text = commands[1];
restart();
console.log('New text set to: ' + text);
} else {
console.log('Current text: ' + text);
}
break;
case 'padding':
if (commands[1]) {
padding = parseInt(commands[1]);
console.log('New padding set to: ' + padding);
} else {
console.log('Current padding: ' + padding);
}
break;
case 'current':
var value = commands[1];
if (value) {
if (numberRegex.test(value)) {
current = parseInt(value);
} else if (keyRegex.test(value)) {
current = toNumber(value);
} else {
console.log('Incorrect value');
}
console.log('New index set to: ' + toRadix(current, charset));
} else {
printCurrent();
}
break;
case 'performance':
printPerformance();
break;
}
});
socketio.on('connection', function (socket) {
console.log('Socket connected');
socket.on('decode_result', function (data) {
if (data.result.length > 0) {
for (var i = 0; i < data.result.length; i++) {
console.log(data.result[i].key + ': ' + data.result[i].value);
foundResults[data.result[i].key] = data.result[i].value;
fs.appendFile('results.txt', data.result[i].key + ": " + data.result[i].value + "\n", function (err) {
if (err) return console.log(err);
});
}
socketio.emit('decode_found', data);
}
});
socket.on('request_decode', function () {
newDecode(socket);
});
socket.on('request_results', function () {
socket.emit('results', foundResults);
});
socket.on('request_current', function () {
socket.emit('current', toRadix(current, charset));
});
socket.on('disconnect', function () {
console.log("Socket disconnected");
});
});
function newDecode(socket) {
socket.emit('decode_this', {
text: text,
start: current,
stop: current + padding,
charset: charset
});
current += padding;
}
function toRadix(n, charset) {
var result = [];
n++;
while (n !== 0) {
result.unshift(charset.charAt((n - 1) % charset.length));
n = Math.floor((n - 1) / charset.length);
}
return result.join('');
}
function toNumber(str) {
var out = 0, len = str.length;
for (var pos = 0; pos < len; pos++) {
out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - pos - 1);
}
return out - 1;
}
function restart() {
foundResults = {};
current = 1;
}
function statusCheck(print) {
if (print) {
printPerformance();
printCurrent();
}
performance = (current - old) / 10;
old = current;
setTimeout(function () {
statusCheck(print);
}, 10 * 1000);
}
function printPerformance() {
console.log("Performance: " + performance + " keys/s");
}
function printCurrent() {
console.log("Current index: " + toRadix(current, charset));
}
http.listen(5000, function () {
console.log('listening on *:5000');
var print = false;
if (process.argv[2]) {
print = true;
}
statusCheck(print);
});
process.stdin.resume(); //so the program will not close instantly
//do something when app is closing
process.on('exit', exitHandler.bind(null, {cleanup: true}));
//catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {cleanup: true}));
// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', exitHandler.bind(null, {cleanup: true}));
process.on('SIGUSR2', exitHandler.bind(null, {cleanup: true}));
//catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {cleanup: true}));
function exitHandler(options, err) {
if (options.cleanup) {
//socketio.emit('exit');
process.exit()
}
if (err) console.log(err.stack);
if (options.exit) process.exit();
} | 7028a8c4408a9abf57f74f877f1370364b4dd2c2 | [
"Markdown",
"Java",
"JavaScript"
] | 6 | Java | phek/cipher_bruteforce | 5c2d5cdca4fc391bb90c34870d76b4422e37f2fa | 3306847f004444767498578f5fcfc343320c5fc1 |
refs/heads/master | <repo_name>lnhote/leetcodego<file_sep>/actest/test.go
package actest
import (
"fmt"
"github.com/stretchr/testify/assert"
)
type SimpleTest struct {
}
var (
t = SimpleTest{}
)
func (t SimpleTest) Errorf(format string, args ...interface{}) {
fmt.Printf(format, args...)
}
func Equal(expected, actual interface{}, msgAndArgs ...interface{}) bool {
return assert.Equal(t, expected, actual, msgAndArgs...)
}
func True(actual bool, msgAndArgs ...interface{}) bool {
return assert.True(t, actual, msgAndArgs...)
}
func False(actual bool, msgAndArgs ...interface{}) bool {
return assert.False(t, actual, msgAndArgs...)
}
func EqualValues(expected, actual interface{}, msgAndArgs ...interface{}) bool {
return assert.EqualValues(t, expected, actual, msgAndArgs...)
}<file_sep>/node/type.go
package node
import (
"fmt"
"strings"
"strconv"
)
/**
* Definition for singly-linked list.
*/
type ListNode struct {
Val int
Next *ListNode
}
func (l *ListNode) String() string {
arr := []string{}
for l != nil {
arr = append(arr, strconv.Itoa(l.Val))
l = l.Next
}
return strings.Join(arr, "->")
}
func New(arr []int) *ListNode {
l := &ListNode{}
p := l
for i, val := range arr {
p.Val = val
if i != len(arr)-1 {
p.Next = &ListNode{}
}
p = p.Next
}
return l
}
func Print(head *ListNode) {
for head != nil {
fmt.Print(head.Val)
head = head.Next
}
fmt.Print("\n")
}<file_sep>/wildcard_matching.go
package main
import (
"github.com/lnhote/leetcodego/actest"
)
// https://leetcode.com/problems/wildcard-matching/description/
// '?' Matches any single character.
// '*' Matches any sequence of characters (including the empty sequence).
func isMatch(s string, p string) bool {
dp := make([][]bool, len(s)+1)
for i := 0; i <= len(s); i++ {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for i := 1; i <= len(s); i++ {
dp[i][0] = false
}
for j := 1; j <= len(p); j++ {
dp[0][j] = p[j-1] == '*' && dp[0][j-1]
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
// match 1, match more than 1, or match none
dp[i][j] = dp[i-1][j-1] || dp[i-1][j] || dp[i][j-1]
} else if p[j-1] == '?' {
dp[i][j] = dp[i-1][j-1]
} else {
dp[i][j] = dp[i-1][j-1] && s[i-1] == p[j-1]
}
// fmt.Printf("dp[%d][%d]=%v\n", i, j, dp[i][j])
}
}
return dp[len(s)][len(p)]
}
func main() {
actest.False(isMatch("", "?"))
actest.False(isMatch("aab", "c*a*b"))
actest.False(isMatch("aa", "a"))
actest.True(isMatch("aa", "a*"))
actest.True(isMatch("aa", "*"))
actest.True(isMatch("a", "a*"))
actest.True(isMatch("aaaaa", "a*"))
actest.False(isMatch("cb", "?a"))
actest.True(isMatch("adceb", "*a*b"))
actest.False(isMatch("acdcb", "a*c?b"))
actest.True(isMatch("abbabbbaabaaabbbbbabbabbabbbabbaaabbbababbabaaabbab", "*aabb***aa**a******aa*"))
}
<file_sep>/roman_to_integer.go
package main
import (
"github.com/lnhote/leetcodego/actest"
)
const (
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
)
var (
symboles = map[uint8]int{
'I': I,
'V': V,
'X': X,
'L': L,
'C': C,
'D': D,
'M': M,
}
)
//Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999
func romanToInt(s string) int {
if len(s) == 0 {
return 0
}
result := 0
var last = 0
for i:= 0; i<len(s); i++ {
if value, ok := symboles[s[i]]; ok {
result += value
if last != 0 && (value / last == 10 || value / last == 5) {
result -= last * 2
}
last = value
} else {
return 0
}
}
return result
}
func main() {
actest.Equal(3, romanToInt("III"))
actest.Equal(4, romanToInt("IV"))
actest.Equal(9, romanToInt("IX"))
actest.Equal(58, romanToInt("LVIII"))
actest.Equal(1994, romanToInt("MCMXCIV"))
}<file_sep>/partition_equal_subset_sum.go
package main
import (
"github.com/lnhote/leetcodego/actest"
)
func canPartition(nums []int) bool {
sum := 0
for _, num := range nums {
sum += num
}
if sum%2 == 1 {
return false
}
sum = sum / 2
n := len(nums)
// dp[i][j] means whether the specific sum j can be gotten from the first i numbers.
// i=0 means pick no number
// if we can pick such a series of numbers from 0-i whose sum is j, dp[i][j] is true, otherwise it is false.
dp := make([][]bool, n+1)
for i := 0; i <= n; i++ {
dp[i] = make([]bool, sum+1)
}
for i := 0; i <= n; i++ {
dp[i][0] = true
}
for i := 1; i <= n; i++ {
num := nums[i-1]
for j := 1; j <= sum; j++ {
dp[i][j] = dp[i-1][j]
if j >= num {
// fmt.Printf("dp[%d][%d]=%+v\n", i-1, j, dp[i-1][j])
dp[i][j] = dp[i][j] || dp[i-1][j-num]
// fmt.Printf("sum(%d) >= num(%d): dp[%d][%d]=%+v\n", j, num, i, j, dp[i][j])
}
}
}
return dp[n-1][sum]
}
func main() {
actest.Equal(false, canPartition([]int{1, 2, 3, 4, 5, 6})) // false
actest.Equal(true, canPartition([]int{2, 2, 2, 3, 3})) // true
actest.Equal(true, canPartition([]int{2, 2, 2, 2, 2, 5, 5})) // true
actest.Equal(false, canPartition([]int{6, 4, 4})) // false
actest.Equal(true, canPartition([]int{1, 1, 1, 3, 4})) // true
actest.Equal(true, canPartition([]int{1, 5, 11, 5})) // true
actest.Equal(false, canPartition([]int{1, 2, 5})) // false
}
<file_sep>/longest_palindromic_substring.go
package main
import (
"github.com/lnhote/leetcodego/actest"
)
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
func longestPalindrome(s string) string {
if len(s) < 2 {
return s
}
maxStr := ""
for i:= 0; i<len(s); i++ {
sub1 := expandAroundCenter(s, i, i)
sub2 := expandAroundCenter(s, i, i+1)
if len(sub1) > len(maxStr) {
maxStr = sub1
}
if len(sub2) > len(maxStr) {
maxStr = sub2
}
}
return maxStr
}
func expandAroundCenter(s string, left, right int) string {
if left < 0 || right > len(s) - 1 || s[left] != s[right] {
return ""
}
L := left
R := right
for L >= 0 && R < len(s) && s[L] == s[R] {
L--
R++
}
// log.Printf("expandAroundCenter[%s][%d, %d]=[%d, %d]", s, left, right, L+1, R)
return s[L+1:R]
}
func main() {
actest.Equal("bab", longestPalindrome("babad"))
actest.Equal("bb", longestPalindrome("cbbd"))
actest.Equal("aaaabaaaa", longestPalindrome("aaaabaaaaaaaa"))
actest.Equal("aaaabbaaaa", longestPalindrome("aaaabbaaaaaaaa"))
}<file_sep>/add_two_numbers.go
package main
import (
. "github.com/lnhote/leetcodego/node"
)
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
// Explanation: 342 + 465 = 807.
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
carry := 0
var prev *ListNode = nil
var head *ListNode = nil
var p *ListNode
for (l1 != nil || l2 != nil) {
sum := 0
if l1 != nil {
sum += l1.Val
l1 = l1.Next
}
if l2 != nil {
sum += l2.Val
l2 = l2.Next
}
sum += carry
if sum >= 10 {
carry = 1
sum = sum - 10
} else {
carry = 0
}
p = &ListNode{sum, nil}
if prev != nil {
prev.Next = p
} else {
head = p
}
prev = p
}
if carry > 0 && prev != nil {
prev.Next = &ListNode{carry, nil}
}
return head
}
func main() {
var n1 = New([]int{2,4,3})
var n2 = New([]int{5,6,4})
Print(n1)
Print(n2)
Print(addTwoNumbers(n1, n2))
}<file_sep>/title_to_num.go
package main
import "github.com/lnhote/leetcodego/actest"
// https://leetcode.com/problems/excel-sheet-column-number/description/
func titleToNumber(s string) int {
if len(s) == 0 {
return 0
}
sum := 0
for i := 0; i < len(s); i++ {
num := int(s[i] - 'A' + 1)
sum = sum*26 + num
}
return sum
}
func main() {
actest.Equal(titleToNumber("A"), 1)
actest.Equal(titleToNumber("B"), 2)
actest.Equal(titleToNumber("Z"), 26)
actest.Equal(titleToNumber("AA"), 27)
actest.Equal(titleToNumber("BA"), 53)
actest.Equal(titleToNumber("ZY"), 701)
}
<file_sep>/3sum.go
package main
import (
"fmt"
"sort"
)
func main() {
// -4, -1, -1, 0, 1, 2
fmt.Println(threeSum([]int{-1, 0, 1, 2, -1, -4})) // [ [-1, 0, 1], [-1, -1, 2] ]
fmt.Println(threeSum([]int{-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0})) // [[-5,1,4],[-4,0,4],[-4,1,3],[-2,-2,4],[-2,1,1],[0,0,0]]
}
// https://leetcode.com/problems/3sum/
// The solution set must not contain duplicate triplets.
func threeSum(nums []int) [][]int {
if len(nums) < 3 {
return [][]int{}
}
if !sort.IntsAreSorted(nums) {
sort.Ints(nums)
}
result := [][]int{}
for i:=0; i<len(nums)-2; i++ {
if i > 0 && nums[i] == nums[i-1] {
continue
}
a := nums[i]
sumBC := 0 - a
lo := i+1
hi := len(nums)-1
for lo < hi {
b := nums[lo]
c := nums[hi]
if b + c < sumBC {
lo++
} else if b + c > sumBC {
hi--
} else {
result = append(result, []int{a, b, c})
for ;lo < hi && nums[lo] == nums[lo+1]; {
lo++
}
for ;lo < hi && nums[hi] == nums[hi-1]; {
hi--
}
lo++
hi--
}
}
}
return result
}
<file_sep>/remove_dup_from_sorted_list.go
package main
// https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
// Given a sorted linked list, delete all duplicates such that each element appear only once.
import (
. "github.com/lnhote/leetcodego/node"
"github.com/lnhote/leetcodego/actest"
)
func deleteDuplicates(head *ListNode) *ListNode {
if head == nil {
return nil
}
mark := head
p := head.Next
for p != nil {
if p.Val == mark.Val {
mark.Next = p.Next
} else {
mark = p
}
p = p.Next
}
return head
}
func main() {
actest.Equal(New([]int{1}), deleteDuplicates(New([]int{1,1,1})))
actest.Equal(New([]int{1,2}), deleteDuplicates(New([]int{1,1,2})))
actest.Equal(New([]int{1,2,3}), deleteDuplicates(New([]int{1,1,2,3,3})))
}<file_sep>/container_with_most_water.go
package main
import (
"github.com/lnhote/leetcodego/actest"
)
// https://leetcode.com/problems/container-with-most-water/description/
func maxArea(height []int) int {
max:=0
lo:=0
hi:=len(height)-1
for lo < hi {
min := 0
if height[lo]>=height[hi] {
min = height[hi]
} else {
min = height[lo]
}
if min*(hi-lo) >= max {
max = min*(hi-lo)
}
if height[lo]>=height[hi] {
hi--
} else {
lo++
}
}
return max
}
func main() {
actest.Equal(49, maxArea([]int{1,8,6,2,5,4,8,3,7}))
}<file_sep>/two_sum.go
package main
import (
"github.com/lnhote/leetcodego/actest"
)
func twoSum(nums []int, target int) []int {
dic := make(map[int]int, len(nums))
var r1, r2 int
for _, v := range nums {
counterpart := target - v
if exist, ok := dic[counterpart]; exist == 1 && ok {
return []int{v, counterpart}
} else {
dic[v] = 1
}
}
return []int{r1, r2}
}
func main() {
actest.EqualValues([]int{4,2}, twoSum([]int{1,2,3,4,5}, 6))
} | 61fc948fa865f10dcb2b3f8bb4d65815fb290e6c | [
"Go"
] | 12 | Go | lnhote/leetcodego | c2448c46ed9ad747d2a48dd12e62ddc480bda060 | 990ae5f258fa24d8995ce9744ce36591ebe9646e |
refs/heads/master | <file_sep># Mapping Tool for Learning Poverty Data
This is an open source script to map the learning poverty data. See the Learning Poverty github repo for more details on how this measure is constructed. https://github.com/worldbank/LearningPoverty.
This is a personal project, and should not be viewed as an official World Bank project.
The data for this project is pulled from the World Bank open data API, and should be entirely reproducible. The shape file is downloaded from open source sources as well. Shape file was retrieved from https://datahub.io/core/geo-countries. The original data comes from Natural Earth and is public domain. I appreciate the organizations Natural Earth, Lexman and the Open Knowledge Foundation for this data.
As a significant contributor to human capital deficits, the learning crisis undermines sustainable growth and poverty reduction. The paper introduces the new concept of _learning poverty_ and provides a synthetic indicator with global coverage to spotlight this crisis. _Learning poverty_ means being unable to read and understand a short, age-appropriate text by age 10. This indicator brings together schooling and learning by adjusting the proportion of kids in school bellow a proficiency threshold by the out-of-school population.
The new data show that **more than half of all children in World Bank client countries suffer from _learning poverty_** – the majority of them low- and middle-income countries. And progress in reducing _learning poverty_ is far too slow to meet the SDG aspirations: even if countries reduce their _learning poverty_ at the fastest rates we have seen so far in this century, the goal of ending it will not be attained by 2030.
<sup>[1] <NAME>., and others. 2019. _“Will Every Child Be Able to Read by 2030? Why Eliminating Learning Poverty Will Be Harder Than You Think, and What to Do About It.”_ World Bank Policy Research Working Paper series. Washington, DC: World Bank.</sup>
Map can be viewed at
http://rpubs.com/stacybw/learning_poverty_map
I will try to update as new data is released.
<file_sep>#This is a simple script to pull learning poverty data from the World Bank API and map the data using leaflet
#links to the shape file used is embedded in the code.
# Author: <NAME> 10/17/2019
library(tidyverse)
library(WDI)
library(leaflet)
library(htmlwidgets)
#Set directory to save work
save_dir<-"C:/Users/wb469649/Documents/Github/learning_poverty_map"
#list of indicators
ind_list <- c( "SE.LPV.PRIM", "SE.LPV.PRIM.FE", "SE.LPV.PRIM.MA", "SE.LPV.PRIM.OOS", "SE.LPV.PRIM.OOS.FE", "SE.LPV.PRIM.OOS.MA",
"SE.LPV.PRIM.BMP", "SE.LPV.PRIM.BMP.FE", "SE.LPV.PRIM.BMP.MA")
#read in data from wbopendata
dat<-WDI(indicator=ind_list, start=2011, end=2019, extra=T) %>%
filter(!is.na(SE.LPV.PRIM) & !is.na(country)) %>%
group_by(iso3c) %>%
arrange(year) %>%
filter(row_number()==n())
#do some processing on lat/long
dat <- dat %>%
mutate(ISO_A3=iso3c)
#read in TopoJSON polygon file
#downloaded https://datahub.io/core/geo-countries#data
shape_dir<-"C:/Users/wb469649/Documents/Github/learning_poverty_map"
countries <- geojsonio::geojson_read(paste(shape_dir,"countries.geojson", sep="/"),
what = "sp")
countries@data <- countries@data %>%
left_join(dat) %>%
mutate(prof=100-SE.LPV.PRIM)
#create pallete
bins <- c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
pal <- colorBin("RdYlGn", domain = countries@data$SE.LPV.PRIM, bins = bins, reverse=TRUE)
#create labels
labels <- sprintf(
"<strong>%s</strong><br/> <hr size=2>
<strong> %g%% </strong> Overall Learning Poverty <br/>
<strong> %g%% </strong> Male Learning Poverty <br/>
<strong> %g%% </strong> Female Learning Poverty <br/> <hr size=1>
<strong> %g%% </strong> Overall Children Out of School <br/>
<strong> %g%% </strong> Male Children Out of School <br/>
<strong> %g%% </strong> Female Children Out of School <br/> <hr size=1>
<strong> %g%% </strong> Overall Pupils below minimum reading proficiency <br/>
<strong> %g%% </strong> Male Pupils below minimum reading proficiency <br/>
<strong> %g%% </strong> Female Pupils below minimum reading proficiency ",
countries@data$ADMIN, round(countries@data$SE.LPV.PRIM, digits = 1), round(countries@data$SE.LPV.PRIM.MA, digits = 1), round(countries@data$SE.LPV.PRIM.FE, digits = 1),
round(countries@data$SE.LPV.PRIM.OOS, digits = 1), round(countries@data$SE.LPV.PRIM.OOS.MA, digits = 1), round(countries@data$SE.LPV.PRIM.OOS.FE, digits = 1),
round(countries@data$SE.LPV.PRIM.BMP, digits = 1), round(countries@data$SE.LPV.PRIM.BMP.MA, digits = 1), round(countries@data$SE.LPV.PRIM.BMP.FE, digits = 1)
) %>%
lapply(htmltools::HTML)
m <- leaflet(countries) %>%
addTiles() %>%
addPolygons(stroke = FALSE, smoothFactor = 0.3, fillOpacity = 0.7,
fillColor = ~pal(SE.LPV.PRIM),
popup=labels) %>%
addLegend(pal=pal, values=~SE.LPV.PRIM, opacity=0.7, title="Learning Poverty", position="bottomright")
m
saveWidget(m, file=paste(save_dir,"learning_poverty_map.html", sep="/"))
| 8e22d28b99963b040098ce9fd38be95e56b088fc | [
"Markdown",
"R"
] | 2 | Markdown | stacybri/learning_poverty_map | a2034dacbb6aef70a9ac834af06a0062a25ee6dd | 4d54350d8797b5df5494a371420c8579db65ac57 |
refs/heads/master | <repo_name>alpha-000/PLWebsite<file_sep>/store.php
<html>
<body>
<link rel="stylesheet" href="main.css">
<h3 color: #263238;>Welcome<h3>
<?php
$name = $_POST["username"];
echo $name.'!';
function add(){ //Adds song to specified playlist/file
list($si,$ati,$abi) = explode(", " , $_POST["buy"]);
$location = $_POST['addition'];
$library = fopen($location.".txt","a+") or die("Refresh browser");
$input = $si." ".$ati." ".$abi; //Specifies format for file
$library = fwrite($library,$input);
}
function createFile($file){ //Creates table for available songs according to file specified
$songs = fopen($file, "r") or die("Refresh browser");
echo "<table>"."<tr>" //Creates base for table
."<th>".'Song'."<th>"
."<th>".'Artist'."<th>"
."<th>".'Album'."<th>"
."<th>"."</th>"
."</tr>";
do { //Populates table with file
list($s,$at,$ab) = explode(" ", fgets($songs));
if(strlen($s) == 0)
break;
echo "<tr>"
."<td>".$s."<td>"
."<td>".$at."<td>"
."<td>".$ab."<td>"
."<td>" //adds button to help add purchased songs into specified playlist and refresh page
."<form action = \"store.php\" method = \"post\">"."<input type = \"text\" name =\"addition\">"."<button type = \"submit\" name = \"buy\" value = \"$s, $at, $ab\">purchase"."</button>\n"."</form>"
."</tr>";
} while(!feof($songs));
echo ".</table>";
}
function playlists($file){//Creates table for available playlists
$songs = fopen($file, "r") or die("Refresh browser");
$s = "library";
echo "<table>"."<tr>"//Creates base for table
."<th>".'Playlists'."<th>"
."<th>"."<th>"
."<th>"."<th>"
."<th>"."<th>"
."</tr>"
."<tr>"
."<td>".$s."<td>"
."<td>"
."<form action = \"my_playlist.php\" method = \"post\">"."<button type = \"submit\" name = \"openplay\" value = \"$s\">open"."</button>\n"."</form>"
."<td>"
."<td>"
."<form action = \"store.php\" method = \"post\">"."<button type = \"submit\" name = \"deleteplay\" value = \"$s\">delete"."</button>\n"."</form>"
."<td>"
."</tr>";
do { //Populates table with playlists
$s = fgets($songs);
if((preg_match("/[a-z]/i",$s))){
fopen(substr($s,0,-1).".txt","a");
echo "<tr>"
."<td>".$s."<td>"
."<td>"//Creates button to open playlist and access my_playlist
."<form action = \"my_playlist.php\" method = \"post\">"."<button type = \"submit\" name = \"openplay\" value = \"$s\">open"."</button>\n"."</form>"
."<td>"
."<td>"//Creates button to delete playlist and refresh page
."<form action = \"store.php\" method = \"post\">"."<button type = \"submit\" name = \"deleteplay\" value = \"$s\">delete"."</button>\n"."</form>"
."<td>"
."<td>"//Creates button to rename file and pass information from previous file to new file
."<form action = \"store.php\" method = \"post\">"."<input type = \"text\" name = \"rname\">"."<button type = \"submit\" name = \"rename\" value = \"$s\">rename"."</button>\n"."</form>"
."<td>"
."</tr>";
}
} while(!feof($songs));
echo ".</table>";
}
if (isset($_POST["buy"])){//Creates logic for purchase button
add();
}
if (isset($_POST["deleteplay"])){//Creates logic for delete button for playlist
$deletion = $_POST["deleteplay"];
$deletion2 = substr($_POST["deleteplay"],0,-2);
$list = fopen("playlists.txt","r");
$listcontents;
while(!feof($list)){ //populates listcontents with current file content
$curr = fgets($list);
$listcontents = $listcontents.";".$curr;
}
$list = fopen("playlists.txt","w+");//Overwrites file
$listcontents = substr($listcontents,0,-1);
$listcontents = str_replace(";"."$deletion2","",$listcontents);//Gets rid of specified playlist in file
$contents = explode(";", $listcontents);
for($x = 1; $x < count($contents); $x++){
if(preg_match("/[a-z]/i",$contents[$x])){//Repopulates file
fwrite($list,$contents[$x]);
}
}
}
if (isset($_POST["createplay"]) && isset($_POST["playname"])){//Creates new playlist
$playlistname = $_POST["playname"];
$list = fopen("playlists.txt", "a+");
fwrite($list, $playlistname."\n");//Adds playlist to the playlist file
fclose($list);
}
if(isset($_POST["rename"]) && isset($_POST["rname"])){//Creates logic for renaming playlist
$deletion = $_POST["rename"];
$deletion2 = substr($_POST["rename"],0,-2);
$list = fopen("playlists.txt","r");
$listcontents;
while(!feof($list)){ //populates listcontents with current file content
$curr = fgets($list);
$listcontents = $listcontents.";".$curr;
}
$list = fopen("playlists.txt","w+");
$listcontents = substr($listcontents,0,-1);
$listcontents = str_replace(";"."$deletion2",";".$_POST['rname'],$listcontents);//Replaces current name with new name
echo $listcontents;
$contents = explode(";", $listcontents);
for($x = 1; $x < count($contents); $x++){//Repopulates file with the new name
if(preg_match("/[a-z]/i",$contents[$x])){
fwrite($list,$contents[$x]);
}
$list2 = fopen(trim($deletion).".txt","r");
$list3 = fopen(trim($_POST['rname']).".txt","w+");//Transfers file contents from previous file to the new playlists file
while(!feof($list2)){
$line = fgets($list2);
fwrite($list3, $line);
}
}
}
?>
<h2>Lollipop Tunes</h2>
<?php
createFile("lollipop.txt");
?>
<p>
<h2>Oreo Tunes</h2>
</p>
<?php
createFile("oreo.txt");
?>
<p>
<h2>Playlists</h2>
</p>
<?php
playlists("playlists.txt");
echo
"<form action = \"store.php\" method = \"post\">"
."<input type = \"text\" name = \"playname\">"
."<button type = \"submit\" name = \"createplay\" value = \"$s\">create"."</button>\n"."</form>";
?>
</body>
</html>
<file_sep>/README.md
# PLWebsite
The log in does not have the backgound logic once logged in all the users will be connected to the same website where all the changes will be made to same playlits, both adding and subtracting playlists/songs.
<file_sep>/my_playlist.php
<html>
<body>
<link rel="stylesheet" href="main.css">
<?php
echo "<table>"."<tr>"//Creates table
."<th>".'Song'."<th>"
."<th>".'Artist'."<th>"
."<th>".'Album'."<th>"
."<th>"."</th>"
."<th>"."</th>"
."<th>"."</th>"
."</tr>";
$file = $_POST["openplay"]; //Creates file based off name passed to file
$library = fopen(trim($file).".txt", "r") or die("error");
do { //Populates playlist with information from current file
list($s,$at,$ab) = explode(" ", fgets($library));
if(preg_match("/[a-z]/i",$s)){
echo "<tr>"
."<td>".$s."<td>"
."<td>".$at."<td>"
."<td>".$ab."<td>"
."<td>"."<button type = \"submit\"> play"."</button>"
."<td>"//Passes file name to refreshed website using hidden button and removes song
."<form action = \"my_playlist.php\" method = \"post\">"."<input type = \"hidden\" name = \"openplay\" value = \"$file\">"
."<button type = \"submit\" name = \"delete\" value = \"$s,$at,$ab\">remove"."</button>\n"."</form>"
."<td>"
."<td>"//Annotates current song name
."<form action = \"my_playlist.php\" method = \"post\">"."<input type = \"hidden\" name = \"openplay\" value = \"$file\">"."<input type = \"text\" name = \"annotate\">"."<button type = \"submit\" name = \"anname\" value = \"$s\">rename"."</button>\n"."</form>"
."<td>"
."</tr>";
}
} while(!feof($library));
echo ".</table>";
if (isset($_POST["delete"])){//Creates logic for removal
$library = fopen(trim($file).".txt", "r") or die("error");
$deletion = $_POST["delete"];
$deletion2 = substr($_POST["delete"],0,-2);
$listcontents;
while(!feof($library)){//Fills listcontents with current file contents
$curr = fgets($library);
$listcontents = $listcontents.";".$curr;
}
$library = fopen(trim($file).".txt", "w+") or die("error");//Clears file
$listcontents = substr($listcontents,0,-1);
list($s,$at,$ab) = explode(",",$deletion);
$listcontents = str_replace(";".$s." ".$at." ".$ab,"",$listcontents);//Gets rid of specified song
$contents = explode(";", $listcontents);
for($x = 1; $x < count($contents); $x++){//Repopulates file without song
if(preg_match("/[a-z]/i",$contents[$x])){
fwrite($library,$contents[$x]);
}
//echo $contents[$x]." ".strcmp($deletion,$contents[$x])." ";
}
}
if(isset($_POST["annotate"]) && isset($_POST["anname"])){//Creates logic for annotate
$library = fopen(trim($file).".txt", "r") or die("error");
$deletion = $_POST["anname"];
$deletion2 = substr($_POST["anname"],0,-2);
$listcontents;
while(!feof($library)){//Fills listcontents with current file contents
$curr = fgets($library);
$listcontents = $listcontents.";".$curr;
}
$library = fopen(trim($file).".txt", "w+") or die("error");//clears file
$listcontents = substr($listcontents,0,-1);
list($s,$at,$ab) = explode(",",$deletion);
$listcontents = str_replace(";".$s,";".trim($_POST['annotate']),$listcontents);//Replaces song name with new name
$contents = explode(";", $listcontents);
for($x = 1; $x < count($contents); $x++){
if(preg_match("/[a-z]/i",$contents[$x])){//Repopulates file
fwrite($library,$contents[$x]);
}
}
}
?>
<form method="post" action="store.php">
<p align="middle"><b>Buy More Songs!</b>
<button type="submit">Go Back:</button>
</p>
</form>
</body>
</html>
| 64d1e63d80269299e22389f992112974c14cda3f | [
"Markdown",
"PHP"
] | 3 | PHP | alpha-000/PLWebsite | 0c45e58a294e149735e60c92fff6f78f98ebccb7 | 541c5e8533818296deb1fe344d760c03f988a728 |
refs/heads/master | <repo_name>Vishwanathavin/MLprojects<file_sep>/README.md
# MLprojects
This repo consists of fun projects that I did as a part of the various online machine learning courses I took
<file_sep>/Digit_recognizer/main.py
import numpy as np
import pandas as pd
#%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import tensorflow as tf
# settings
LEARNING_RATE = 1e-4
# set to 20000 on local environment to get 0.99 accuracy
TRAINING_ITERATIONS = 2500
DROPOUT = 0.5
BATCH_SIZE = 50
# set to 0 to train on all available data
VALIDATION_SIZE = 2000
# image number to output
IMAGE_TO_DISPLAY = 10
# read training data from CSV file
data = pd.read_csv('../input/train.csv')
print('data({0[0]},{0[1]})'.format(data.shape))
print (data.head())
images = data.iloc[:,1:].values
images = images.astype(np.float)
# convert from [0:255] => [0.0:1.0]
images = np.multiply(images, 1.0 / 255.0)
print('images({0[0]},{0[1]})'.format(images.shape))
image_size = images.shape[1]
print ('image_size => {0}'.format(image_size))
# in this case all images are square
image_width = image_height = np.ceil(np.sqrt(image_size)).astype(np.uint8)
print ('image_width => {0}\nimage_height => {1}'.format(image_width,image_height))
# display image
def display(img):
# (784) => (28,28)
one_image = img.reshape(image_width, image_height)
plt.axis('off')
plt.imshow(one_image, cmap=cm.binary)
# output image
display(images[IMAGE_TO_DISPLAY])
<file_sep>/utils/ndim_grid.py
import numpy as np
# for i,j in zip(range(0,10),range(0,15)):
# print i,j
text=[[0 for i in range(10)] for j in range(10)]
# print np.linspace(i,j,10)[:-1]
# for i in range(0,2):
# for j in range(0,2):
# text[i][j] = [i,j]
print text
# np.linspace(i,j,10) for i,j in zip(0,10) | 8891c023a6932c46c4e033dd5e10e1f2ca7b2542 | [
"Markdown",
"Python"
] | 3 | Markdown | Vishwanathavin/MLprojects | 472dd997ebeb76f1286ff47e71306e6be2f75907 | fb65c11f9421f7eada62805292c64d18595112d3 |
refs/heads/master | <file_sep>require "java"
require "rbenv"
require "rbenv/rack"
require "jenkins/rack"
class RbenvDescriptor < Jenkins::Model::DefaultDescriptor
DEFAULT_VERSION = "2.2.0"
DEFAULT_GEM_LIST = "bundler,rake"
DEFAULT_IGNORE_LOCAL_VERSION = false
DEFAULT_RBENV_ROOT = "$HOME/.rbenv"
DEFAULT_RBENV_REPOSITORY = "https://github.com/sstephenson/rbenv.git"
DEFAULT_RBENV_REVISION = "master"
DEFAULT_RUBY_BUILD_REPOSITORY = "https://github.com/sstephenson/ruby-build.git"
DEFAULT_RUBY_BUILD_REVISION = "master"
include Jenkins::RackSupport
def call(env)
Rbenv::RackApplication.new.call(env)
end
end
class RbenvWrapper < Jenkins::Tasks::BuildWrapper
TRANSIENT_INSTANCE_VARIABLES = [:build, :launcher, :listener]
class << self
def transient?(x)
# return true for a variable which should not be serialized
TRANSIENT_INSTANCE_VARIABLES.include?(x.to_s.to_sym)
end
end
describe_as Java.hudson.tasks.BuildWrapper, :with => RbenvDescriptor
display_name "rbenv build wrapper"
# The default values should be set on both instantiation and deserialization.
def initialize(attrs={})
from_hash(attrs)
end
attr_reader :build
attr_reader :launcher
attr_reader :listener
attr_accessor :version
attr_accessor :gem_list
attr_accessor :ignore_local_version
attr_accessor :rbenv_root
attr_accessor :rbenv_repository
attr_accessor :rbenv_revision
attr_accessor :ruby_build_repository
attr_accessor :ruby_build_revision
# Will be invoked by jruby-xstream after deserialization from configuration file.
def read_completed()
from_hash({})
end
def setup(build, launcher, listener)
@build = build
@launcher = launcher
@listener = listener
Rbenv::Environment.new(self).setup!
end
def to_hash()
{
"version" => @version,
"gem_list" => @gem_list,
"ignore_local_version" => @ignore_local_version,
"rbenv_root" => @rbenv_root,
"rbenv_repository" => @rbenv_repository,
"rbenv_revision" => @rbenv_revision,
"ruby_build_repository" => @ruby_build_repository,
"ruby_build_revision" => @ruby_build_revision,
}
end
private
def from_hash(hash={})
@version = string(hash.fetch("version", @version), RbenvDescriptor::DEFAULT_VERSION)
@gem_list = string(hash.fetch("gem_list", @gem_list), RbenvDescriptor::DEFAULT_GEM_LIST)
@ignore_local_version = boolean(hash.fetch("ignore_local_version", @ignore_local_version), RbenvDescriptor::DEFAULT_IGNORE_LOCAL_VERSION)
@rbenv_root = string(hash.fetch("rbenv_root", @rbenv_root), RbenvDescriptor::DEFAULT_RBENV_ROOT)
@rbenv_repository = string(hash.fetch("rbenv_repository", @rbenv_repository), RbenvDescriptor::DEFAULT_RBENV_REPOSITORY)
@rbenv_revision = string(hash.fetch("rbenv_revision", @rbenv_revision), RbenvDescriptor::DEFAULT_RBENV_REVISION)
@ruby_build_repository = string(hash.fetch("ruby_build_repository", @ruby_build_repository), RbenvDescriptor::DEFAULT_RUBY_BUILD_REPOSITORY)
@ruby_build_revision = string(hash.fetch("ruby_build_revision", @ruby_build_revision), RbenvDescriptor::DEFAULT_RUBY_BUILD_REVISION)
end
# Jenkins may return empty string as attribute value which we must ignore
def string(value, default_value=nil)
s = value.to_s
if s.empty?
default_value
else
s
end
end
def boolean(value, default_value=false)
if FalseClass === value or TrueClass === value
value
else
# rbenv plugin (<= 0.0.15) stores boolean values as String
case value.to_s
when /false/i then false
when /true/i then true
else
default_value
end
end
end
end
<file_sep>#!/usr/bin/env ruby
require "delegate"
require "rbenv/errors"
require "rbenv/invoke"
require "rbenv/scm"
require "rbenv/semaphore"
module Rbenv
class Environment < SimpleDelegator
include Rbenv::InvokeCommand
include Rbenv::Semaphore
def initialize(build_wrapper)
@build_wrapper = build_wrapper
super(build_wrapper)
end
def setup!
install!
detect_version!
# To avoid starting multiple build jobs, acquire lock during installation
synchronize("#{rbenv_root}.lock") do
versions = capture(rbenv("versions", "--bare")).strip.split
unless versions.include?(version)
update!
listener << "Installing #{version}..."
run(rbenv("install", version), {out: listener})
listener << "Installed #{version}."
end
gem_install!
end
build.env["RBENV_ROOT"] = rbenv_root
build.env['RBENV_VERSION'] = version
# Set ${RBENV_ROOT}/bin in $PATH to allow invoke rbenv from shell
build.env["PATH+RBENV_BIN"] = "#{rbenv_root}/bin"
# Set ${RBENV_ROOT}/bin in $PATH to allow invoke binstubs from shell
build.env["PATH+RBENV_SHIMS"] = "#{rbenv_root}/shims"
end
private
def install!
unless test("[ -d #{rbenv_root.shellescape} ]")
listener << "Installing rbenv..."
run(Rbenv::SCM::Git.new(rbenv_repository, rbenv_revision, rbenv_root).checkout, {out: listener})
listener << "Installed rbenv."
end
unless test("[ -d #{plugin_path("ruby-build").shellescape} ]")
listener << "Installing ruby-build..."
run(Rbenv::SCM::Git.new(ruby_build_repository, ruby_build_revision, plugin_path("ruby-build")).checkout, {out: listener})
listener << "Installed ruby-build..."
end
end
def detect_version!
if ignore_local_version
listener << "Just ignoring local Ruby version."
else
# Respect local Ruby version if defined in the workspace
get_local_version(build.workspace.to_s).tap do |version|
if version
listener << "Use local Ruby version #{version}."
self.version = version # call RbenvWrapper's accessor
end
end
end
end
def get_local_version(path)
str = capture("cd #{path.shellescape} && #{rbenv("local")} 2>/dev/null || true").strip
not(str.empty?) ? str : nil
end
def update!
# To update definitions, update rbenv before installing ruby
listener << "Updating rbenv..."
run(Rbenv::SCM::Git.new(rbenv_repository, rbenv_revision, rbenv_root).sync, {out: listener})
listener << "Updated rbenv."
listener << "Updating ruby-build..."
run(Rbenv::SCM::Git.new(ruby_build_repository, ruby_build_revision, plugin_path("ruby-build")).sync, {out: listener})
listener << "Updated ruby-build."
end
def gem_install!
# Run rehash everytime before invoking gem
run(rbenv("rehash"), {out: listener})
list = capture(rbenv("exec", "gem", "list")).strip.split
gem_list.split(",").each do |gem|
unless list.include?(gem)
listener << "Installing #{gem}..."
run(rbenv("exec", "gem", "install", gem), {out: listener})
listener << "Installed #{gem}."
end
end
# Run rehash everytime after invoking gem
run(rbenv("rehash"), {out: listener})
end
def rbenv(*args)
(["env", "RBENV_ROOT=#{rbenv_root}", "RBENV_VERSION=#{version}", "#{rbenv_root}/bin/rbenv"] + args).shelljoin
end
def plugin_path(name)
File.join(rbenv_root, "plugins", name)
end
end
end
| 5f4e3d2a9ad1492abc7b1de32b5902d1dc488806 | [
"Ruby"
] | 2 | Ruby | ryanschwartz/rbenv-plugin | 82ed948ba92f901d88cdbf03f35acdd65c94f10d | acf1a9418eeba4ffeb3af201fd520a4fb1f6d199 |
refs/heads/main | <repo_name>JhonelCH/MESA_DE_PARTES_VIRTUAL<file_sep>/app/models/Model_tramite.php
<?php
class Model_tramite extends CI_Model
{
function __construct()
{
parent::__construct();
}
function getCount($params = ''){
$params['count'] = true;
return $this->getAll($params);
}
public function gettipopersona(){
$data = array();
$this->db->where('estado','1');
$query = $this->db->get('tb_tipopersona');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function gettramite(){
$data = array();
$this->db->where('estado','1');
$this->db->where('orden !=','0');
$query = $this->db->get('tb_tippedido');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function getie() {
/*
$data = array();
// $this->db->distinct();
//$this->db->select('nombre');
$this->db->order_by('nombre','asc');
$this->db->where('estado','1');
$query = $this->db->get('ie');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
//var_dump($data);
}
}
$query->free_result();
// return $data;*/
$data = array();
$url='http://rap.ugel03.gob.pe/wsAdjudicaciones/index.php/api/WsAdjudicaUgel03/InstitucionesEducativas/';
$data = null;
$method='GET';
$result = llamadoApi($method, $url, $data );
$result2 = json_decode(json_encode($result), true);
foreach ($result2 as $row){
$data[] = $row;
//var_dump($data);
}
return $data;
/* $PersonaId=$result->PersonaJuridicaId;
$TipoSolicitante=$result->TipoDocumento;*/
}
public function getTipoDoc($tipodoc){
$this->db->where('idTipo',$tipodoc);
$this->db->order_by('descripcion','asc');
$provincias = $this->db->get('tb_tipodocumento');
if($provincias->num_rows()>0)
{
return $provincias->result();
}
}
public function getNivelPedido($id,$nivel){
$this->db->where('nivelPadre',$id);
$this->db->where('nivel',$nivel);
$this->db->order_by('nombre','asc');
$nivelesTramites = $this->db->get('tb_tippedido');
if($nivelesTramites->num_rows()>0)
{
return $nivelesTramites->result_array();
}
}
public function getNivelPedidoLev2($id,$nivel){
$this->db->where('nivelPadre',$id);
$this->db->where('nivel',$nivel);
$this->db->order_by('nombre','asc');
$nivelesTramites = $this->db->get('tb_tippedido');
if($nivelesTramites->num_rows()>0)
{
return $nivelesTramites->result_array();
}
}
function getAll($params = ''){
$select = $where = $limit = $order = '';
$where = " WHERE ";//"WHERE c.cupon_id=tc.cupon_id AND tc.id_categoria=ct.id_categoria";
#$where = "WHERE (d.State=1 OR d.State=-1) AND a.IdDisco=d.IdDisco";
//writer($params['idUser']); exit;
if (is_array($params)) {
if (isset($params['start'],$params['limit']))
$limit = "LIMIT " . $params['start'] . ", " . $params['limit'];
if (isset($params['orderBy'],$params['sentido']))
$order = "ORDER BY " . $params['orderBy'] . " " . $params['sentido'];
if (isset($params['status']))
$where .= " (b.status = '".$params['status']."')";
if(isset($params['search2']))
$where .= " AND b.idperiodo = ".$params['search2'];
;
if(isset($params['search']))
$where .= " AND (CONCAT(b.nombre) LIKE('%".$params['search']."%') OR b.dni LIKE('".$params['search']."%'))";
;
}
if (isset($params['count'])){
$select = "SELECT COUNT(*) AS total";
}
else{
$select = "SELECT b.* ";
//$select = "SELECT c.*, ct.categoria_name ";
}
$sql = "$select
FROM boleta b
$where
$order
$limit";
$query = $this->db->query($sql);
if (isset($params['count'])) {
$result = $query -> row();
return $result -> total;
}
else
if ( $query -> result() )
return $query -> result();
else
return false;
}
//obtenemos las localidades dependiendo de la provincia escogida
function Get_TipPedido($buscar)
{
$sql = "SELECT nombre FROM tb_tippedido WHERE id_tippedido=$buscar AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row()->nombre;
}
else
return false;
}
function Get_TipPedido2($buscar)
{
$sql = "SELECT nombre FROM tb_tippedido WHERE id_tippedido=$buscar AND estado=2";
$query = $this->db->query($sql);
if($query->result()){
return $query->row()->nombre;
}
else
return false;
}
function Get_TipPedidoid($buscar)
{
$sql = "SELECT id_tippedido FROM tb_tippedido WHERE id_tippedido=$buscar AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row()->id_tippedido;
}
else
return false;
}
function Get_TipPedidoid2($buscar)
{
$sql = "SELECT id_tippedido FROM tb_tippedido WHERE id_tippedido=$buscar AND estado=2";
$query = $this->db->query($sql);
if($query->result()){
return $query->row()->id_tippedido;
}
else
return false;
}
function Get_Requisito($buscar)
{
$sql = "SELECT * FROM tb_requisitos WHERE id_tippedido=$buscar AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
$data["requisitos"] = $query->result();
$data["costo"] = $this->Get_Costo($buscar);
return $data;
}
else
return false;
}
function getUltimoNivel($buscar)
{
$sql = "SELECT * FROM tb_tippedido WHERE id_tippedido=$buscar ";
$query = $this->db->query($sql);
if($query->result()){
$data["nivel"] = $query->result();
return $data;
}
else
return false;
}
function Get_Costo($id)
{
$sql = "SELECT * FROM tb_costopedido WHERE id_tippedido=$id AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->result();
}
else
return false;
}
function Get_AllTipPedido(){
$sql = "SELECT * FROM tb_tippedido WHERE estado=1 order by orden asc";
$query = $this->db->query($sql);
if($query->result()){
return $query->result_array();
}
else
return false;
}
function save_pedido($data){
$this->db->insert("tb_pedido",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
function update_periodo($data){
$id = $this->db->update('periodo', $data, array('idperiodo' => $data['idperiodo']));
if($id){
return true;
}
else{
return false;
}
}
function Obt_Periodo(){
$sql = "SELECT * FROM periodo WHERE status=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->result();
}
else
return false;
}
function delete($data){
$id = $this->db->update('boleta', $data, array('idboleta' => $data['idboleta']));
if($id){
return true;
}
else{
return false;
}
}
}<file_sep>/app/views/login/registro - copia.php
<!DOCTYPE>
<html lang="en" class="h-100">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Mesa de Partes Virtual | Ugel03 </title>
<link href="<?php echo site_resource('mdp')?>/css/style.css" rel="stylesheet" />
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo site_resource('mdp')?>/images/logo-full.png">
<script src="<?php echo site_resource('mdp')?>/js/plugins/jquery-3.3.1.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/jquery.validate.min.js"></script>
</head>
<script type="text/javascript">
function countChar(val) {
var len = val.value.length;
if (len >= 250) {
val.value = val.value.substring(0, 250);
} else {
$('#charNum').text(250 - len);
}
};
function soloNumeros(e)
{
var key = window.Event ? e.which : e.keyCode
return ((key >= 48 && key <= 57) || (key==8))
}
function myFunction(){
$.ajax({
url:"<?php echo site_url("Login/consultadni")?>",
data:{id:$("#txtdoc").val()},
dataType:"json",
type:"POST",
success:function(data){
$("#txtnombre").val("");
$("#txtnombre").val(data.nombres);
$("#txtapepat").val("");
$("#txtapepat").val(data.apellido_paterno);
$("#txtapemat").val("");
$("#txtapemat").val(data.apellido_materno);
}
});
}
function myFunction2(){
$.ajax({
url:"<?php echo site_url("Login/consultaruc")?>",
data:{id:$("#txtdoc").val()},
dataType:"json",
type:"POST",
success:function(data){
$("#txtnombre").val("");
$("#txtnombre").val(data.razonsocial);
}
});
}
$(function(){
$("#cboTipoPersona").change(function(){
$("#cboTipoPersona option:selected").each(function() {
TipoPersona = $('#cboTipoPersona').val();
$.post(
"<?php echo(site_url("Login/gettipodoc"))?>",
{TipoPersona : TipoPersona},
function(data) {$("#coTipoDocumento").html(data); }
);
});
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if(valueSelected==1){
$("#txtdoc").prop("disabled",false);
$("#divRazon").css("display", "none");
$("#divRazon").removeClass("required");
$("#divIE").css("display", "none");
$("#divIE").removeClass("required");
$("#divNombres").css("display", "");
$("#txtnombres").val("");
$("#txtapePaterno").val("");
$("#txtapeMaterno").val("");
$("#txtapepat").addClass("required");
$("#txtapemat").addClass("required");
$("#txtnombre").addClass("required");
$('#lblNroDoc').text("Número de Documento");
$('#lblBus').text("Búsqueda");
$("#btnbsuquedadni").show();
$("#btnbsuquedaruc").hide();
$("#txtdoc").attr('maxlength', 9);
$("#txtdoc").val("");
}else if(valueSelected==2){
$("#txtdoc").prop("disabled",false);
$("#divNombres").css("display", "none");
$("#divNombres").removeClass("required");
$("#divIE").css("display", "none");
$("#divIE").removeClass("required");
$("#divRazon").css("display", "");
$("#divRazon").addClass("required");
$("#txtnombres").val("");
$("#txtapePaterno").val("");
$("#txtapeMaterno").val("");
$("#txtapepat").removeClass("required");
$("#txtapemat").removeClass("required");
$("#txtnombre").addClass("required");
$('#lblNroDoc').text("Número de Documento");
$('#lblBus').text("Búsqueda");
$("#btnbsuquedadni").hide();
$("#btnbsuquedaruc").show();
$("#txtdoc").attr('maxlength', 11);
$("#txtdoc").val("");
} else if(valueSelected==4){
$("#txtdoc").prop("disabled",false);
$("#divNombres").css("display", "none");
$("#divNombres").removeClass("required");
$("#divRazon").css("display", "none");
$("#divRazon").removeClass("required");
$("#divIE").css("display", "");
$("#divIE").addClass("required");
$("#txtnombres").val("");
$("#txtapePaterno").val("");
$("#txtapeMaterno").val("");
$("#txtapepat").removeClass("required");
$("#txtapemat").removeClass("required");
$("#txtnombre").addClass("required");
$('#lblNroDoc').text("Cod Local y/o Modular");
$('#lblBus').text("");
$("#btnbsuquedadni").hide();
$("#btnbsuquedaruc").hide();
$("#txtdoc").attr('maxlength', 6);
$("#txtdoc").attr("placeholder", "Ingrese código modular/local");
$("#txtdoc").val("");
}
});
})
$(function() {
$("#ap-frmRegistro").validate({
errorElement: "span",
errorClass: "afr-error",
errorPlacement: function(error, element) {},
submitHandler: function(forms) {
enviarFormDatosPersonales()
}
})
});
function enviarFormDatosPersonales() {
var datastring = $("#ap-frmRegistro").serialize();
$.ajax({
url: $("#ap-frmRegistro").attr('action'),
method: "POST",
data: datastring,
dataType: "JSON",
beforeSend: function() {
},
success: function(data) {
switch (data.resp) {
case 10:
alert(data.text);
break;
default:
// code block
}
}
})
}
</script>
<body class="h-100">
<div class="authincation h-100">
<div class="container h-100">
<div class="row justify-content-center h-100 align-items-center">
<div class="col-md-6">
<div class="authincation-content">
<div class="row no-gutters">
<div class="col-xl-12">
<div class="auth-form">
<div class="text-center mb-3">
<a href="index.html"><img src="<?php echo site_resource('mdp')?>/images/logo-full.png" alt=""></a>
</div>
<h4 class="text-center mb-4 text-white"><strong>Registrarse</strong></h4>
<form id="ap-frmRegistro" name="ap-frmRegistro" action="<?php echo(site_url('Login/enviarRegistroDatos'))?>" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-12">
<label class="mb-1 text-white">Tipo de Persona</label>
<?php
echo "<select class='form-control' id='cboTipoPersona' name='cboTipoPersona' required='required' >";
if (count($tipopersona)) {
echo "<option value='0'>[--Seleccione--]</option>";
foreach ($tipopersona as $list) {
echo "<option value='". $list['id'] . "'>" . $list['descripcion'] . "</option>";
}
}
echo "</select>";
?>
</div>
<div class="form-group col-md-12">
<label class="mb-1 text-white">Tipo de Documento</label>
<select class="form-control" required="required" id="coTipoDocumento" name="coTipoDocumento">
<option value="0">[--Seleccione--]</option>
</select>
</div>
<div class="form-group col-md-10">
<label class="mb-1 text-white" id="lblNroDoc" name="lblNroDoc">Nro Documento</label>
<input class="form-control" type="text" onkeypress="return soloNumeros(event);" maxlength="11" placeholder="Ingrese Documento" name="txtdoc" id="txtdoc" >
</div>
<div class="form-group col-md-1">
<label class="mb-1 text-white" id="lblBus" name="lblBus"></label>
<button id="btnbsuquedadni" name="btnbsuquedadni" onclick="myFunction()" style="background-color: #E12222;color: white;height: 55px;width: 65px;display:none" ><i class="fa fa-search"></i></button>
<button id="btnbsuquedaruc" name="btnbsuquedaruc" onclick="myFunction2()" style="background-color: #E12222;color: white;height: 55px;width: 65px;display:none " ><i class="fa fa-search"></i></button>
</div>
</div>
<div class="form-row" id="divNombres" name="divNombres">
<div class="form-group col-md-12">
<label class="mb-1 text-white">Nombres:</label>
<input type="text" class="form-control" placeholder="Ingrese Nombres" name="txtnombre" id="txtnombre">
</div>
<div class="form-group col-md-12">
<label class="mb-1 text-white">Apellido Paterno:</label>
<input type="text" class="form-control" placeholder="Ingrese Apellido Paterno" name="txtapepat" id="txtapepat">
</div>
<div class="form-group col-md-12">
<label class="mb-1 text-white">Apellido Materno:</label>
<input type="text" class="form-control" placeholder="Ingrese Apellido Materno" name="txtapemat" id="txtapemat">
</div>
</div>
<div class="form-row" id="divRazon" name="divRazon" style="display:none;">
<div class="form-group col-md-12">
<label class="mb-1 text-white">Razón Social:</label>
<input type="text" class="form-control" placeholder="Ingrese Razón Social" name="txtrazonsocial" id="txtrazonsocial">
</div>
</div>
<div class="form-row" id="divIE" name="divIE" style="display:none;">
<div class="form-group col-md-12">
<label class="mb-1 text-white">Institución Educativa:</label>
<input type="text" class="form-control" placeholder="Ingrese I.E." id="txtie" name="txtie">
</div>
<div class="form-group col-md-12">
<label class="mb-1 text-white">Cargo:</label>
<input type="text" class="form-control" placeholder="Ingrese Cargo" name="txtcargo" id="txtcargo">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label class="mb-1 text-white">Teléfono</label>
<input class="form-control" onkeypress="return soloNumeros(event);" placeholder="Ingrese Teléfono" maxlength="9" type="text" name="txtphone" id="txtphone" required >
</div>
<div class="form-group col-md-12">
<label class="mb-1 text-white">Correo</label>
<input class="form-control" type="email" placeholder="Ingrese Correo" name="txtemail" id="txtemail" required >
</div>
<div class="form-group col-md-12">
<label class="mb-1 text-white">Repetir correo</label>
<input class="form-control" type="email" placeholder="<NAME>" name="txtemail2" id="txtemail2" required >
</div>
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="resultadocheck">
<label class="mb-1 text-white">
Acepto contacto por el correo ingresado
</label>
</div>
</div>
<div class="text-center mt-4">
<button type="submit" class="btn bg-danger text-white btn-block">
<i class="fa fa-check color-info"></i> Registrarse
</button>
</div>
</form>
<div class="new-account mt-3 text-center">
<p class="text-white">
¿Ya tienes con una cuenta? <br>
<a class="text-white" href="<?php echo(site_url('Login'))?>">Iniciar Sesión</a>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="<?php echo site_resource('mdp')?>/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
<!--<script src="<?php echo site_resource('mdp')?>/js/custom.min.js"></script>-->
<script src="<?php echo site_resource('mdp')?>/js/deznav-init.js"></script>
</body>
</html><file_sep>/app/controllers/Tramite.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Tramite extends CI_Controller {
var $solicitud;
var $filesdirectory;
function __construct()
{
parent::__construct();
ini_set("max_execution_time", 0);
$this->load->library("session");
$this->load->model("Model_tramite","tramite");
$this->load->library('My_PHPMailer');
$this->load->library('My_dom');
}
public function index()
{
$dataview['ie'] = $this->tramite->getie();
$dataview['tipopersona'] = $this->tramite->gettipopersona();
$dataview["solicitud"] = $this->tramite->Get_AllTipPedido();
//writer($dataview["solicitud"]);die;
$this->load->view('tramite/home',$dataview);
/*$this->load->view('boleta/home');*/
}
public function getNivelPedido(){
$html="";
$id = $_POST['id'];
$nivel = $_POST['nivel'];
$rs = $this->tramite->getNivelPedido($id,$nivel);
$html.= "<option value=''>[--SELECCIONE--]</option>";
foreach($rs as $item){
$html.= "<option value='".$item["id_tippedido"]."'>".$item["nombre"]."</option>";
}
echo $html;
}
public function getNivelPedidoLev2(){
$html="";
$id = $_POST['id2'];
$nivel = $_POST['nivel'];
$rs = $this->tramite->getNivelPedidoLev2($id,$nivel);
$html.= "<option value=''>[--SELECCIONE--]</option>";
if($rs){
foreach($rs as $item){
$html.= "<option value='".$item["id_tippedido"]."'>".$item["nombre"]."</option>";
}
echo $html;
}else{
echo false;
}
}
public function consultaruc(){
$ruc=$this->input->post("id");
$data = file_get_html("https://api.sunat.cloud/ruc/".$ruc);
$info = json_decode($data, true);
if($data==='[]' || $info['fecha_inscripcion']==='--'){
$datos = array(0 => 'nada');
echo json_encode($datos);
}else{
$datos = array(
// 0 => $info['ruc'],
1 => $info['razon_social'],
// 2 => date("d/m/Y", strtotime($info['fecha_actividad'])),
// 3 => $info['contribuyente_condicion'],
// 4 => $info['contribuyente_tipo'],
// 5 => $info['contribuyente_estado'],
// 6 => date("d/m/Y", strtotime($info['fecha_inscripcion'])),
// 7 => $info['domicilio_fiscal'],
// 8 => date("d/m/Y", strtotime($info['emision_electronica']))
);
$datosRuc["razonsocial"] = html_entity_decode($datos[1], ENT_QUOTES, "UTF-8");
echo json_encode($datosRuc);
}
}
public function consultadni(){
$dni = $this->input->post('id');
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_URL, 'https://dni.optimizeperu.com/api/persons/' . $dni);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$result = curl_exec($curl);
curl_close($curl);
$_result = json_decode($result);
$datos['nombres'] = $_result->name;
$datos['apellido_paterno'] = $_result->first_name;
$datos['apellido_materno'] = $_result->last_name;
echo json_encode($datos);
}
public function getUltimoNivel(){
$nivel = $this->tramite->getUltimoNivel($this->input->post("id"));
echo(json_encode($nivel));
}
public function gettipodoc(){
$options = "";
if($this->input->post('TipoPersona'))
{
$TipoPersona = $this->input->post('TipoPersona');
$Tipodoc = $this->tramite->getTipoDoc($TipoPersona);
foreach($Tipodoc as $fila)
{
?>
<option value="<?=$fila->id?>"><?=$fila->descripcion?></option>
<?php
}
}
}
public function enviar(){
$dataview["servicio"] = $this->tramite->Get_TipPedido($this->input->post("cbservicio"));
$this->solicitud = $dataview["servicio"];
$dataview["dependencia"] = $this->input->post("txtdependencia");
$dataview["resumen"] = $this->input->post("txtresumen");
$dataview["apepat"] = $this->input->post("txtapepat");
$dataview["apemat"] = $this->input->post("txtapemat");
$dataview["nombre"] = $this->input->post("txtnombre");
$dataview["razonsocial"] = $this->input->post("txtrazonsocialhid");
$dataview["doc"] = $this->input->post("txtdoc");
// $dataview["ie"] = $this->input->post("txtie");
$dataview["ie"] = $this->input->post("txtie_val");
$dataview["cargo"] = $this->input->post("txtcargo");
$dataview["via"] = $this->input->post("rbtvia");
$dataview["nombvia"] = $this->input->post("txtnomvia");
$dataview["referencia"] = $this->input->post("txtreferencia");
$dataview["telefono"] = $this->input->post("txtphone");
$dataview["modular"] = $this->input->post("txtmodula");
$dataview["email"] = $this->input->post("txtemail");
if( $this->tramite->Get_TipPedidoid($this->input->post("cbservicio")) == 16 || $this->tramite->Get_TipPedidoid($this->input->post("cbservicio")) == 52){
$dataview["fundamento"] = $this->input->post("txtfundpedido");
}
if( $this->tramite->Get_TipPedidoid($this->input->post("cbservicio")) == 51){
$dataview["fundamento"] = 'RECLAMO REASIGNACIÓN '.$this->input->post("txtfundpedido");
}
$html = $this->load->view('tramite/pdf',$dataview,true);
$this->genera($html);
}
public function genera($html)
{
ini_set("memory_limit","880M");
set_time_limit(0);
$this->load->library('Pdf');
/*writer($dataview);die;*/
//$mpdf=new mPDF('','', 0, '', 15, 15);
#$mpdf=new mPDF('utf-8', 'A4-L');
$mpdf=new mPDF('utf-8', 'A4',0, '', 10, 10, 13, 2, 9, 9, 'P');
/*$mpdf=new mPDF('c'); */
$mpdf->SetTitle('FUT');
$mpdf->mirroMargins = 1;
$mpdf->ignore_invalid_utf8 = true;
$mpdf->defaultheaderfontsize = 9; /* in pts */
$mpdf->defaultheaderfontstyle = ""; /* blank, B, I, or BI */
$mpdf->defaultheaderline = 1; /* 1 to include line below header/above footer */
$mpdf->defaultfooterfontsize = 9; /* in pts */
$mpdf->defaultfooterfontstyle = ""; /* blank, B, I, or BI */
$mpdf->defaultfooterline = 1; /* 1 to include line below header/above footer */
/*$mpdf->SetHeader('');
$mpdf->SetFooter('{PAGENO}'); defines footer for Odd and Even Pages - placed at Outer margin */
$mpdf->SetFooter(array(
'L' => array(
'content' => 'Text to go on the left',
'font-family' => 'sans-serif',
'font-style' => '', /* blank, B, I, or BI */
'font-size' => '10', /* in pts */
),
'C' => array(
'content' => '- {PAGENO} -',
'font-family' => 'arial',
'font-style' => '',
'font-size' => '18', /* gives default */
),
'R' => array(
'content' => 'Printed @ {DATE j-m-Y H:m}',
'font-family' => 'monospace',
'font-style' => '',
'font-size' => '10',
),
'line' => 1, /* 1 to include line below header/above footer */
), 'E' /* defines footer for Even Pages */
);
$mpdf->WriteHTML($html);
$path = dirname(APPPATH).'/resource/download/fut';
if(!is_dir($path)):
mkdir($path);
endif;
/*$mpdf->Output('Boletas.pdf','I');*/
$namePdf = "FUT_".date("Y-m-d")."_".substr(md5(uniqid().rand(0,100).date("Y-m-d")),rand(0,17),15);
/*Creando el directorio*/
$directory = $namePdf;
$this->filesdirectory = $directory;
$pathfiles = dirname(APPPATH).'/resource/download/fut/'.$directory;
if(!is_dir($pathfiles)):
mkdir($pathfiles);
endif;
$namePdf = $namePdf.".pdf";
$filepdf = dirname(APPPATH).'/resource/download/fut/'.$directory."/".$namePdf;
$mpdf->Output($filepdf,'F');
$files = $_FILES['afr-file'];
if($files != '')
{
foreach($files["name"] as $key=>$item){
if($files["error"][$key] == 0 and $files["size"][$key] > 0){
$newname = cleanString($item);
if(move_uploaded_file($files['tmp_name'][$key], $pathfiles."/".$newname)){
}
}
}
}
$this->sendmail($pathfiles);
}
public function sendmail($pathfiles){
/* ap capcha */
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Por favor revise el formulario captcha.</h2>';
exit;
}
$secretKey = "<KEY>";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if($responseKeys["success"]) {
/*variables sinad ws */
$urlws='http://rap.ugel03.gob.pe/wsAdjudicaciones/index.php/api/WsAdjudicaUgel03/verificaIdentificacion/';
if(isset($_POST["txtdoc"])){ $txtdni = $this->input->post("txtdoc"); }
if(isset($_POST["txtfolio"])){ $Folios = $this->input->post("txtfolio"); }
if(isset($_POST["txtfoficio"])){ $oficio = $this->input->post("txtfoficio"); }
if($_POST['cboTipoPersona']==1){
$from_name = $this->input->post("txtnombre")." ".$this->input->post("txtapepat");
$destinatarioNombre = "sr(s)".$this->input->post("txtapepat")." ".$this->input->post("txtapemat").", ".$this->input->post("txtnombre");
$valueEstadoTipo = 1 ;
}
if($_POST['cboTipoPersona']==2){
$from_name = $this->input->post("txtrazonsocialhid");
$destinatarioNombre = "Sres de razón social ".$this->input->post("txtrazonsocialhid");
$valueEstadoTipo = 2 ;
}
if($_POST['cboTipoPersona']==4){
$from_name = "I.E:";
//$from_name = "Codigo modular :".$this->input->post("txtie");
$destinatarioNombre = "Sres de la Institución Educativa";
//$destinatarioNombre = "Sres de la Institución Educativa con codigo modular".$this->input->post("txtie");
$valueEstadoTipo = 3 ;
$txtdni = $this->input->post("txtie");
}
$cbservicio = $this->input->post("cbservicio");
if($cbservicio != ''){
$id_tramite = $this->tramite->Get_TipPedidoid($this->input->post("cbservicio"));
if($id_tramite == 21 || $id_tramite == 22){
$cbservicio_sub = $this->input->post("cbservicio_sub");
if($cbservicio_sub != '')
{
$dataview["servicio"] = $this->tramite->Get_TipPedido($this->input->post("cbservicio"));
$dataview["subservicio"] = $this->tramite->Get_TipPedido2($this->input->post("cbservicio_sub"));
$id_tramite = $this->tramite->Get_TipPedidoid2($this->input->post("cbservicio_sub"));
$cbservicio_sub2 = $this->input->post("cbservicio_sub2");
if($cbservicio_sub2 != '' && $cbservicio != '22')
{
$dataview["subservicio2"] = $this->tramite->Get_TipPedido2($this->input->post("cbservicio_sub2"));
if($id_tramite == 25 || $id_tramite == 26){
$id_tramite = $this->tramite->Get_TipPedidoid2($this->input->post("cbservicio_sub2"));
$this->solicitud = $dataview["servicio"].' - '.$dataview["subservicio"].' - '.$dataview["subservicio2"];
}
}else if($cbservicio == '22'){
$this->solicitud = $dataview["servicio"].' - '.$dataview["subservicio"];
}else{
echo '<h2>Por favor agregar sub - trámite.</h2>';
exit;
}
}else{
echo '<h2>Por favor agregar sub - trámite.</h2>';
exit;
}
}
}else{
echo '<h2>Por favor agregar trámite.</h2>';
exit;
}
/* ap set parametros segun requerimientos */
if( $id_tramite == 16 || $id_tramite == 22 || $id_tramite == 21 || $id_tramite == 25 || $id_tramite == 26 || $id_tramite == 42 || $id_tramite == 43 || $id_tramite == 44 || $id_tramite == 45 || $id_tramite == 50 || $id_tramite == 51 || $id_tramite == 52 || $id_tramite == 60 || $id_tramite == 61){
$emailFut = "<EMAIL>";$emailFutpass = "<PASSWORD>.";$booleansinad = false;$CC_emailFut_ugel = "<EMAIL>";
// $emailFut = "<EMAIL>";$emailFutpass = "<PASSWORD>";$booleansinad = false;$CC_emailFut_ugel = "<EMAIL>";
}else{
$emailFut = "<EMAIL>";$emailFutpass = "<PASSWORD>."; $booleansinad = true;
//$emailFut = "<EMAIL>";$emailFutpass = "<PASSWORD>";$booleansinad = true;
}
/* REGISTRA SINAD WS*/
/*input de tipo persona natural*/
$Nombres_tp1 = $this->input->post("txtnombre");
$Apellidos_tp1 = $this->input->post("txtapepat")." ".$this->input->post("txtapemat");
$NumeroDocumento_tp1 = $this->input->post("txtdoc");
$Telefono1_tp1 = $this->input->post("txtphone");
$Telefono2_tp1 = "";
$Email_tp1 = $this->input->post("txtemail");
$CodigoUbigeo_tp1 = "150132";
$CodigoUbigeoDes_tp1 ="";
$PaisId_tp1 = "";
$Direccion_tp1 = $this->input->post("txtnomvia")." ref:".$this->input->post("txtreferencia");
/*Complemento persona juridica data */
$Descripcion_tp2= $this->input->post("txtrazonsocialhid");
$CodigoModular_tp2 = NULL ;
$TipoSectorId_tp2 ='13';
$TipoSectorDes_tp2 = "OTRAS INSTITUCIONES";
$TipoDocumento_tp2 = NULL ;
/*Complemento datos reg i.e*/
$personaJuridicaId = $this->input->post("txtie");
$CC_emailFut_ugel ="";
$part_url="rap.ugel03.gob.pe/wsAdjudicaciones/index.php/api/WsAdjudicaUgel03/saveExpedienteDocentet";
if($booleansinad){
switch ($id_tramite) {
/*Propuesta Contrato Docente case 1 */
case 13:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";/*CORREO COPIA AL EQUIPO DE PERSONAL */
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'1/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
//var_dump($rest);die;
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/*2 Solicitud de receso temporal y/o definitivo de institución educativa privada case 2*/
case 14:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'2/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/*3 Solicitud de reconocimiento de promotores de institución educativa privada case 3*/
case 15:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'3/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 4 Autorización a los comités de recursos propios y actividades productivas empresariales de las i.e. públicas, para abrir cuenta bancaria mancomunada y registrar firmas en el banco para manejar la cuenta bancaria mancomunada*/
case 17:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'4/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/*5 Presentación de los comites de Recursos propios y actividades productivas empresariales de las i.e. públicas, del libro caja y bancos */
case 18:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'5/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 6 Presentación del plan anual de recursos propios y actividades productivas empresariales de las i.e. públicas*/
case 19:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'6/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 7. Reconocimiento de adeudos de ejercicios presupuestales anteriores (devengados */
case 20:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'7/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.1. Solicito licencia con goce de haber por incapacidad temporal: Si es otorgado por ESSALUD */
case 27:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'811/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.2. Solicito licencia con goce de haber por incapacidad temporal: Si es otorgado por MÉDICO PARTICULAR */
case 28:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'812/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.3. Solicito licencia por maternidad */
case 29:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'813/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.4. Solicito licencia con goce de haber por paternidad */
case 30:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'814/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.5. Solicito licencia por adopción */
case 31:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'815/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.6. Solicito asumir representación oficial del Estado Peruano */
case 32:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'816/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.7. Solicito licencia por citación expresa judicial, militar o policial */
case 33:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'817/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.8. Solicito licencia por siniestro */
case 34:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'818/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.10. Solicito licencia por fallecimiento de padres, cónyuges, hijos o hermanos (luto) */
case 35:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'8110/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.11. Representación sindical */
case 36:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'819/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.11. Solicito licencia por capacitación organizada y autorizada por el MINEDU */
case 37:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'8111/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.12. Solicito licencia por estudios de postgrado, especialización o perfeccionamiento, autorizado por el MINEDU y por los gobiernos regionales en el país o el extranjero */
case 38:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'8112/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.13. Solicito licencia por desempeño de cargo de consejero regional o regidor municipal */
case 39:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'8113/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.14. Solicito licencia por enfermedad grave o terminal de familiares directos (hijos, padres y cónyuge) */
case 40:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'8114/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.1.15. Solicito licencia por capacitación oficializada */
case 41:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'8115/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.2.1. Motivos particulares */
case 50:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'821/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.2.2. Capacitación no oficializada */
case 42:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'822/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.2.3. Enfermendad grave de los padres, conyuge, conviviente o hijos */
case 43:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'823/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.2.4. Desempeño de funciones públicas o cargos de confianza (solo para docentes y auxiliares de educación) */
case 44:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'824/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 8.2.5. Contrato cas en los programas presupuestales de logros de aprendizaje – pela (solo para docente) */
case 45:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'825/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 9.1. En caso de fallecimiento de madre, padre e hijos del servidor público */
case 46:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'91/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 9.2. En caso de fallecimiento del servidor público, solicitado por el conyuge */
case 47:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'92/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 9.3. En caso de fallecimiento de servidor público, solicitado por hijos y hermanos */
case 48:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'93/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 9.4. En caso de fallecimiento de su conyuge (reconocido judicialmente) */
case 49:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'94/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 10. Solicitud de elaboración de constancia de pagos de haberes y descuentos (solo hasta marzo 1998) */
case 23:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'10/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 11. Solicitud de copia digital de resoluciones directorales */
case 24:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'11/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 15. Actualización de Datos de Cuenta en el Banco de la Nación */
case 53:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'15/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 16. Aperturas de cuenta en el Banco de la Nación */
case 1:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'16/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 17. Emisión de Constancia y/o Certificado de Trabajo */
case 5:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'17/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 18. Elaboración de Informe Escalafonario */
case 3:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'18/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 19. Recepción de resoluciones de la ONP para notificación y archivo */
case 54:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'19/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 20. Solicitud de cese por fallecimiento */
case 55:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'20/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 21. Cese voluntario */
case 56:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'21/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 22. Soporte Tecnológico para los Equipos de Cómputo de las Instituciones Educativas */
case 57:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'22/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 23. Tramite de Subsidio ante Essalud por COVID-19 */
case 58:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'23/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 24. Subsidio por Maternidad */
case 59:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'24/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 25. Constancia de Ubicación Geográfica */
case 8:
//$CC_emailFut_ugel = "<EMAIL>";
//$CC_emailFut_ugel = "<EMAIL>";
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'25/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 28. Atención de Requerimiento de expedientes solicitados por los juzgados de trabajo */
case 62:
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'28/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
/* 29. Autorización de Funcionamiento y Registro de Instituciones Educativas Privadas */
case 63:
$CC_emailFut_ugel = "<EMAIL>";
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$result_ = llamadoApi('GET', $urlws, $data ); $result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){$TipoSolicitante='NULL';}else{$TipoSolicitante=$result["TipoDocumento"];}
$url_saveExp='http://'.$part_url.'29/';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi('GET', $url_saveExp, $dataSave ); $rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
}
}
// $valueEstadoTipo
/*
if($booleansinad){
switch ($id_tramite) {
case 13:
$data = array("id" => "$txtdni","Nombres_tp1"=>"$Nombres_tp1","Apellidos_tp1"=>"$Apellidos_tp1","NumeroDocumento_tp1"=>"$NumeroDocumento_tp1" ,"Telefono1_tp1"=>"$Telefono1_tp1","Telefono2_tp1"=>"$Telefono2_tp1" ,"Email_tp1"=>"$Email_tp1","CodigoUbigeo_tp1"=>"$CodigoUbigeo_tp1","CodigoUbigeoDes_tp1"=>"$CodigoUbigeoDes_tp1","PaisId_tp1"=>"$PaisId_tp1","Direccion_tp1"=>"$Direccion_tp1","Descripcion_tp2"=>"$Descripcion_tp2","CodigoModular_tp2"=>"$CodigoModular_tp2","TipoSectorId_tp2"=>"$TipoSectorId_tp2","TipoSectorDes_tp2"=>"$TipoSectorDes_tp2","TipoDocumento_tp2"=>"$TipoDocumento_tp2","valueEstadoTipo"=>"$valueEstadoTipo","personaJuridicaId"=>"$personaJuridicaId");
$method='GET';
$result_ = llamadoApi($method, $urlws, $data );
$result = json_decode(json_encode($result_), true);
if($result){
$PersonaId=$result["PersonaId"];
if(is_null($result["TipoDocumento"])){
$TipoSolicitante='NULL';
}else{
$TipoSolicitante=$result["TipoDocumento"];
}
$url_saveExp='http://rap.ugel03.gob.pe/wsAdjudicaciones/index.php/api/WsAdjudicaUgel03/saveExpedienteDocentet1/';
$method='GET';
$dataSave = array("PersonaId" => "$PersonaId","folio" => "$Folios","TipoSolicitante"=>"$TipoSolicitante","oficio"=>"$oficio");
$rest_ = llamadoApi($method, $url_saveExp, $dataSave );
$rest = json_decode(json_encode($rest_), true);
$NumeroExp = 'MPT-FUT'.date('Y').'-EXT-'.$rest["NumeroExp"];
$Pass = $rest["Pass"];
}
break;
case 14:
echo "en progress";
break;
case 15:
echo "en progress";
break;
}
}
*/
/* fin activa registro sinad*/
if( $id_tramite == 16 || $id_tramite == 22 || $id_tramite == 21 || $id_tramite == 25 || $id_tramite == 26 || $id_tramite == 42 || $id_tramite == 43 || $id_tramite == 44 || $id_tramite == 45 || $id_tramite == 50|| $id_tramite == 51 || $id_tramite == 52 || $id_tramite == 60 || $id_tramite == 61){
$emailFut = "<EMAIL>";$emailFutpass = "<PASSWORD>.";$booleansinad = false;$CC_emailFut_ugel = "<EMAIL>";
// $emailFut = "<EMAIL>";$emailFutpass = "<PASSWORD>";$booleansinad = false;$CC_emailFut_ugel = "<EMAIL>";
}else{
$emailFut = "<EMAIL>";$emailFutpass = "<PASSWORD>."; $booleansinad = true;
//$emailFut = "<EMAIL>";$emailFutpass = "<PASSWORD>";$booleansinad = true;
}
/*****************************************************************/
$body_email_especialista ='';
if($booleansinad){
$body_email_especialista = 'Estimado especialista :<br>
La plataforma de Mesa de partes virtual a registrado un solicitud para el tramite de '.$this->solicitud.'
generando un N° EXP: '.$NumeroExp.' <br>';
}else{
$body_email_especialista = 'Estimado especialista :<br>
La plataforma de Mesa de partes virtual a registrado un solicitud para el tramite de '.$this->solicitud.'<br>';
}
$from_mail = trim($this->input->post("txtemail"));
$mail = new PHPMailer();
$mail->isSMTP();
//$mail->SMTPDebug = 1;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Host = "mail.ugel03.gob.pe";
$mail->Port = 25;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = false;
$mail->Username = $emailFut;
$mail->Password = <PASSWORD>;
$mail->From = $from_mail;
$mail->FromName = $from_name;
/* $mail->AddAddress($emailFut,"Generico");*/
$mail->AddAddress($CC_emailFut_ugel,"Generico");
// $mail->addBCC('<EMAIL>',"Generico");
$mail->addCC("<EMAIL>","Generico");
// $mail->AddCC("<EMAIL>","Generico");
// $mail->AddCC("<EMAIL>","Generico");
$mail->Subject = 'Mesa de Partes Virtual Tramite: '.$this->solicitud;
$mail->Body =$body_email_especialista;
$mail->IsHTML(true);
// Activo condificacción utf-8
$mail->CharSet = 'UTF-8';
$directorio = opendir($pathfiles); //ruta actual
while ($archivo = readdir($directorio)) //obtenemos un archivo y luego otro sucesivamente
{
if (!is_dir($archivo))//verificamos si es o no un directorio
{
$mail->AddAttachment($pathfiles."/".$archivo);
}
}
// Envio mail
if(!$mail->Send()) {
$data["message"] = "Error en el envío: " . $mail->ErrorInfo;
$error = 1;
} else {
$data["message"] = "¡Su Solicitud fue enviado correctamente!";
$error = 0;
}
$data = array(
"msg"=>$data["message"],
"error" => $error
);
$this->session->set_userdata($data);
$datasave["id_tippedido"] = $this->input->post("cbservicio");
$datasave["ape_pat"] = $this->input->post("txtapepat");
$datasave["ape_mat"] = $this->input->post("txtapemat");
$datasave["Nombre"] = $this->input->post("txtnombre");
$datasave["razon_social"] = $this->input->post("txtrazonsocialhid");
$datasave["documento"] = $this->input->post("txtdoc");
$datasave["cargo"] = $this->input->post("txtcargo");
$datasave["telefono"] = $this->input->post("txtphone");
$datasave["correo"] = $this->input->post("txtemail");
$datasave["archivo"] = $this->filesdirectory;
$datasave["creado"] = date("Y-m-d H:i:s");
$datasave["tipo_doc"] = $_POST['cboTipoPersona'] ;
$datasave["oficio"] = $_POST['txtfoficio'] ;
$datasave["folio"] = $_POST['txtfolio'] ;
// $datasave["asunto"] = $this->input->post("txtfundpedido");
if ($_POST['txtfundpedido']){
$datasave["asunto"]=$this->input->post("txtfundpedido");
}else{
$datasave["asunto"]='';
};
$this->tramite->save_pedido($datasave);
/**********************Envio de confirmacion**************************/
$body_email_solicitante ='';
if($booleansinad){
$body_email_solicitante= '<br> Estimado <br> '.$destinatarioNombre.'<br>
En buena hora su solicitud estará siendo procesada por un especialista,usted recibira la respuesta de la solicitud por este medio.
Tambien estamos brindando los accesos para hacer seguimiento al tramite habiéndose generado
el:<br> N° EXP: '.$NumeroExp.' <br> Contraseña: '.$Pass.'<br> <a href="http://sinad.ugel03.gob.pe/Sinad/ConsultaExterna/loginExterno.aspx">Click aqui para consultar el Expediente</a>.<br>
<b> BUZÓN DESATENDIDO, No se responderán a los correos electrónicos enviados a esta dirección.</b><br>
<br>Telef : 4273210 / 4262627 / 4261562<br> Atención de 8:30am a 4:30pm<br> UGEL 03 - Av. Iquitos 918, La Victoria, La Victoria';
}else{
$body_email_solicitante = '<br> Estimado <br> '.$destinatarioNombre.'<br>
En buena hora su solicitud estará siendo procesada por un especialista,usted recibira la respuesta de la solicitud por este medio.
<br>
<b> BUZÓN DESATENDIDO, No se responderán a los correos electrónicos enviados a esta dirección.</b><br>
<br>Telef : 4273210 / 4262627 / 4261562<br> Atención de 8:30am a 4:30pm<br> UGEL 03 - Av. Iquitos 918, La Victoria, La Victoria';
}
$mail_r='';
$from_mail_reenvio = $emailFut;
$from_name_reenvio = 'Mesa de partes Virtual UGEL03';
$mail_r = new PHPMailer();
$mail_r->isSMTP();
$mail_r->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail_r->Host = "mail.ugel03.gob.pe";
$mail_r->Port = 25;
$mail_r->SMTPSecure = 'tls';
$mail_r->SMTPAuth = false;
$mail_r->Username = $emailFut;
$mail_r->Password = <PASSWORD>;
$mail_r->From = $from_mail_reenvio;
$mail_r->FromName = $from_name_reenvio;
$mail_r->AddAddress(trim($this->input->post("txtemail")),"Generico");
$mail_r->Subject = 'Mesa de partes Virtual : Tramite '.$this->solicitud;
$mail_r->Body = $body_email_solicitante ;
$mail_r->IsHTML(true);
$mail_r->CharSet = 'UTF-8';
// Envio mail
if(!$mail_r->Send()) {
$data["message"] = "Error en el envío: " . $mail_r->ErrorInfo;
$error = 1;
} else {
$data["message"] = "¡Su Solicitud fue enviado correctamente!";
$error = 0;
}
redirect("tramite");
} else {
$data["message"] = "Posiblemente seas un bot, intente de nuevo";
$error = 1;
}
}
public function requisitos()
{
$requisitos = $this->tramite->Get_Requisito($this->input->post("id"));
/*writer($requisitos);die;
$response = "";
foreach($requisitos as $item){
$response = $response."<li>
<label>". $item->descripcion ." :</label>
<input type='file' name='afr-file[]' class='required' >
</li>";
}*/
echo(json_encode($requisitos));
}
public function formato(){
$dataview["solicitud"] = $this->tramite->Get_AllTipPedido();
//writer($dataview["solicitud"]);die;
$this->load->view('tramite/formato-silencioadm',$dataview);
}
public function institucion_educativa()
{
$ie = $this->tramite->getie();
$like = $_POST['searchTerm'];
$result = array_filter($ie, function ($item) use ($like) {
if (stripos($item['Descripcion'], $like) !== false) {
return true;
}
return false;
});
echo json_encode($result, JSON_PRETTY_PRINT);
}
public function tipo_pedido()
{
$pedido = $this->tramite->gettramite();
$like = $_POST['searchTerm'];
$result = array_filter($pedido, function ($item) use ($like) {
if (stripos($item['nombre'], $like) !== false) {
return true;
}
return false;
});
echo json_encode($result, JSON_PRETTY_PRINT);
}
}
<file_sep>/app/controllers/Inventory.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Inventory extends CI_Controller {
/**
*/
function __construct()
{
parent::__construct();
ini_set("max_execution_time", 0);
$this->load->library("session");
$this->load->model("Model_boleta","boleta");
}
public function index()
{
//cargamos la librería
$this->load->library('ciqrcode');
//hacemos configuraciones
// $params['data'] = $this->random(30);
$params['data'] = "<NAME>";
//writer($params['data']);die;
$params['level'] = 'H';
$params['size'] = 3;
//decimos el directorio a guardar el codigo qr, en este
//caso una carpeta en la raíz llamada qr_code
$params['savename'] = FCPATH.'resource/qr_code/qrcode.png';
//generamos el código qr
$this->ciqrcode->generate($params);
echo '<img src="'.base_url().'resource/qr_code/qrcode.png" />';
}
public function random($num){
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$string = '';
for ($i = 0; $i < $num; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1)];
}
return $string;
}
}
<file_sep>/admin/controllers/Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct()
{
parent::__construct();
date_default_timezone_set('America/Lima');
ini_set("max_execution_time", 0);
//$this->load->helper('captcha');
$this->load->library("session");
$this->load->model("Model_login","login");
$this->load->library('My_PHPMailer');
}
public function index()
{
$this->load->view('login/home');
}
public function enviarLogin(){
$msg = array();
$data = $this->login->Get_user($this->input->post("userLogin"),$this->input->post("passuser"));
if($data){
$this->session->set_userdata(array("iduser"=>$data['id_usuario'],"idtipo"=>$data['id_tipo'],"user"=>$data['email'],"dni"=>$data['dni'],"nombres"=>$data['nombres'],"apepa"=>$data['apellido_pat'],"apema"=>$data['apellido_mat'],"logueado"=>true));
$msg["resp"] = 100;
$msg["text"] = "Accediendo!!!.";
echo json_encode($msg);
}else{
$msg["resp"] = 10;
$msg["text"] = "Usuario y/o contraseña incorrecta.";
echo json_encode($msg);
}
//echo json_encode($msg);
}
public function enviaCredenciales(){
date_default_timezone_set('America/Lima');
/* Re-capcha:v3 */
$nroDoc = $this->input->post("nroDoc");
$fechaRegistro = $this->input->post("fechaRegistro");
//$emailUser = $this->input->post("emailUser");
$txtnombres = $this->input->post("nombresuser");
$apellidosuser = $this->input->post("apellidosuser");
$tituloConsulta = $this->input->post("tituloConsulta");
$asuntoReclamo = $this->input->post("asuntoReclamo");
$codModular = $this->input->post("ie");
$from_name = $txtnombres.' ,'.$apellidosuser;
$from_name2 = $txtnombres;
$from_mail = trim($this->input->post("emailUser"));
$telefonoUsuario = $this->tramite->buscaTelefono($from_mail,$nroDoc);
$nombreIe = $this->tramite->buscaie($codModular);
/*comrobamos si el correo y/o Dni se encuentra registrado*/
/*$verficaDocumento = $this->tramite->buscaEmail($from_mail);
$verfica = '';
if($verficaDocumento["num"] == 0){
$verfica = true ;
}
if($verficaDocumento["num"] >= 1){
$verfica = false ;
}
*/
if(true){
$mail = new PHPMailer();
$mail->isSMTP();
//$mail->SMTPDebug = 1;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Host = "mail.ugel03.gob.pe";
$mail->Port = 25;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = false;
$mail->Username = "<EMAIL>";
$mail->Password = "<PASSWORD>";
$mail->From = $from_mail;
$mail->FromName = $from_name;
$mail->AddAddress('<EMAIL>',"Generico");
if(!$mail->Send()) {
$data["message"] = "Error en el envíos: " . $mail->ErrorInfo;
$error = 1;
} else {
$data["message"] = $txtnombres." ¡En buena hora! datos registrados correctamente ";
$error = 0;
}
/*envio mensaje de confirmacion al solicitante*/
// $Pass = generateRandomPass(6);
$from_mail = '<EMAIL>' ;
$mail->From = $from_mail;
$mail->FromName = $from_name;
$mail->AddCC((string)$this->input->post("emailUser"),"Usuario");
$mail->Subject = '[UGEL03]Buzon de Consultas UGEL03';
$mail->Body = '<b>UNIDAD DE GESTION EDUCATIVA LOCAL 03 </b><br>
Estimado(a) <b>'.$from_name2.'</b><br>
Se ha registrado correctamente su consulta a nuestro buzon.<br>
<b>Detalle:</b><br>
<b>Asunto: </b>'.$tituloConsulta.'<br>
<b>Descripción: </b>'.$asuntoReclamo.'<br>
<b>Institución educativa: </b>'.$nombreIe["num"].'<br>
<b>Fecha de Registro: </b>'.$fechaRegistro.'<br>
<b>Medios de comunicación usuario:</b><br>
<b>Telefono Usuario : </b>'.$telefonoUsuario["num"].'<br>
<b>Correo Usuario : </b>'.trim($this->input->post("emailUser")).'<br>
Gracias por registrar su consulta al nuevo portal de Buzon de Consultas <br>
<br> Atte:<br><b>UGEL03 </b><br>
Telef : (01) 6155800 Anexo: 13018 Informes <br> Atención de 8:30am a 1:00pm y 2:00 a 4:30pm<br> UGEL 03 - Av. Iquitos 918, La Victoria';
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
if(!$mail->Send()) {
$data["message"] = "Error en el envío: " . $mail->ErrorInfo;
$error = 1;
} else {
$data["message"] = $from_name2.", Se ha enviado un correo de confirmacion sus datos fueron registrados correctamente. ";
$error = 0;
}
$data = array(
"msg"=>$data["message"],
"error" => $error
);
$this->session->set_userdata($data);
/***********savedata***********************/
$dataview["idUsuario"] = $this->input->post("doc");
$dataview["titulo"] = $this->input->post("tituloConsulta");
$dataview["descripcion"] = $this->input->post("asuntoReclamo");
$dataview["ie"] = $this->input->post("ie");
$dataview["fechaConsulta"] = date("Y-m-d H:i:s");
$dataview["modificado"] = date("Y-m-d H:i:s");
$dataview["estado"] = '1';
$dataview["flg"] = '1';
$this->tramite->save_Consultabuzon($dataview);
echo json_encode($data["msg"]);
}/*else{
$data["message"] = "El correo electronico ya se encuentra registrado";
$error = 2;
$data = array(
"msg"=>$data["message"],
"error" => $error
);
echo json_encode($data);
}*/
}
public function logout(){
$this->session->sess_destroy();
redirect("login/index");
}
}
<file_sep>/admin/models/old/Merito_model.php
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Merito_model extends CI_Model
{
public $table = 'tb_merito';
public $id = 'id_merito';
public $order = 'DESC';
function __construct()
{
parent::__construct();
}
// get all
function get_all(){
$this->db->distinct();
$this->db->join('tb_inscripcion', 'tb_inscripcion.id_inscripcion = tb_merito.inscripcion_id');
$this->db->order_by($this->id, $this->order);
return $this->db->get($this->table)->result();
}
// get data by id
function get_by_id($id)
{ $this->db->distinct();
$this->db->join('tb_inscripcion', 'tb_inscripcion.id_inscripcion = tb_merito.inscripcion_id');
$this->db->where($this->id, $id);
return $this->db->get($this->table)->row();
}
// get total rows
function total_rows($q = NULL) {
$this->db->distinct();
$this->db->join('tb_inscripcion', 'tb_inscripcion.id_inscripcion = tb_merito.inscripcion_id');
$this->db->order_by($this->id, $this->order);
$this->db->like('id_merito', $q);
$this->db->or_like('control_id', $q);
$this->db->or_like('inscripcion_id', $q);
$this->db->or_like('descripcion_ins', $q);
$this->db->or_like('orden', $q);
$this->db->or_like('dni', $q);
$this->db->from($this->table);
return $this->db->count_all_results();
}
function get_limit_data($limit, $start = 0, $q = NULL) {
$this->db->distinct();
$this->db->join('tb_inscripcion', 'tb_inscripcion.id_inscripcion = tb_merito.inscripcion_id');
$this->db->join('tb_control_adju', 'tb_control_adju.id_control = tb_merito.control_id');
$this->db->join('tb_fase', 'tb_fase.id_fase = tb_control_adju.id_fase');
$this->db->join('tb_etapa', 'tb_etapa.id_etapa = tb_control_adju.id_etapa');
$this->db->order_by($this->id, $this->order);
$this->db->like('id_merito', $q);
// $this->db->or_like('control_id', $q);
$this->db->or_like('inscripcion_id', $q);
$this->db->or_like('descripcion_ins', $q);
//$this->db->or_like('orden', $q);
$this->db->or_like('dni', $q);
$this->db->limit($limit, $start);
return $this->db->get($this->table)->result();
}
// insert data
function insert($data)
{
$this->db->insert($this->table, $data);
}
// update data
function update($id, $data)
{
$this->db->where($this->id, $id);
$this->db->update($this->table, $data);
}
// delete data
function delete($id)
{
$this->db->where($this->id, $id);
$this->db->delete($this->table);
}
}
<file_sep>/app/libraries/My_dom.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class My_dom {
public function My_dom()
{
require_once dirname(__FILE__) . '/simple_html_dom.php';
}
}
?><file_sep>/app/views/login/registro.php
<!DOCTYPE html>
<html lang="en" class="h-100">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Mesa de Partes Virtual | Ugel03 </title>
<link href="<?php echo site_resource('mdp')?>/css/style.css" rel="stylesheet" />
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo site_resource('mdp')?>/images/logo-full.png">
<script src="<?php echo site_resource('mdp')?>/js/plugins/jquery-3.3.1.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/jquery.validate.min.js"></script>
</head>
<script type="text/javascript">
function countChar(val) {
var len = val.value.length;
if (len >= 250) {
val.value = val.value.substring(0, 250);
} else {
$('#charNum').text(250 - len);
}
};
function soloNumeros(e)
{
var key = window.Event ? e.which : e.keyCode
return ((key >= 48 && key <= 57) || (key==8))
}
$(window).resize(function() {
$('#afr-cmessage').css({
left: ($(window).width() - $('#afr-cmessage').outerWidth(true))/2,
top: ($(window).height() - $('#afr-cmessage').outerHeight(true))/2
});
});
function myFunction(){
$.ajax({
url:"<?php echo site_url("Login/consultadni")?>",
data:{id:$("#txtdoc").val()},
dataType:"json",
type:"POST",
success:function(data){
$("#txtnombre").val("");
$("#txtnombre").val(data.nombres);
$("#txtapepat").val("");
$("#txtapepat").val(data.apellido_paterno);
$("#txtapemat").val("");
$("#txtapemat").val(data.apellido_materno);
}
});
}
function myFunction2(){
$.ajax({
url:"<?php echo site_url("Login/consultaruc")?>",
data:{id:$("#txtdoc").val()},
dataType:"json",
type:"POST",
success:function(data){
$("#txtnombre").val("");
$("#txtnombre").val(data.razonsocial);
}
});
}
// MUESTRA EL INPUT DONDE INGRESA CARGO SI SELECCIONA 12
$(function(){
$('#cboCargo').click(function() {
if ($('#cboCargo').val() == 12) {
$('#txtcargo').css("display", "");
return true;
}else{
$('#txtcargo').css("display", "none");
return false;
}
});
})
$(function(){
$('#condiciones').click(function() {
if ($(this).is(':checked')) {
$("#resultadocheck").val(1);
}else{
$("#resultadocheck").val(0);
}
});
$("#cboTipoPersona").change(function(){
$("#cboTipoPersona option:selected").each(function() {
TipoPersona = $('#cboTipoPersona').val();
$.post(
"<?php echo(site_url("Login/gettipodoc"))?>",
{TipoPersona : TipoPersona},
function(data) {$("#coTipoDocumento").html(data); }
);
});
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if(valueSelected==1){
$("#txtdoc").prop("disabled",false);
$("#divRazon").css("display", "none");
$("#divRazon").removeClass("required");
$("#divIE").css("display", "none");
$("#divIE").removeClass("required");
$("#divNombres").css("display", "");
$("#txtnombres").val("");
$("#txtapePaterno").val("");
$("#txtapeMaterno").val("");
$("#txtapepat").addClass("required");
$("#txtapemat").addClass("required");
$("#txtnombre").addClass("required");
$('#lblNroDoc').text("Número de Documento");
$('#lblBus').text("Búsqueda");
$("#btnbsuquedadni").show();
$("#btnbsuquedaruc").hide();
$("#txtdoc").attr('maxlength', 8);
$("#txtdoc").attr("placeholder", "Ingrese Documento");
$("#txtdoc").val("");
//$('#txtcontra').val("AF@34d");
//console.log($("#txtnombre").val());
}else if(valueSelected==2){
$("#txtdoc").prop("disabled",false);
$("#divNombres").css("display", "none");
$("#divNombres").removeClass("required");
$("#divIE").css("display", "none");
$("#divIE").removeClass("required");
$("#divRazon").css("display", "");
$("#divRazon").addClass("required");
$("#txtnombres").val("");
$("#txtapePaterno").val("");
$("#txtapeMaterno").val("");
$("#txtapepat").removeClass("required");
$("#txtapemat").removeClass("required");
$("#txtnombre").addClass("required");
$('#lblNroDoc').text("Número de Documento");
$('#lblBus').text("Búsqueda");
$("#btnbsuquedadni").hide();
$("#btnbsuquedaruc").show();
$("#txtdoc").attr('maxlength', 11);
$("#txtdoc").attr("placeholder", "Ingrese Numero R.U.C");
$("#txtdoc").val("");
} else if(valueSelected==3){
$("#txtdoc").prop("disabled",false);
$("#divNombres").css("display", "none");
$("#divNombres").removeClass("required");
$("#divRazon").css("display", "none");
$("#divRazon").removeClass("required");
$("#divIE").css("display", "");
$("#divIE").addClass("required");
$("#txtnombres").val("");
$("#txtapePaterno").val("");
$("#txtapeMaterno").val("");
$("#txtapepat").removeClass("required");
$("#txtapemat").removeClass("required");
$("#txtnombre").addClass("required");
$('#lblNroDoc').text("Cod Local y/o Modular");
$('#lblBus').text("");
$("#btnbsuquedadni").hide();
$("#btnbsuquedaruc").hide();
$("#cboCargo").css("display", "");
$("#lblCargo").text("Cargo:");
//$("#txtcargo").addClass("required");
$("#txtdoc").attr('maxlength', 6);
$("#txtdoc").attr("placeholder", "Ingrese código modular/local");
$("#txtdoc").val("");
} else if(valueSelected==4){
$("#txtdoc").prop("disabled",false);
$("#divNombres").css("display", "");
$("#divNombres").addClass("required");
$("#divRazon").css("display", "none");
$("#divRazon").removeClass("required");
$("#divIE").css("display", "");
$("#divIE").addClass("required");
$("#txtnombres").val("");
//$("#txtnombres").css("display", "");
$("#txtapePaterno").val("");
//$("#txtapePaterno").css("display", "");
$("#txtapeMaterno").val("");
//$("#txtapeMaterno").css("display", "");
$("#txtapepat").addClass("required");
$("#txtapemat").addClass("required");
$("#txtnombre").addClass("required");
$('#lblNroDoc').text("Numero de Documento");
$('#lblBus').text("Búsqueda");
$("#btnbsuquedadni").show();
$("#btnbsuquedaruc").hide();
$("#cboCargo").css("display", "none");
$("#lblCargo").text("");
$("#txtdoc").attr('maxlength', 8);
$("#txtdoc").attr("placeholder", "Ingrese Doc. Nacional de Identidad");
$("#txtdoc").val("");
}
});
$("#ap-frmRegistro").validate({
errorElement: "span",
errorClass: "afr-error",
errorPlacement: function(error, element) {},
submitHandler: function(forms) {
//$('.afr-btn').attr("disabled","disabled");
// forms.submit();
enviarFormDatosPersonales()
}
})
$("#afr-btnclose").click(function() {
$("#afr-cmessage").fadeOut(500, function() {
$("#afr-overlay").fadeOut(700);
});
});
$('#afr-cmessage').css({
left: ($(window).outerWidth() - $('#afr-cmessage').outerWidth(true)) / 2,
top: ($(window).outerHeight() - $('#afr-cmessage').outerHeight(true)) / 2
});
setTimeout(function() {
$("#afr-msg").fadeOut(12000);
}, 1800);
$("#ap-frmRegistro").validate({
rules: {
userLogin: "required",
userLogin: {
required: true,
email: true
}
},
messages: {
userLogin: "Por favor ingresar email."
},
errorElement: "span",
errorClass: "afr-error",
errorPlacement: function(error, element) {},
submitHandler: function(forms) {
enviarFormDatosPersonales();
}
})
})
function enviarFormDatosPersonales__() {
var datastring = $("#ap-frmRegistro").serialize();
$(".loader").css("display", "block");
$(".alert-success").css("display", "none");
$(".alert-danger").css("display", "none");
$.ajax({
url: $("#ap-frmRegistro").attr('action'),
method: "POST",
data: datastring,
dataType: "JSON",
beforeSend: function() {
// $("#in-pogress").html("Processing daata");
},
success: function(data) {
// alert(data.msg);
switch (data.error) {
case 0:
$(".alert-success").text(data.msg);
$(".alert-success").css("display", "block");
$(".alert-danger").css("display", "none");
$(".loader").css("display", "none");
/*
<?php $this->session->sess_destroy(); ?>
location.reload();*/
break;
case 1:
$(".alert-danger").text(data.msg);
$(".alert-danger").css("display", "block");
$(".alert-success").css("display", "none");
$(".loader").css("display", "none");
break;
case 2:
$(".alert-danger").text(data.msg);
$(".alert-danger").css("display", "block");
$(".alert-success").css("display", "none");
$(".loader").css("display", "none");
break;
case 3:
$(".alert-danger").text(data.msg);
$(".alert-danger").css("display", "block");
$(".alert-success").css("display", "none");
$(".loader").css("display", "none");
break;
default:
// code block
}
if (data.error == 3) {
} else {
}
}
})
}
function enviarFormDatosPersonales() {
var datastring = $("#ap-frmRegistro").serialize();
$.ajax({
url: $("#ap-frmRegistro").attr('action'),
method: "POST",
data: datastring,
dataType: "JSON",
beforeSend: function() {
},
success: function(data) {
switch (data.resp) {
case 100:
$(this).closest('form').find("input[type=text]").val("");
alert(data.text);
window.location.href = "<?php echo site_url('Login') ?>";
break;
case 10:
alert(data.text);
break;
default:
// code block
}
}
})
}
</script>
<body class="h-100">
<div class="authincation h-100">
<div class="container h-100">
<div class="row justify-content-center h-100 align-items-center">
<div class="col-md-10">
<div class="authincation-content">
<div class="row no-gutters">
<div class="col-xl-12">
<div class="auth-form">
<div class="text-center mb-3">
<a href="index.html"><img src="<?php echo site_resource('mdp')?>/images/logo-full.png" alt=""></a>
</div>
<h4 class="text-center mb-4 text-white"><strong>Registrarse</strong></h4>
<form id="ap-frmRegistro" name="ap-frmRegistro" action="<?php echo(site_url('Login/enviarRegistroDatos'))?>" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-4">
<label class="mb-1 text-white">Tipo de Persona</label>
<?php
echo "<select class='form-control' id='cboTipoPersona' name='cboTipoPersona' required='required' >";
if (count($tipopersona)) {
echo "<option value='0'>[--Seleccione--]</option>";
foreach ($tipopersona as $list) {
echo "<option value='". $list['idTipPer'] . "'>" . $list['descripcion'] . "</option>";
}
}
echo "</select>";
?>
</div>
<div class="form-group col-md-4">
<label class="mb-1 text-white">Tipo de Documento</label>
<select class="form-control" required="required" id="coTipoDocumento" name="coTipoDocumento">
<option value="0">[--Seleccione--]</option>
</select>
</div>
<div class="form-group col-md-3">
<label class="mb-1 text-white" id="lblNroDoc" name="lblNroDoc">Nro Documento</label>
<input class="form-control" type="text" onkeypress="return soloNumeros(event);" maxlength="11" placeholder="Ingrese Documento" name="txtdoc" id="txtdoc">
</div>
<div class="form-group col-md-1">
<label class="mb-1 text-white" id="lblBus" name="lblBus"></label>
<button id="btnbsuquedadni" name="btnbsuquedadni" onclick="myFunction()" style="background-color: #E12222;color: white;height: 55px;width: 65px;display:none" ><i class="fa fa-search"></i></button>
<button id="btnbsuquedaruc" name="btnbsuquedaruc" onclick="myFunction2()" style="background-color: #E12222;color: white;height: 55px;width: 65px;display:none " ><i class="fa fa-search"></i></button>
</div>
</div>
<div class="form-row" id="divNombres" name="divNombres">
<div class="form-group col-md-4">
<label class="mb-1 text-white">Nombres:</label>
<input type="text" class="form-control" placeholder="Ingrese Nombres" name="txtnombre" id="txtnombre" maxlength="40" >
</div>
<div class="form-group col-md-4">
<label class="mb-1 text-white">Apellido Paterno:</label>
<input type="text" class="form-control" placeholder="Ingrese Apellido Paterno" name="txtapepat" id="txtapepat" maxlength="30" >
</div>
<div class="form-group col-md-4">
<label class="mb-1 text-white">Apellido Materno:</label>
<input type="text" class="form-control" placeholder="Ingrese Apellido Materno" name="txtapemat" id="txtapemat" maxlength="30" >
</div>
</div>
<div class="form-row" id="divRazon" name="divRazon" style="display:none;">
<div class="form-group col-md-12">
<label class="mb-1 text-white">Razón Social:</label>
<input type="text" class="form-control" placeholder="Ingrese Razón Social" name="txtrazonsocial" id="txtrazonsocial" maxlength="40">
</div>
</div>
<div class="form-row" id="divIE" name="divIE" style="display:none;">
<div class="form-group col-md-8">
<label class="mb-1 text-white">Institución Educativa:</label>
<input type="text" class="form-control" placeholder="Ingrese Institución Educativa" id="txtie" name="txtie" maxlength="80">
</div>
<div class="form-group col-md-4">
<label class="mb-1 text-white" id="lblCargo">Cargo:</label>
<?php
echo "<select class='form-control' id='cboCargo' name='cboCargo'>";
if (count($Cargo)) {
echo "<option value=''>[--Seleccione--]</option>";
foreach ($Cargo as $list) {
echo "<option value='". $list['idCargo'] . "'>" . $list['descripcion_cargo'] . "</option>";
}
echo "<option value='12'>".'OTROS'."</option> <br>";
echo '<input style="display:none" type="text" class="form-control" placeholder="Ingrese Otro Cargo" name="txtcargo" id="txtcargo" maxlength="30">';
}
echo "</select>";
?>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label class="mb-1 text-white">Teléfono</label>
<input class="form-control" onkeypress="return soloNumeros(event);" placeholder="Ingrese Teléfono" maxlength="9" type="tel" name="txtphone" id="txtphone" required >
</div>
<div class="form-group col-md-4">
<label class="mb-1 text-white">Correo</label>
<input class="form-control" type="email" placeholder="Ingrese Correo" name="txtemail" id="txtemail" maxlength="80" required >
</div>
<div class="form-group col-md-4">
<label class="mb-1 text-white">Repetir correo</label>
<input class="form-control" type="email" placeholder="<NAME>" name="txtemail2" id="txtemail2" maxlength="80" required >
</div>
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="condiciones" name="condiciones" data-toggle="modal" data-target="#exampleModalLong" >
<label class="mb-1 text-white">
Acepto contacto por el correo ingresado
</label>
<input id="resultadocheck" name="resultadocheck" type="hidden" value="0">
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Terminos y condiciones</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p style="text-align:justify"> Al dar click en este casillero, usted está autorizando </p>
<p style="text-align:justify"><b> Veracidad de la información declara por el administrado</b></p>
<p style="text-align:justify"> Declaro expresamente que la información ingresa en la Plataforma para el proceso de contratación docente 2020 es verdadera y conforme con lo establecido en el artículo 49 del Texto Único Ordenado de la Ley N° 27444, Ley del Procedimiento Administrativo General, y en caso de resultar falsa la información que proporciono, me sujeto a los alcances de lo establecido en el artículo 411 del Código Penal, concordante con el artículo 33 del Texto Único Ordenado de la Ley N° 27444, Ley del Procedimiento Administrativo General; autorizando a efectuar la comprobación de la veracidad de la información declarada en la presente plataforma.</p>
<p style="text-align:justify"><b> Autorización para la notificación al correo electrónico</b> </p>
<p style="text-align:justify">AUTORIZO de forma expresa y conforme a lo dispuesto por el artículo N° 20 del Texto único Ordenando de la Ley N° 27444 – Ley del Procedimiento Administrativo General, aprobado mediante el DECRETO SUPREMO Nº 004-2019-JUS y modificado mediante el Decreto Legislativo N° 1497, a la UNIDAD DE GESTION EDUCATIVA LOCAL 03 – UGEL 05, que me notifique el/los acto(s) administrativo(s), comunicados o documentación adicional que se emitan a consecuencia del proceso de contratación docente 2020 al correo electrónico consignado en presente plataforma; así mismo acuerdo que el acto administrativo, los comunicados o la documentación adicional pueda estar contenida en un archivo adjunto o un enlace web a través del cual se descargará y/o otros mecanismo que garanticen su notificación.</p>
<p style="text-align:justify">Tengo conocimiento que las notificaciones dirigidas a la dirección de mi correo electrónico señalada en la presente Plataforma se entiende válidamente efectuadas cuando la UGEL 05 reciba la respuesta de recepción de la dirección electrónica antes señalada; a través del acuse de recibo, el mismo que dejará constancia del acto de notificación; en concordancia a lo establecido por el artículo 20 del mencionado Texto Único Ordenado, surtiendo efectos el día siguiente que conste haber sido recibido en mi bandeja de entrada, conforme a lo previsto en el numeral 2 del artículo 25 del citado Texto Único Ordenado.</p>
<p style="text-align:justify">
En atención a la presente autorización me comprometo con las siguientes obligaciones:
1. Señalar una dirección de correo electrónica válida, a la cual tenga acceso y que se mantenga activa durante el proceso de contratación docente 2020.
2. Asegurar que la capacidad del buzón de la dirección de correo electrónico permita recibir los documentos a notificar.
3. Revisar continuamente la cuenta de correo electrónico, incluyendo la bandeja de spam o el buzón de correo no deseado.</p>
<p style="text-align:justify">El no tomar conocimiento oportuno de las notificaciones remitidas por la UNIDAD DE GESTION EDUCATIVA LOCAL 03 – UGEL 05, debido al incumplimiento de las presentes obligaciones, constituye exclusiva responsabilidad de mi persona. </p>
<p style="text-align:justify">DECRETO LEGISLATIVO Nº 1497: DECRETO LEGISLATIVO QUE ESTABLECE MEDIDAS PARA PROMOVER Y FACILITAR CONDICIONES REGULATORIAS QUE CONTRIBUYAN A REDUCIR EL IMPACTO EN LA ECONOMÍA PERUANA POR LA EMERGENCIA SANITARIA PRODUCIDA POR EL COVID- 19
Artículo 3.- Incorporación de párrafo en el artículo 20 de la Ley Nº 27444, Ley del Procedimiento Administrativo General
Incorpórase un último párrafo en el artículo 20 de la Ley Nº 27444, Ley del Procedimiento Administrativo General, cuyo texto queda redactado de la manera siguiente:
“Artículo 20.- Modalidades de notificación
(…)</p>
<p style="text-align:justify">El consentimiento expreso a que se refiere el quinto párrafo del numeral 20.4 de la presente Ley puede ser otorgado por vía electrónica.”</p>
<p style="text-align:justify"><b>Autorización para el tratamiento de los datos personal del administrado</b></p>
<p style="text-align:justify">En atención a los dispuesto por la Ley N° 29733, Ley de Protección de Datos Personales y su Reglamento aprobado por Decreto Supremo N° 003-2013-JUS, AUTORIZO a la UNIDAD DE GESTION EDUCATIVA LOCAL 03 – UGEL 05 al tratamiento de mis datos personales, así como cualquier otra información ingresada en la plataforma para el proceso de contratación docente 2020.</p>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
<!--- MENSAJE DE ERROR Y/O BIENVENIDA -->
<div class="mc-footer">
<div style="display:none" class="alert alert-card alert-success" role="alert"> <strong>Registro Exitoso!</strong> el sistema enviara un correo con los accesos. <button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</div>
<div style="display:none" id="error" class="alert alert-card alert-danger" role="alert"><strong>Ocurrio un error !</strong> vuelva a registrar nuevamente.<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</div>
</div>
<div class="text-center mt-1">
<button type="submit" class="btn bg-danger text-white btn-block">
<i class="fa fa-check color-info"></i> Registrarse
</button>
</div>
</form>
<div class="new-account mt-3 text-right">
<p class="text-white"> ¿Ya tienes con una cuenta? <a class="text-white" href="<?php echo(site_url('Login'))?>">Iniciar Sesión</a> </p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="<?php echo site_resource('mdp')?>/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
<!--<script src="<?php echo site_resource('mdp')?>/js/custom.min.js"></script>-->
<!-- <script src="<?php echo site_resource('mdp')?>/js/deznav-init.js"></script>-->
<!--<script src="<?php echo site_resource('mdp')?>/vendor/global/global.min.js"></script>-->
<script src="<?php echo site_resource('mdp')?>/js/plugins/bootstrap.bundle.min.js"></script>
</body>
</html><file_sep>/app/views/tramite/home-on.php
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>FORMULARIO ÚNICO DE TRAMITE (FUT)</title>
<script src="<?php echo site_resource('admin') ?>/js/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="<?php echo site_resource('admin') ?>/js/custominputfile.min-es.js"></script>
<script src="<?php echo site_resource('admin') ?>/js/jquery.validate.min.js"></script>
<script src="<?php echo site_resource('admin') ?>/js/messages_es.js"></script>
<link rel="stylesheet" href="<?php echo site_resource('admin') ?>/js/css/custominputfile.min.css" type="text/css" />
<link rel="stylesheet" href="<?php echo site_resource('admin') ?>/css/style.css" type="text/css" />
<script type="text/javascript">
var cbo;
var dependencia = [];
<?php
foreach($solicitud as $item){
?>
dependencia[<?php echo $item["id_tippedido"]?>] = "<?php echo $item["referencia"]?>";
<?php
}
?>
$(window).resize(function(){
$('#afr-cmessage').css({
left: ($(window).width() - $('#afr-cmessage').outerWidth(true))/2,
top: ($(window).height() - $('#afr-cmessage').outerHeight(true))/2
});
});
$(function(){
$("#afr-btnclose").click(function(){
$("#afr-cmessage").fadeOut(500,function(){
$("#afr-overlay").fadeOut(700);
});
});
$('#afr-cmessage').css({
left: ($(window).outerWidth() - $('#afr-cmessage').outerWidth(true))/2,
top: ($(window).outerHeight() - $('#afr-cmessage').outerHeight(true))/2
});
setTimeout(function(){
$("#afr-msg").fadeOut(2000);
},1800);
var validar = $("#afr-frmfut").validate({
errorElement:"span",
errorClass:"afr-error",
errorPlacement: function(error, element){},
submitHandler:function(forms){
$('.afr-btn').attr("disabled","disabled");
forms.submit();
},
rules: {
'via[]':{ required:true },
'afr-file[]' :{ required:true }
}
})
$("#cbservicio").change(function(){
idservicio = $(this).val();
switch(idservicio){
case "9" :
/*alert("AFR Soft");return false;*/
break;
}
$("#afr-dependencia").text(dependencia[$(this).val()]);
$("#txtdependencia").val(dependencia[$(this).val()]);
$("#ulfile li").remove();
$("#afr-message table tr").remove();
$("#cbcosto option").remove();
items_requisito = "";
$.ajax({
url:"<?php echo site_url("tramite/requisitos")?>",
data:{id:$(this).val()},
dataType:"json",
type:"POST",
success:function(data){
var ctrl = 0;
$.each(data.requisitos,function(index, items){
ctrl = ctrl + 1;
items_requisito = items_requisito + '<li><label>' + items.descripcion + ':</label><input type="file" name="afr-file[' + ctrl + ']" class="required" id="requisito' + ctrl + '"></li>';
})
if(data.costo.length > 0){
if(idservicio == 2){
var tr = "";
var opt = '<option value="">-- Seleccione --</option>';
$.each(data.costo,function(index, items){
tr = tr + '<tr><td style="width:140px;">' + items.observacion + '</td><td style="width:80px;">S/. ' + items.costo + '</td></tr>'
opt = opt + '<option value="' + items.costo + '">' + items.observacion + ' --- ' + 'S/.' + items.costo + '</option>';
})
$("#cbcosto").append(opt);
$("#afr-message table").append(tr);
$("#cbcosto").show();
$("#afr-overlay").fadeIn(500,function(){
$("#afr-cmessage").fadeIn(700);
});
$("#ulfile").append(items_requisito);
$("#afr-costo span").text("0.00");
return false;
}
$("#cbcosto").hide();
$.each(data.costo,function(index, items){
$("#afr-costo span").text(items.costo);
})
}
else{
$("#cbcosto").hide();
$("#afr-costo span").text("0.00");
}
//alert(data.requisitos[0].id_requisito);
$("#ulfile").append(items_requisito);
}
});
$("#cbcosto").change(function(){
$("#afr-costo span").text($(this).val());
});
/*$.post("<?php echo site_url("tramite/requisitos")?>",{id:$(this).val()},function(data){
alert(data.requisito);
$("#ulfile").append(data);
});*/
});
})
</script>
</head>
<body>
<div id="afr-wrapper">
<div id="afr-overlay">
</div>
<div id="afr-cmessage">
<div id="afr-bodymsg">
<a href="javascript:void(0)" id="afr-btnclose">X</a>
<div id="afr-headmsg">Escala de Pagos</div>
<div id="afr-message">
<table>
</table>
</div>
</div>
</div>
<div id="afr-toph">
<div id="afr-menu">
<div id="afr-date">
Lima, <?php echo datesmart(date("Y-m-d"),'{day} {month:name} {year}') ?>
</div>
</div>
</div>
<div id="afr-cheader">
<div id="afr-navmenu">
<div id="afr-header">
<div id="afr-logo">
<img src="<?php echo site_resource('admin') ?>/img/logo-ugel03.jpg" >
<div id="afr-rm">
RM N° 0445-2012-ED
</div>
</div>
</div>
</div>
</div>
<div id="afr-bgcontaniner">
<div id="afr-container">
<div id="afr-contform">
<?php if(@$this->session->userdata("msg")!=""){ ?>
<div id="afr-msg" class="afr-msg <?php echo((@$this->session->userdata("error")==1)? "afr-msgerror":"")?>">
<?php echo @$this->session->userdata("msg");
$this->session->sess_destroy();
?>
</div>
<?php }?>
<form id="afr-frmfut" name="afr-frmfut" action="<?php echo(site_url("tramite/enviar"))?>" method="post" enctype="multipart/form-data">
<input type="hidden" name="txtdependencia" id="txtdependencia">
<table id="afr-tblmain" border="0" cellpadding="0" cellspacing="0">
<tr class="">
<td class="borde-down">
FORMULARIO ÚNICO DE TRAMITE (FUT)
</td>
<td rowspan="6" class="borde-down border-left" style="width:200px" id="afr-costo">
<img src="<?php echo site_resource('admin') ?>/img/logo-bn.png" border="0" >
<div>Banco de la Nación</div>
<div>Cta. Cte. N°: 0000-281905</div>
<div>COSTO:</div><div id="afr-costo" style="font-weight:700;font-size:20px" >S/. <span>0.00</span></div>
<div>
<select id="cbcosto" name="cbcosto" class="required">
<option value="">-- Seleccione --</option>
</select>
</div>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="borde-down spaceleft">
I.- Resumen de su pedido:
<span>
<select id="cbservicio" name="cbservicio" required>
<option value="">-- Seleccione solicitud --</option>
<?php
foreach($solicitud as $item){
?>
<option value="<?php echo $item["id_tippedido"]?>"><?php echo $item["nombre"]?></option>
<?php
}
?>
</select>
</span>
</td>
</tr>
<tr class="textleft">
<td class="borde-down">
<textarea id="txtresumen" name="txtresumen" placeholder="Detalle su solicitud" class="afr-textarea required" ></textarea>
</td>
</tr>
<tr class="textleft">
<td class="borde-down spaceleft">
II. Dependecia o autoridad a quien se dirige: <span id="afr-dependencia" style="font-weight:700">DIRECTOR UGEL 03</span>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="borde-down spaceleft">
III. Datos del solicitante:
</td>
</tr>
<tr class="textleft">
<td class="spaceleft">
Persona Natural:
</td>
</tr>
<tr>
<td colspan="2">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr style="height:60px;">
<td style="width:325px; " class="spaceleft">
<label>Apellido Paterno:</label><input class="textborder" style="width:213px; height:24px" type="text" name="txtapepat" id="txtapepat">
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
<label>Apellido Materno:</label><input class="textborder" style="width:213px; height:24px" type="text" name="txtapemat" id="txtapemat">
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
<label>Nombres:</label><input class="textborder" type="text" style="width:213px; height:24px" name="txtnombre" id="txtnombre">
</td>
</tr>
</table>
</td>
</tr>
<tr class="textleft">
<td class="spaceleft">
Persona Jurídica:
</td>
</tr>
<tr class="textleft">
<td colspan="2" class="spaceleft">
<label>Razón Social:</label><input class="textborder" style="width:833px; height:24px" type="text" name="txtrazonsocial" id="txtrazonsocial">
</td>
</tr>
<tr class="textleft">
<td class="spaceleft">
Tipo de Documento:
</td>
</tr>
<tr>
<td colspan="2">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr style="height:60px;">
<td style="width:272px; " class="spaceleft">
<label>DNI N° y/o RUC:</label><input class="textborder required number" style="width:150px; height:24px" type="text" name="txtdoc" id="txtdoc" >
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
<label>IE:</label><input class="textborder" style="width:213px; height:24px" type="text" name="txtie" id="txtie">
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
<label>Cargo Actual:</label><input class="textborder" type="text" style="width:213px; height:24px" name="txtcargo" id="txtcargo">
</td>
</tr>
</table>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="spaceleft borde-down borde-top" colspan="2">
IV. DIRECCIÓN:
</td>
</tr>
<tr>
<td colspan="2">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="spaceleft">TIPO DE VÍA:</td>
<td><label>Avenida:</label><input type="radio" name="rbtvia" value="1"></td>
<td><label>Jirón:</label><input type="radio" name="rbtvia" value="2"></td>
<td><label>Calle:</label><input type="radio" name="rbtvia" value="3"></td>
<td><label>Pasaje:</label><input type="radio" name="rbtvia" value="4"></td>
<td><label>Carretera:</label><input type="radio" name="rbtvia" value="5"></td>
<td><label>Prolongación:</label><input type="radio" name="rbtvia" value="6"></td>
<td><label for="rbtvia[]" class="afr-error" style="display:none;">Please choose one.</label></td>
</tr>
</table>
</td>
</tr>
<tr class="textleft">
<td colspan="2" class="spaceleft">
<label style="display:inline-block; width:90px;">Nombre de la vía:</label><input class="textborder required" style="width:814px; height:24px" type="text" name="txtnomvia" id="txtnomvia" >
</td>
</tr>
<tr class="textleft">
<td colspan="2" class="spaceleft">
<label style="display:inline-block; width:90px;">Referencia:</label><input class="textborder required" style="width:814px; height:24px" type="text" name="txtreferencia" id="txtreferencia" >
</td>
</tr>
<tr>
<td colspan="2" class="spaceleft">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<label>Teléfonos:</label><input class="textborder" style="width: height:24px" type="text" name="txtphone" id="txtphone">
</td>
<td>
<label>Código Modular:</label><input class="textborder" style="width: height:24px" type="text" name="txtmodula" id="txtmodula">
</td>
<td>
<label>Correo:</label><input class="textborder email" style="width: height:24px" type="text" name="txtemail" id="txtemail" required >
</td>
</tr>
</table>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="spaceleft borde-down borde-top" colspan="2">
DECLARO que los datos presentados en el presente formulario los realizo con carácter de DECLARACIÓN JURADA
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="spaceleft borde-down " colspan="2">
V. FUNDAMENTOS DEL PEDIDO:
</td>
</tr>
<tr class="textleft">
<td class="borde-down" colspan="2">
<textarea id="txtfundpedido" name="txtfundpedido" placeholder="Escriba aquí fundamento de pedido." class="afr-textarea" style="height:80px" required ></textarea>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="spaceleft borde-down " colspan="2">
VI. DOCUMENTOS QUE SE ADJUNTAN:
</td>
</tr>
<tr class="textleft">
<td class="" colspan="2">
<ul id="ulfile">
<li>
<label>* Copia de DNI :</label>
<input type="file" name="afr-file[]" class="required requisito" id="file1" >
</li>
</ul>
</td>
</tr>
<tr class="textleft ">
<td class="spaceleft" colspan="2">
Declaro que los datos presentados en el presente formulario los realizo con caracter de declaración jurada.
</td>
</tr>
</table>
<div style="text-align:right">
<div id="afr-important">
<b>Importante:</b> Antes de enviar el formulario, asegurese que su correo este digitado correctamente y sea válido.
</div>
<input type="submit" value="Enviar" class="afr-btn" >
</div>
</form>
</div>
</div>
</div>
<div style="clear:both"></div>
<div id="afr-footer">
<div id="afr-ctextfooter">
<div id="afr-textf">
<ul>
<li class="fcontact">4273210 / 4262627 / 4261562</li>
<li class="ftime">Atención de 8:30am a 1:00pm y de 2:00pm a 4:00pm</li>
<li class="fhome">UGEL 03 - Jr. Andahuaylas 563, Cercado de Lima </li>
</ul>
</div>
<div id="afr-copy">
UGEL 03 | <?Php echo date("Y");?> © Todos los derechos reservados
</div>
</div>
</div>
</div>
</body>
</html><file_sep>/app/controllers/Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
//$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function __construct()
{
parent::__construct();
ini_set("max_execution_time", 0);
$this->load->library("session");
// Importa el modelo y le da el nombre "login"
$this->load->model("Model_login","login");
$this->load->library('My_PHPMailer');
$this->load->library('My_dom');
}
public function index()
{
$this->load->view('login/login');
}
public function olvidar()
{
$this->load->view('login/olvido');
}
public function registrate()
{
$dataview['tipopersona'] = $this->login->gettipopersona();
// Envia la variable Cargo al modelo
$dataview['Cargo'] = $this->login->gettipocargo();
$this->load->view('login/registro',$dataview);
}
public function usuario()
{
if ($this->session->userdata('nroDocumento')) {
$dataview['data_usuario']= $this->login->obtenerUsuario($this->session->userdata('iduser'));
$dataview['Via'] = $this->login->gettipovia();
$dataview['Zona'] = $this->login->gettipozona();
$dataview['ubicacion'] = $this->login->getubicacion(); // Obtenemos los Departamentos
$this->load->view('usuario/usuario',$dataview);
} else {
$this->session->set_userdata(array('msg' => ''));
$this->load->view('login/login'); // CARGA la Pagina Login
}
}
public function getprovincia()
{
$options = "";
if($this->input->post('depa_id')){
$depa_id = $this->input->post('depa_id');
$proovincia = $this->login->getprovincia($depa_id);
?>
<option value="0">[--Seleccione--]</option>
<?php
foreach($proovincia as $fila)
{
?>
<option value="<?=$fila->idProv?>"><?=$fila->provincia?></option>
<?php
}
}
}
public function getdistrito(){
$options = "";
if($this->input->post('id_prov'))
{
$id_prov = $this->input->post('id_prov');
$distrito = $this->login->getdistrito($id_prov);
foreach($distrito as $fila)
{
?>
<option value="<?=$fila->idDist?>"><?=$fila->distrito?></option>
<?php
}
}
}
public function gettipodoc(){
$options = "";
if($this->input->post('TipoPersona'))
{
$TipoPersona = $this->input->post('TipoPersona');
$Tipodoc = $this->login->getTipoDoc($TipoPersona);
foreach($Tipodoc as $fila)
{
?>
<option value="<?=$fila->idDoc?>"><?=$fila->descripcion?></option>
<?php
}
}
}
public function consultaruc(){
$ruc=$this->input->post("id");
$data = file_get_html("https://api.sunat.cloud/ruc/".$ruc);
$info = json_decode($data, true);
if($data==='[]' || $info['fecha_inscripcion']==='--'){
$datos = array(0 => 'nada');
echo json_encode($datos);
}else{
$datos = array(
1 => $info['razon_social'],
);
$datosRuc["razonsocial"] = html_entity_decode($datos[1], ENT_QUOTES, "UTF-8");
echo json_encode($datosRuc);
}
}
public function consultadni(){
$dni = $this->input->post('id');
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_URL, 'https://dni.optimizeperu.com/api/persons/' .$dni);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$result = curl_exec($curl);
curl_close($curl);
$_result = json_decode($result);
$datos['nombres'] = $_result->name;
$datos['apellido_paterno'] = $_result->first_name;
$datos['apellido_materno'] = $_result->last_name;
echo json_encode($datos);
}
public function enviarLogin()
{
$msg = array();
$data = $this->login->Get_user($this->input->post("userLogin"),$this->input->post("passuser"));
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
$id_usuario = $data['id_usuario'];
$nroDocumento = $data['nroDocumento'];
$correo = $data['correo'];
$pass = $data['pass'];
$dataview["nroDocumento"] = $nroDocumento;
$dataview["id_usuario"] = $id_usuario;
$dataview["correo"] = $correo;
$dataview["pass"] = $pass;
$dataview["fecha"] = date("Y-m-d");
$dataview["ip"] = $ipaddress;
$dataview["modificado"] = date("Y-m-d H:i:s");
$dataview["estado"] = '1';
/**********************************************************/
if($data){
//$this->login->save_primerlogin($dataview);
$this->session->set_userdata(array(
"correo"=>$data['correo'],
"nroDocumento"=>$data['nroDocumento'],
"iduser"=>$data['id_usuario'],
"TipoPersona"=>$data['idTipPer'],
"TipoDocumento"=>$data['idtTipDoc'],
"nameuser"=>$data['nombre'],
"apaterno"=>$data['apPaterno'],
"amaterno"=>$data['apMaterno'],
"celular"=>$data['celular'],
"pass"=>$data['pass'],
"logueado"=>true));
$msg["resp"] = 100;
$msg["text"] = "Inicio de Sesion Exitoso!";
echo json_encode($msg);
//return $this->load->view('usuario/vistausuario');
//redirect("Login/vistausuario","refresh");
}else{
$msg["resp"] = 10;
$msg["text"] = "Usuario y/o contraseña incorrecta.";
echo json_encode($msg);
}
}
/*****************************************************/
function generate_string($input, $strength = 6) {
$input_length = strlen($input);
$random_string = '';
for($i = 0; $i < $strength; $i++) {
$random_character = $input[mt_rand(0, $input_length - 1)];
$random_string .= $random_character;
}
return $random_string;
}
/*****************************************************************************************/
public function enviarRegistroDatos()
{
$msg = array();
date_default_timezone_set('America/Lima');
/* Re-capcha:v3 */
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = [
'secret' => "6Ld3b9EZAAAAADFQvB3E4IgED1k0VIHx0KSX2EV4",
//'response' => $_POST['token'],
'remoteip' => $_SERVER['REMOTE_ADDR']
];
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
//$response = file_get_contents($url, false, $context);
//$res = json_decode($response, true);
if(true) {
$tipoPersona=$this->input->post("cboTipoPersona");
$documento=trim($this->input->post("coTipoDocumento"));
$dni=trim($this->input->post("txtdoc"));
$txtnombre = $this->input->post("txtnombre");
$txtapepat = $this->input->post("txtapepat");
$txtapemat = $this->input->post("txtapemat");
$txtrazonsocial = $this->input->post("txtrazonsocial");
$txtie = $this->input->post("txtie");
// ID DE CARGO: NUMERO
$idCargo = $this->input->post("cboCargo");
// TEXTO QUE INGRESA EN EL INPUT DE CARGO
//$txtcargo=$this->input->post("txtcargo");
// CONTRASEÑA DE 6 DIGITOS
$txtcontra=$this->input->post("txtcontra");
$txtphone=trim($this->input->post("txtphone"));
$txtemail = trim($this->input->post("txtemail"));
$txtemail2= trim($this->input->post("txtemail2"));
$resultadocheck= $this->input->post("resultadocheck");
$from_name = $txtapepat.' '.$txtapemat.' ,'.$txtnombre;
$from_name2 = $txtnombre;
$verifica = '';
//$contra1 = generate_string($permitted_chars, 6);
//$contra = sha1('AFj34d'); // ENCRIPTACION DE CONTRASEÑA
$contra = '<PASSWORD>'; // ENCRIPTACION DE CONTRASEÑA
//$contra = password_hash($contra1,PASSWORD_DEFAULT); // ENCRIPTACION DE CONTRASEÑA
$estado = '1';
/******************************VALIDA CAMPOS VACÍOS***********************************************/
if ($tipoPersona != 0) {
$verifica = true ;
} else {
$msg["resp"] = 10;
$msg["text"] = "Debe seleccionar un tipo de persona.";
echo json_encode($msg);die;
}
if ($documento != 0) {
$verifica = true ;
} else {
$msg["resp"] = 10;
$msg["text"] = "Debe seleccionar un tipo de documento.";
echo json_encode($msg);die;
}
/******************************VALIDA CORREOS IGUALES Y CHECK***********************************************/
if ($txtemail==$txtemail2) {
$verifica = true ;
} else {
//$verifica = false ;
$msg["resp"] = 10;
$msg["text"] = "Los correos electrónicos no coinciden.";
echo json_encode($msg);die;
// CAMBIO MODIFICADO
/*$data["message"] = "Los correos electrónicos no coinciden";
$error = 2;
$data = array(
"msg"=>$data["message"],
"error" => $error
);
echo json_encode($data);die;*/
}
if ($resultadocheck == 1) {
$verifica = true ;
}else{
$msg["resp"] = 10;
$msg["text"] = "Debe seleccionar la casilla de acepto contacto.";
echo json_encode($msg);die;
}
/******************************VALIDA DNI Y EMAIL***********************************/
$verificaemail = $this->login->buscaEmail($txtemail);
$verificaDocumento = $this->login->buscaDni($dni);
if($verificaemail["num"] == 0){
$verfica = true ;
}else if($verificaemail["num"] >= 1){
//$verifica = false ;
$msg["resp"] = 10;
$msg["text"] = "El Correo electronico ya se encuentra registrado.";
echo json_encode($msg);die;
}
if($verificaDocumento["num"] == 0){
$verifica = true ;
} else if($verificaDocumento["num"] >= 1){
//$verifica = false ;
$msg["resp"] = 10;
$msg["text"] = "El DNI ya se encuentra registrado.";
echo json_encode($msg);die;
}
/******************************TIEMPO DATE**********************************/
date_default_timezone_set('America/Lima');
$timestamp = time();
$fecha_actual = date("Y-m-d H:i:s", $timestamp);
/**********************************CORREO*******************************/
if($verifica){
/*$mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Host = "mail.<EMAIL>";
$mail->Port = 25;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = false;
$mail->Username = "<EMAIL>";
$mail->Password = "<PASSWORD>";
$mail->From = $txtemail;
$mail->FromName = $from_name;
if(!$mail->Send()) {
$data["message"] = "Error en el envío: " . $mail->ErrorInfo;
$error = 1;
} else {
$data["message"] = $txtnombre." ¡En buena hora! datos registrados correctamente, se ha enviado al correo el último paso para crear una cuenta en Mesa de Partes Virtual.";
$error = 0;
}
$Pass = $dni;
$from_mail = '<EMAIL>' ;
$mail->From = $txtemail;
$mail->FromName = $from_name;
$mail->AddCC((string)$this->input->post("txtemail"),"Usuario");
$mail->Subject = '[UGEL03] Confirmación de cuenta para Mesa de Partes Virtual';
$mail->Body =
'<b>UNIDAD DE GESTION EDUCATIVA LOCAL 03 </b>
<br>Estimado(a) <b>'.$from_name.'</b>
<br>
<br> Gracias por registrarse a Mesa de Partes Virtual, a través de este correo damos a conocer su usuario y contraseña provisional:
<br>
<br>Usuario : '.trim($this->input->post("txtemail")).'
<br>Contraseña : '.$Pass.'
<br>
<br>Para ingresar al sistema debe generar su contraseña oficial, a través del siguiente enlace: <a href="http://sistemas01.ugel03.gob.pe/mesadepartesvirtual/generar"> Generar Contraseña Virtual</a>
<br>
<br>
<br>Atte:
<br>
<br><b>UGEL03</b>
<br>Telef : (01) 6155800 Anexo: 13018 Informes
<br>Atención de 8:30am a 1:00pm y 2:00 a 4:30pm
<br>UGEL 03 - Av. Iquitos 918, La Victoria';
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
if(!$mail->Send()) {
$data["message"] = "Error en el envío: " . $mail->ErrorInfo;
$error = 1;
} else {
$data["message"] = $txtnombre." ¡En buena hora! datos registrados correctamente, se ha enviado al correo sus credenciales de acceso a la plataforma de Reasignación.";
$error = 0;
}
$data = array(
"msg"=>$data["message"],
"error" => $error
);*/
$this->session->set_userdata($data);
/***********GUARDADO***********************/
$dataview["idTipPer"] = $this->input->post("cboTipoPersona");
$dataview["idtTipDoc"] = $this->input->post("coTipoDocumento");
$dataview["idCargo"] = $this->input->post("cboCargo");
if($tipoPersona == '1'){
$dataview["nroDocumento"] = $this->input->post("txtdoc");
$dataview["nombre"] = $this->input->post("txtnombre");
$dataview["apPaterno"] = $this->input->post("txtapepat");
$dataview["apMaterno"] = $this->input->post("txtapemat");
}
if($tipoPersona == '2'){
$dataview["nroDocumento"] = $this->input->post("txtdoc");
$dataview["nombre"] = $this->input->post("txtrazonsocial");
}
if($tipoPersona == '3'){
$dataview["nroDocumento"] = $this->input->post("txtdoc");
$dataview["nombre"] = $this->input->post("txtie");
$dataview["idCargo"] = $this->input->post("cboCargo");
$dataview["descripcion_cargo"] = $this->input->post("txtcargo");
// VALIDA SI SE SELECCIONO 12 EN EL SELECT
/*if($idCargo == '12'){
$dataview["descripcion_cargo"] = $this->input->post("txtCargo");
}*/
}
if($tipoPersona == '4'){
$dataview["nroDocumento"] = $this->input->post("txtdoc");
$dataview["nombre"] = $this->input->post("txtnombre");
$dataview["apPaterno"] = $this->input->post("txtapepat");
$dataview["apMaterno"] = $this->input->post("txtapemat");
}
$dataview["celular"] = $this->input->post("txtphone");
$dataview["correo"] = trim($this->input->post("txtemail"));
//$dataview["pass"] = $this->input->post("txt<PASSWORD>");
$dataview["pass"] = <PASSWORD>;
$dataview["estado"] = $estado;
//$dataview["estado"] = val("1");
$dataview["modificado"] = date("Y-m-d H:i:s");
/* Registra un Usuario*/
$this->login->save_registroUsuario($dataview);
$idusu = $this->login->buscaIdUsuario($dni);
$id_usuario = $idusu["usu"];
$dataview2["id_usuario"] = $id_usuario;
//$dataview2["pass"] = $this->input->post("txtdoc");
$dataview["modificado"] = date("Y-m-d H:i:s");
$msg["resp"] = 100;
$msg["text"] = "En buena Hora registro exitoso.";
echo json_encode($msg);die;
/*$this->login->save_credencialUsuario($dataview2);
echo json_encode($data); */
}else{
$msg["resp"] = 10;
$msg["text"] = "Error al guardar la información.";
echo json_encode($msg);die;
}
} else {
$msg["resp"] = 10;
$msg["text"] = "Error! No eres un humano.";
echo json_encode($msg);die;
}
}
public function enviarActualizarDatos()
{
$msg = array();
date_default_timezone_set('America/Lima');
/* Re-capcha:v3 */
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = [
'secret' => "<KEY>",
//'response' => $_POST['token'],
'remoteip' => $_SERVER['REMOTE_ADDR']
];
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
//$response = file_get_contents($url, false, $context);
//$res = json_decode($response, true);
if(true){
$data = $this->login->Get_user($this->input->post("userLogin"),$this->input->post("passuser"));
$this->session->set_userdata($data);
// DATOS DE PERSONA
$tipoPersona = $this->session->userdata('idTipPer');
$dni=trim($this->session->userdata("nroDocumento"));
$celular = $this->input->post("celular");
$correo = $this->input->post("correo");
$password1 = $<PASSWORD>->input->post("password1");
// Datos de Direccion
$departamento = $this->input->post("cbDepartamento");
$provincia = $this->input->post("cbProvincia");
$distrito = $this->input->post("cbDistrito");
$via = $this->input->post("cbVia");
$zona = $this->input->post("cbZona");
$txtvia = $this->input->post("txtvia");
$txtzona = $this->input->post("txtzona");
$txtreferencia = $this->input->post("txtreferencia");
$id_usuario = $this->session->userdata('id_usuario');
$estado = '1';
$verifica = true;
/******************************VALIDA CAMPOS VACÍOS***********************************************/
if ($departamento != 0) {
$verifica = true ;
} else {
$msg["resp"] = 10;
$msg["text"] = "Debe seleccionar un Departamento.";
echo json_encode($msg);die;
}
if ($provincia != 0) {
$verifica = true ;
} else {
$msg["resp"] = 10;
$msg["text"] = "Debe seleccionar una Provincia.";
echo json_encode($msg);die;
}
if ($distrito != 0) {
$verifica = true ;
} else {
$msg["resp"] = 10;
$msg["text"] = "Debe seleccionar una Distrito.";
echo json_encode($msg);die;
}
if ($via != 0) {
$verifica = true ;
} else {
$msg["resp"] = 10;
$msg["text"] = "Debe seleccionar una Via.";
echo json_encode($msg);die;
}
if ($zona != 0) {
$verifica = true ;
} else {
$msg["resp"] = 10;
$msg["text"] = "Debe seleccionar una Zona.";
echo json_encode($msg);die;
}
if ($txtvia != '') {
$verifica = true ;
} else {
$msg["resp"] = 10;
$msg["text"] = "Debe escribir el Nombre de la Via.";
echo json_encode($msg);die;
}
if ($txtzona != '') {
$verifica = true ;
} else {
$msg["resp"] = 10;
$msg["text"] = "Debe escribir el Nombre de la Zona.";
echo json_encode($msg);die;
}
if ($txtvia != '') {
$verifica = true ;
} else {
$msg["resp"] = 10;
$msg["text"] = "Debe escribir el Nombre de la Referencia.";
echo json_encode($msg);die;
}
/******************************TIEMPO DATE**********************************/
date_default_timezone_set('America/Lima');
$timestamp = time();
$fecha_actual = date("Y-m-d H:i:s", $timestamp);
if($verifica){
$this->session->set_userdata($data);
/***********GUARDADO***********************/
if($id_usuario > 0){
$dataview1["id_usuario"] = $id_usuario;
$dataview1["idDist"] = $this->input->post("cbDistrito");
$dataview1["idProv"] = $this->input->post("cbProvincia");
$dataview1["idDepa"] = $this->input->post("cbDepartamento");
$dataview1["idVia"] = $this->input->post("cbVia");
$dataview1["idZona"] = $this->input->post("cbZona");
$dataview1["nomVia"] = $this->input->post("txtvia");
$dataview1["nomZona"] = $this->input->post("txtzona");
$dataview1["referencia"] = $this->input->post("txtreferencia");
$dataview1["estado"] = $estado;
$dataview1["modificado"] = date("Y-m-d H:i:s");
$this->login->save_direccionusuario($dataview1);
}
if($tipoPersona == '1'){
$dataview["idTipPer"] = $tipoPersona;
$dataview["celular"] = $this->input->post("celular");
$dataview["correo"] = $this->input->post("correo");
$dataview["pass"] = $this->input->post("password1");
}
if($tipoPersona == '2'){
$dataview["idTipPer"] = $tipoPersona;
$dataview["celular"] = $this->input->post("celular");
$dataview["correo"] = $this->input->post("correo");
$dataview["pass"] = $this->input->post("<PASSWORD>");
}
if($tipoPersona == '3'){
$dataview["idTipPer"] = $tipoPersona;
$dataview["celular"] = $this->input->post("celular");
$dataview["correo"] = $this->input->post("correo");
$dataview["pass"] = $this->input->post("password1");
}
if($tipoPersona == '4'){
$dataview["idTipPer"] = $tipoPersona;
$dataview["celular"] = $this->input->post("celular");
$dataview["correo"] = $this->input->post("correo");
$dataview["pass"] = $this->input->post("password1");
}
$dataview["modificado"] = date("Y-m-d H:i:s");
$this->login->update_datosPersonales($dataview);
$idusu = $this->login->buscaIdUsuario($dni);
$id_usuario = $idusu["usu"];
$dataview2["id_usuario"] = $id_usuario;
//$dataview2["pass"] = $this->input->post("tx<PASSWORD>");
$dataview["modificado"] = date("Y-m-d H:i:s");
$msg["resp"] = 100;
$msg["text"] = "En buena Hora registro exitoso.";
echo json_encode($msg);die;
}else{
$msg["resp"] = 10;
$msg["text"] = "Error al actualizar la información.";
echo json_encode($msg);die;
}
}else{
$msg["resp"] = 10;
$msg["text"] = "Error! No eres un humano.";
echo json_encode($msg);die;
}
}
public function olvidoPassword(){
$msg = array();
$data = $this->login->Get_user2($this->input->post("userLogin"));
/*********************************************/
$id_usuario = $data['id_usuario'];
$nroDocumento = $data['nroDocumento'];
$from_mail = $data['correo'];
$email = $data['correo'];
$pass = $<PASSWORD>['<PASSWORD>'];
$txtnombres = $data['nombre'];
$txtapePaterno = $data['apPaterno'];
$txtapeMaterno = $data['apMaterno'];
$from_name = $txtapePaterno.' '.$txtapeMaterno.' ,'.$txtnombres;
/**********************************************************/
if($data){
$mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Host = "mail.ugel03.gob.pe";
$mail->Port = 25;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = false;
$mail->Username = "consult<EMAIL>";
$mail->Password = "<PASSWORD>";
$mail->From = $from_mail;
$mail->FromName = $from_name;
if(!$mail->Send()) {
$data["message"] = "Error en el envío: " . $mail->ErrorInfo;
$error = 1;
} else {
$data["message"] = $txtnombres." ¡En buena hora! datos registrados correctamente , se ha enviado credenciales de acceso a Mesa de Partes Virtual. ";
$error = 0;
}
$Pass = $pass;
$from_mail = '<EMAIL>' ;
$mail->From = $from_mail;
$mail->FromName = $from_name;
$mail->AddCC((string)$this->input->post("userLogin"),"Usuario");
$mail->Subject = '[UGEL03] Envío de contraseña de Mesa de Partes Virtual';
$mail->Body = '<b>UNIDAD DE GESTION EDUCATIVA LOCAL 03 </b><br>
Estimado(a) <b>'.$from_name.'</b><br>
A través de este correo damos a conocer su usuario y contraseña de ingreso al sistema :<br>
<br>Usuario : '.trim($email).'<br>
Contraseña : '.$Pass.'<br>
<br>Puede ingresar al Sistema a través del siguiente enlace :<a href="http://sistemas01.ugel03.gob.pe/pruebamdp2/"> Mesa de Partes Virtual </a> <br>
Nota: Recuerde que las mayúsculas y minúsculas afectan en la clave presente.<br>
<br> Atte:<br><br><br><b>UGEL03 </b><br>
Telef : (01) 6155800 Anexo: 13018 Informes <br> Atención de 8:30am a 1:00pm y 2:00 a 4:30pm<br> UGEL 03 - Av. Iquitos 918, La Victoria';
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
if(!$mail->Send()) {
$data["message"] = "Error en el envío: " . $mail->ErrorInfo;
$error = 1;
} else {
$data["message"] = $txtnombres." ¡En buena hora! datos registrados correctamente , el sistema enviara las credenciales de acceso a su correo electronico ";
$error = 0;
}
$data = array(
"msg"=>$data["message"],
"error" => $error
);
$msg["resp"] = 10;
$msg["text"] = "¡En buena hora! El sistema enviará las credenciales de acceso a su correo electronico";
echo json_encode($msg);
}else{
$msg["resp"] = 10;
$msg["text"] = "Correo no registrado";
echo json_encode($msg);
}
}
public function change_password()
{
$msg = array();
$data['dni'] = $this->session->userdata("nroDoc");
$data['email'] = $this->session->userdata("user");
$data['passaActual'] = $this->input->post("pass<PASSWORD>");
if($this->homeAdjudicaciones->Get_userChangePass($data)){
$this->session->set_userdata(array("user"=>$data['email']));
$data = array();
$data['pass'] = $this->input->post("<PASSWORD>");
$data['nroDoc'] = $this->session->userdata("nroDoc");
$data['email'] = $this->session->userdata("user");
if($this->homeAdjudicaciones->Change_PasswordUser($data)){
$msg["resp"] = 100;
$msg["text"] = "La contraseña se cambio correctamente.";
}
else{
$msg["resp"] = 0;
$msg["text"] = "Ha ocurrido un error.";
}
}
else{
$msg["resp"] = 10;
$msg["text"] = "Ingrese correctamente su contraseña actual.";
}
echo json_encode($msg);
}
public function logout()
{
$this->session->sess_destroy();
redirect("homeAdjudicaciones/index");
}
}
<file_sep>/app/views/tramite/formulario.php
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Boletas</title>
<style type="text/css">
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
table{
width:100%;
font-size:12px;
font-family:Arial;
font-style:italic;
}
table tr td{
padding-left:2px;
}
table.lineheight tr td{
padding-top:1px;
padding-bottom:1px;
}
.wrapper{
}
.container{
width:760px;
font-size:12px;
font-family:arial;
margin:auto;
}
.boleta, .section{
background:#999;
text-align:center;
font-size:14px;
padding: 0px 0 0px 0;
font-style:italic;
font-weight:700;
}
.section{
padding: 5px 0 5px 0;
font-size:12px;
}
table tr.section2 td{
padding-left:2px;
padding-right:2px;
}
td.center{
text-align:center;
vertical-align: middle;
}
.bg{
background:#999;
}
.negrita{
font-weight:700;
}
.textleft{
text-align:left;
padding-left:2px;
}
.l-right{
border-right:1px solid #000;
}
.l-left{
border-left:1px solid #000;
}
.l-bottom{
border-bottom:1px solid #000;
}
.l-border{
border-top:1px solid #000;
border-right:1px solid #000;
border-left:1px solid #000;
border-bottom:1px solid #000;
}
.l-top{
border-top:1px solid #000;
}
.cabimg{
margin:0px 0 5px 0;
}
.vtop{
vertical-align:top;
}
.aright{
text-align:right;
padding-right:2px;
}
.aleft{
text-align:left;
}
.normal{
font-weight:normal;
}
</style>
</head>
<body style="margin-top:0px">
<?php
$ctrl = 1;
$copies = 2;
foreach($datos as $data){
$remtotal = 0;
$desctotal = 0;
$t=1;
for($t=1;$t<=$copies;$t++){
?>
<div class="container">
<div class="cabimg">
<img src="<?php echo site_resource('admin') ?>/img/logo-ugel03-RRHH.jpg" alt="" title="">
</div>
<div>
<span class="negrita"><b>RUC</b>:</span> 20331304736
</div>
<div class="wrapper">
<table class="tb-list" border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="3" class="boleta center bg l-border"><b>BOLETA DE PAGO</b></td>
</tr>
<tr height="10" >
<td class="l-left" width="40" height="10" style=" vertical-align:middle"><b>MES</b>:</td>
<td class="textleft" style=" vertical-align:middle"><?php echo strtoupper($mes) ?></td>
<td class="l-right"></td>
</tr>
<tr height="20">
<td colspan="3" class="center bg negrita l-border" ><b>DATOS DEL TRABAJADOR</b></td>
</tr>
<tr>
<td colspan="3" class="l-left l-right">
<table class="tb-list lineheight" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="negrita" width="170"><b>DNI</b></td>
<td width="10">:</td>
<td><?php echo $data["dni"]?></td>
</tr>
<tr>
<td class="negrita"><b>APELLIDOS Y NOMBRES</b></td>
<td>:</td>
<td><?php echo $data["nombre"]?></td>
</tr>
<tr>
<td class="negrita"><b>MODALIDAD CONTRATO</b></td>
<td>:</td>
<td><?php echo $data["modalidad"]?></td>
</tr>
<tr>
<td class="negrita"><b>FECHA INGRESO</b></td>
<td>:</td>
<td><?php echo $data["fingreso"]?></td>
</tr>
<tr>
<td class="negrita"><b>REG. PENS.</b></td>
<td>:</td>
<td class="normal"><?php echo $data["pension"]?>
<?php
if($data["pension"] == "AFP"){
echo($data["pensionnombre"]." "." <b>CUSSP</b>: ".$data["cussp"]);
}
?>
</td>
</tr>
<tr>
<td class="negrita"><b>AUTOGENERADO ESSALUD</b></td>
<td>:</td>
<td><?php echo $data["autoessalud"]?></td>
</tr>
<tr>
<td class="negrita"><b>CARGO</b></td>
<td>:</td>
<td><?php echo $data["cargo"]?></td>
</tr>
<tr>
<td class="negrita"><b>NUMERO CUENTA</b></td>
<td>:</td>
<td><?php echo $data["nrocuenta"]?></td>
</tr>
</table>
</td>
</tr>
</table>
<table class="tb-list" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="center bg negrita l-top l-right l-left l-bottom" ><b>REMUNERACIONES</b></td>
<td class="center bg negrita l-top l-bottom" ><b>DESCUENTOS</b></td>
<td class="center bg negrita l-top l-left l-right l-bottom" ><b>APORTACIONES DEL EMPLEADOR</b></td>
</tr>
<tr>
<td class="vtop l-left l-right">
<table class="tb-list" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="65">D.L. 1057</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["dl"],2)?></td>
</tr>
<?php if((float)$data["reintegro"]> 0 or (float)$data["reitegroxerror"]> 0 ){?>
<tr>
<td>Reintegro</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["reintegro"] + $data["reitegroxerror"],2)?></td>
</tr>
<?php } ?>
<?php if((float)$data["aguinaldo"]> 0 ){?>
<tr>
<td>Aguinaldo</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["aguinaldo"],2);
?></td>
</tr>
<?php } ?>
<?php if($data["vactrunca"]>0){?>
<tr>
<td>Vac. Trunca</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["vactrunca"],2);
?></td>
</tr>
<?php }?>
</table>
</td>
<?php $remtotal = $data["dl"] + $data["reintegro"] + $data["aguinaldo"]+$data["reitegroxerror"]+$data["vactrunca"];
$ctrl_pension = true;
if($data["pension"] == "ONP"){
$ctrl_pension = false;
}
?>
<td class="vtop " >
<table class="tb-list" border="0" cellpadding="0" cellspacing="0">
<?php if($ctrl_pension){?>
<tr>
<td width="160">SPP - Aporte AFP</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["aporteafp"],2)?>
</td>
</tr>
<tr>
<td>SPP - Prima Seguro AFP</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["seguroafp"],2)?></td>
</tr>
<tr>
<td>SPP - Comisión AFP</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["comisionafp"],2)?></td>
</tr>
<?php } else{?>
<tr>
<td>ONP</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["onp"],2)?></td>
</tr>
<?php }?>
<tr>
<td>Faltas y Tardanzas</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["ft"],2)?></td>
</tr>
<tr>
<td>Descuento de 4ta. Categoría</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["4tacategoria"],2)?></td>
</tr>
<tr>
<td>Otros Descuentos</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["otrosdesc"],2);
$desctotal = $data["aporteafp"]+$data["seguroafp"]+$data["comisionafp"]+$data["onp"]+$data["ft"]+$data["4tacategoria"]+$data["otrosdesc"];
?></td>
</tr>
<?php if($ctrl_pension == false){?>
<tr>
<td width="160"> </td>
<td> </td>
<td class="aright"><?php echo(" ")?></td>
</tr>
<tr>
<td width="160"> </td>
<td> </td>
<td class="aright"><?php echo(" ")?></td>
</tr>
<?php }?>
</table>
</td>
<td class="vtop l-left l-right" >
<table class="tb-list" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="80">ESSALUD</td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($data["essalud"],2)?></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="l-left l-top l-bottom l-right">
<table class="tb-list" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="65" class="negrita center"><b>TOTAL</b></td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($remtotal,2)?></td>
</tr>
</table>
</td>
<td class=" l-bottom l-top">
<table class="tb-list" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="180" class="negrita center"><b>TOTAL</b></td>
<td>:</td>
<td class="aright">S/. <?php echo number_format($desctotal,2)?></td>
</tr>
</table>
</td>
<td class=" l-left l-bottom l-top negrita center bg l-right">
<b>RESUMEN</b>
</td>
</tr>
<tr>
<td>
</td>
<td class="">
</td>
<td class="l-left" style="padding:0">
<table class="tb-list" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="" class="negrita l-bottom"><b>TOTAL REMUNERACIONES</b></td>
<td class="l-bottom">:</td>
<td class="aright l-right l-bottom">S/. <?php echo number_format($remtotal,2)?></td>
</tr>
<tr>
<td width="" class="negrita l-bottom"><b>TOTAL DESCUENTOS</b></td>
<td class="l-bottom">:</td>
<td class="aright l-right l-bottom">S/. <?php echo number_format($desctotal,2)?></td>
</tr>
<tr>
<td width="" class="negrita l-bottom"><b>REMUNERACION NETA</b></td>
<td class="l-bottom">:</td>
<td class="aright l-bottom l-right">S/. <?php echo number_format($data["totliquido"],2)?></td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div style="width:100%; position:relative; padding-top:-60px">
<div style=" float:left; width:238px; position:absolute">
<img src="<?php echo site_resource('admin') ?>/img/sello.png" alt="" title="">
</div>
<div style=" float:right;width:210px; left:200px;top:80px; padding-top:110px">
<div style="border-top:#000 1px solid; text-align:center">
FIRMA DEL TRABAJADOR
</div>
</div>
</div>
</div>
<?php
if($t%2 != 0){ ?>
<div style="border-bottom:2px dotted #000; height:2px; margin-top:8px">
</div>
<?php
}
?>
<br />
<?php
}
$ctrl++;
}?>
</body>
</html>
<file_sep>/app/views/tramite/home.php
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<!--
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MESA DE PARTES VIRTUAL</title>
<script src="<?php echo site_resource('admin') ?>/js/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="<?php echo site_resource('admin') ?>/js/custominputfile.min-es.js"></script>
<script src="<?php echo site_resource('admin') ?>/js/jquery.validate.min.js"></script>
<script src="<?php echo site_resource('admin') ?>/js/messages_es.js"></script>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="<?php echo site_resource('admin') ?>/js/css/custominputfile.min.css" type="text/css" />
<link rel="stylesheet" href="<?php echo site_resource('admin') ?>/css/style.css" type="text/css" />
<script src='https://www.google.com/recaptcha/api.js' async defer></script>
<link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script>
<!-- Nuevo -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
<!-- -->
<script>
/**AP 15092020 Validacion de */
Filevalidation = (a) => {
const fi = document.getElementById('requisito'+a);
// Check if any file is selected.
if (fi.files.length > 0) {
for ( i = 0; i <= fi.files.length - 1; i++) {
const fsize = fi.files.item(i).size;
const ftype= fi.files.item(i).type;
const ftmp_mane = fi.files.item(i).tmp_name;
const file = Math.round((fsize / 1024));
// The size of the file.
if (ftype === 'application/pdf') {
if (file >= 8192) {
/* if (file >= 2048) { */
alert( "Archivo demasiado grande, seleccione un archivo de menos de 8 MB");
fi.value='';
}else{
var input = fi;
var reader = new FileReader();
reader.readAsBinaryString(input.files[0]);
reader.onloadend = function(){
var count = reader.result.match(/\/Type[\s]*\/Page[^s]/g).length;
// console.log('Number of Pages:',count );
document.getElementById('size'+a).innerHTML = '| tamaño de archivo <b>'
+ file + '</b> KB' + ' | número de pagina(s) '+count;
$("#menu_item_id"+a).val(count);
var sum = 0;
$("input[name='menu_item_id[]']").each( function() {
sum += +this.value;
// alert(sum);
$("#txtfolio").val(sum);
$("#txtfolio_").val(sum);
});
// $("#txtfolio").val(count);
}
}
}else{
alert('Solo se permite subir archivos PDFs');
fi.value='';
}
}
}
}
function soloNumeros(e)
{
var key = window.Event ? e.which : e.keyCode
return ((key >= 48 && key <= 57) || (key==8))
}
function myFunction(){
$.ajax({
url:"<?php echo site_url("tramite/consultadni")?>",
data:{id:$("#txtdoc").val()},
dataType:"json",
type:"POST",
success:function(data){
$("#txtnombre").val("");
$("#txtnombre").val(data.nombres);
$("#txtapepat").val("");
$("#txtapepat").val(data.apellido_paterno);
$("#txtapemat").val("");
$("#txtapemat").val(data.apellido_materno);
}
});
}
function myFunction2(){
$.ajax({
url:"<?php echo site_url("tramite/consultaruc")?>",
data:{id:$("#txtdoc").val()},
dataType:"json",
type:"POST",
success:function(data){
$("#txtrazonsocial").val("");
$("#txtrazonsocial").val(data.razonsocial);
$("#txtrazonsocialhid").val(data.razonsocial);
}
});
}
function getvalcboie(){
var valuecbo = $("#txtie").find('option:selected').text();
$("#txtie_val").val(valuecbo);
}
/*genera requisito */
/*nuevo*/
function generaRequisito(idservicio) {
//alert(idservicio);
$("#ulfile li").remove();
items_requisito = "";
$.ajax({
url: "<?php echo site_url("tramite/requisitos")?>",
data: {id: idservicio},
dataType: "json",
type: "POST",
success: function (data) {
var ctrl = 0;
$.each(data.requisitos, function (index, items) {
ctrl = ctrl + 1;
items_requisito = items_requisito + '<li><label>' + items.descripcion + ':</label><input type="file" onchange="Filevalidation(' + ctrl + ')" name="afr-file[' + ctrl + ']" class="' + ((items.requerido === '1') ? 'required' : '') + '" id="requisito' + ctrl + '"> <span id="size' + ctrl + '"> </span> <input type="hidden" id="menu_item_id' + ctrl + '" value="" name="menu_item_id[]"></li>';
})
$("#ulfile").append(items_requisito);
$('#solPedido').attr("disabled", false);
}
});
}
/* valida requisitos */
function validaRequisitos(cbo){
switch(cbo) {
case 1:
/* NUEVO */
var valuecbo2 = $("#cbservicio").find('option:selected').text();
$("#txtpedido_val").val(valuecbo2);
var cbo = $("[name='cbservicio']").val();
/* */
break;
case 2:
var cbo = $("[name='cbservicio_sub']").val();
break;
case 3:
var cbo = $("[name='cbservicio_sub2']").val();
break;
default:
// code block
}
$.ajax({
url:"<?php echo site_url("tramite/getUltimoNivel")?>",
data:{id:cbo},
dataType:"json",
type:"POST",
success:function(data){
var ctrl = 0;
$.each(data.nivel,function(index, items){
if(items.ultimoNivel==1){
generaRequisito(cbo);
}
})
}
});
}
</script>
<script type="text/javascript">
var cbo;
var dependencia = [];
<?php
foreach($solicitud as $item){
?>
dependencia[<?php echo $item["id_tippedido"]?>] = "<?php echo $item["referencia"]?>";
<?php
}
?>
$(window).resize(function(){
$('#afr-cmessage').css({
left: ($(window).width() - $('#afr-cmessage').outerWidth(true))/2,
top: ($(window).height() - $('#afr-cmessage').outerHeight(true))/2
});
});
$(function(){
$("#afr-btnclose").click(function(){
$("#afr-cmessage").fadeOut(500,function(){
$("#afr-overlay").fadeOut(700);
});
});
$('#afr-cmessage').css({
left: ($(window).outerWidth() - $('#afr-cmessage').outerWidth(true))/2,
top: ($(window).outerHeight() - $('#afr-cmessage').outerHeight(true))/2
});
setTimeout(function(){
$("#afr-msg").fadeOut(2000);
},1800);
var validar = $("#afr-frmfut").validate({
errorElement:"span",
errorClass:"afr-error",
errorPlacement: function(error, element){},
submitHandler:function(forms){
$('.afr-btn').attr("disabled","disabled");
forms.submit();
}
})
$('#level1_tramite').hide();
$('#level2_tramite').hide();
/**Nivel 2*/
$("#cbservicio_sub").change(function() {
var idservicioNivel2 = $(this).val();
$("#cbservicio_sub option:selected").each(function() {
$.post("index.php/tramite/getNivelPedidoLev2", {id2:idservicioNivel2, nivel:'2'
}, function(data) {
if(data){
$("#cbservicio_sub2").html(data);
$("#level2_tramite").show();
}else{
$('#level2_tramite').hide();
}
});
});
})
$("#cbservicio").change(function(){
idservicio = $(this).val();
/*********************************/
$("#cbservicio option:selected").each(function() {
$('#level2_tramite').hide();
if(idservicio==21 || idservicio==22 ){
$.post("index.php/tramite/getNivelPedido", {id: idservicio , nivel:'1'
}, function(data) {
$("#cbservicio_sub").html(data);
$("#level1_tramite").show();
});
}else{
$('#level1_tramite').hide();
}
});
/*******************************************/
$(".fundamentosBuzon").hide();
switch(idservicio){
case "1" :$("#informacionAdicional").text("Indicar que es para abono de sus haberes");break;
case "2" :$("#informacionAdicional").text("Indicar el período qué desea que se emita (1973 a marzo 1998) y/o (abril 1998 a la actualidad). indicar las instituciones educativas en las que laboró, si son cesantes desde que fecha");break;
case "3" :$("#informacionAdicional").text("Indicar el uso de la cuenta ; para trámites personales o concurso público");break;
case "4" :$("#informacionAdicional").text("Indicar ugel de destino");break;
case "5" :$("#informacionAdicional").text("Para trámites personales, si es contratado o nombrado");break;
case "6" :$("#informacionAdicional").text("Indicar el número y el año de la emisión, si es resolución directoral o jefatural otros");break;
case "8" :$("#informacionAdicional").text("Indicar la institución educativa en la que labora");break;
case "9" :$("#informacionAdicional").text("Indicar el número de expediente a la cual se está haciendo el silencio administrativo");break;
case "10" :
$("#nro_cuenta").text("00000-282014");
$("#informacionAdicional").text("Escriba aquí fundamento de pedido, Nombre Colegio, Distrito , Grados , Años , Sección (opcional), Especificar si I.E se encuentra activa o inactiva.");
break;
case "11" :$("#informacionAdicional").text("Indicar el tipo de retención");break;
case "12" :$("#informacionAdicional").text("Indicar el mes y el año a reprogramar");break;
case "13" :$("#informacionAdicional").text("Indicar consulta ");break;
case "16" : $(".fundamentosBuzon").show(); $("#informacionAdicional").text("Detalle su consulta ,sea preciso y consiso.");
break;
case "52" : $(".fundamentosBuzon").show(); $("#informacionAdicional").text("Especificar: causal (interés personal o unidad familiar ) y tipo (1,2 o 3)");
break;
case "51" : $(".fundamentosBuzon").show(); $("#informacionAdicional").text("");
break;
case "21" : /*alert("goce");*/
break;
default:
$("#informacionAdicional").text("");
break;
}
$("#afr-dependencia").text(dependencia[$(this).val()]);
$("#txtdependencia").val(dependencia[$(this).val()]);
$("#ulfile li").remove();
items_requisito = "";
// combodinamico(idservicio);
/********************Requisitos de tramite*/
/*
$.ajax({
url:"<?php echo site_url("tramite/requisitos")?>",
data:{id:idservicio},
dataType:"json",
type:"POST",
success:function(data){
var ctrl = 0;
$.each(data.requisitos,function(index, items){
ctrl = ctrl + 1;
items_requisito = items_requisito + '<li><label>' + items.descripcion + ':</label><input type="file" onchange="Filevalidation('+ctrl+')" name="afr-file[' + ctrl + ']" class="required" id="requisito' + ctrl + '"> <span id="size' + ctrl + '"> </span> <input type="hidden" id="menu_item_id'+ctrl+'" value="" name="menu_item_id[]"></li>';
})
$("#ulfile").append(items_requisito);
}
});*/
/*********************************************************/
});
})
function GeneraValidacion(){
$('#requisito' + ctrl).rules('add', {
required: true
});
}
function countChar(val) {
var len = val.value.length;
if (len >= 250) {
val.value = val.value.substring(0, 250);
} else {
$('#charNum').text(250 - len);
}
};
$(function(){
$("#cboTipoPersona").change(function(){
$("#cboTipoPersona option:selected").each(function() {
TipoPersona = $('#cboTipoPersona').val();
$.post("<?php echo(site_url("tramite/gettipodoc"))?>", {
TipoPersona : TipoPersona
}, function(data) {
$("#coTipoDocumento").html(data);
});
});
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if(valueSelected==1 /*|| valueSelected==3 */ || valueSelected=='' ){
$("#txtdoc").prop("disabled",false);
$("#divRazon").css("display", "none");
$("#divNombres").css("display", "");
$("#txtapepat").addClass("required");
$("#txtnombre").addClass("required");
$("#divRazon").removeClass("required");
$("#txtnombreRazon").val("--");
$("#txtnombres").val("");
$("#txtapePaterno").val("");
$("#txtapeMaterno").val("");
$('#lblNroDoc').text("Número de Documento");
$("#btnbsuquedadni").show();
$("#btnbsuquedaruc").hide();
$("#txtdoc").attr('maxlength', 9);
$("#txtdoc").val("");
if(valueSelected==''){
$("#coTipoDocumento").val(0);
}else{
$("#coTipoDocumento").val(2);
}
}else{
$("#txtapepat").removeClass("required");
$("#txtnombre").removeClass("required");
$("#divRazon").addClass("required");
$("#btnbsuquedadni").hide();
$("#btnbsuquedaruc").show();
$("#txtdoc").attr('maxlength', 11);
$("#txtdoc").val("");
if(valueSelected==4){
$('#nameEntidad').text("Nombre de Institución Educativa");
$('#lblNroDoc').text("Cod Local y/o Modular");
$("#txtnombreRazon").attr("placeholder", "Ingrese nombres de la Institución");
// $("#txtdoc").prop("disabled",true);
$("#txtapepat").removeClass("required");
$("#txtnombre").removeClass("required");
$("#divRazon").removeClass("required");
}else{
$("#txtdoc").prop("disabled",false);
$('#nameEntidad').text("Razón Social");
$('#lblNroDoc').text("Número de RUC");
$("#txtnombreRazon").attr("placeholder", "Ingrese nombre de la razón social");
}
$("#divRazon").css("display", "");
$("#divNombres").css("display", "none");
$("#txtnombreRazon").val("");
$("#txtnombres").val("--");
$("#txtapePaterno").val("--");
$("#txtapeMaterno").val("--");
$("#coTipoDocumento").val(3);
}
});
})
/* NUEVO */
$(document).ready(function () {
$('.ie-select2').select2({
ajax: {
url: '<?= site_url("tramite/institucion_educativa")?>',
type: 'post',
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id: item.PersonaJuridicaId,
text: item.Descripcion
}
})
};
},
cache: true
},
placeholder: 'SELECCIONAR IE',
minimumInputLength: 3,
language: {
inputTooShort: function () {
return 'Ingresa como mínimo 3 caracteres de la Institución Educativa...';
},
noResults: function () {
return 'No se encontraron resultados';
},
searching: function () {
return 'Buscando la institución Educativa..';
}
}
});
});
/* */
/* NUEVO */
$(document).ready(function () {
$('.pedido-select2').select2({
ajax: {
url: '<?= site_url("tramite/tipo_pedido")?>',
type: 'post',
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id: item.id_tippedido,
text: item.nombre
}
})
};
},
cache: true
},
placeholder: 'SELECCIONAR SOLICITUD',
minimumInputLength: 3,
language: {
inputTooShort: function () {
return 'Ingresa como mínimo 3 caracteres de la Solicitud...';
},
noResults: function () {
return 'No se encontraron resultados';
},
searching: function () {
return 'Buscando la solicitud..';
}
}
});
});
/* */
</script>
<style>
.box {
text-align:center;
vertical-align:middle;
display:table-cell;
position: relative;
top: 50%;
left: 10%;
transform: translate(0%, 0%);
}
.box select {
background-color: #c3cdd280;
color: #1c516f;
padding: 4px;
width: 100%;
border: none;
font-size: 15px;/*
box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);*/
-webkit-appearance: button;
appearance: button;
outline: none;
}
.box::before {
content: "\f13a";
font-family: FontAwesome;
position: absolute;
top: 0;
right:0;
left:80%;
width: 20%;
height: 100%;
text-align: center;
font-size: 18px;
line-height: 30px;
color: rgba(255, 255, 255, 0.5);
background-color: #c3c4c9;
pointer-events: none;
}
.box:hover::before {
color: rgba(255, 255, 255, 0.6);
background-color: rgba(255, 255, 255, 0.2);
}
.box select option {
padding: 30px;
}
.solPedido {
background-color: #008CBA;
border: none;
color: white;
padding: 15px 62px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 4px;
transition-duration: 0.4s;
margin-left: 365px;
}
.solPedido:hover {
background-color: #4CAF50;
box-shadow: 0 6px 8px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
color: white;
}
.solPedido:disabled {
border: 1px solid #999999;
background-color: #cccccc;
color: #666666;
}
.solPedido span:after {
content: '\00bb';
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.5s;
}
select.form-control:not([size]):not([multiple]) {
height: calc(1.7rem) !important;
}
/* NUEVO */
.select2-results__option {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji" !important;
text-transform: uppercase !important;
font-size: 12px !important;
}
/* */
</style>
</head>
<body>
<div id="afr-wrapper">
<div id="afr-overlay">
</div>
<div id="afr-toph">
<div id="afr-menu">
<div id="afr-date">
Lima, <?php echo datesmart(date("Y-m-d"),'{day} {month:name} {year}') ?>
</div>
</div>
</div>
<div id="afr-cheader">
<div id="afr-navmenu">
<div id="afr-header">
<div id="afr-logo">
<img style="width:450px;margin-right:300px" src="<?php echo site_resource('admin') ?>/img/logo-ugel03.jpg" >
<img style="width:180px;padding-left:10px ; margin-bottom:9px" src="<?php echo site_resource('admin') ?>/img/LOGO UGEL 03-01 (1).png" >
<!-- <div id="afr-rm">
RM N° 0445-2012-ED
</div>-->
</div>
</div>
</div>
</div>
<div id="afr-bgcontaniner">
<div id="afr-container">
<div id="afr-contform">
<?php if(@$this->session->userdata("msg")!=""){ ?>
<div id="afr-msg" class="afr-msg <?php echo((@$this->session->userdata("error")==1)? "afr-msgerror":"")?>">
<?php echo @$this->session->userdata("msg");
$this->session->sess_destroy();
?>
</div>
<?php }?>
<form id="afr-frmfut" name="afr-frmfut" action="<?php echo(site_url("tramite/enviar"))?>" method="post" enctype="multipart/form-data">
<input type="hidden" name="txtdependencia" id="txtdependencia">
<!-- <table style="width:100%; background-color: #f9cfcf;">
<tr>
<th>Descarga en formato digital <a target="_blank" href="http://www.ugel03.gob.pe/web-ugel03/wp-content/uploads/2016/06/FUT.pdf"> FUT </a> </th>
</tr>
</table>
-->
<table id="afr-tblmain" border="0" cellpadding="0" cellspacing="0">
<tr class="">
<td style="color:white;background:#a6a6b9;" class="borde-down">
<b> MESA DE PARTES VIRTUAL</b></br>
FORMULARIO ÚNICO DE TRAMITE (FUT) - RM N° 0445-2012-ED
</td>
<!--
<td rowspan="4" class="borde-down border-left" style="width:200px; color:black" id="afr-tdcosto">
<img src="<?php echo site_resource('admin') ?>/img/logo-bn.png" border="0" >
<div>Banco de la Nación</div>
<div>Cta. Cte. N°: <span id="nro_cuenta">0000-281905</span></div>
<div>COSTO:</div><div id="afr-costo" style="font-weight:700;font-size:20px" >S/. <span>0.00</span></div>
<div>
<select id="cbcosto" name="cbcosto" class="required">
<option value="">-- Seleccione --</option>
</select>
</div>
</td>-->
</tr>
<tr class="textleft afr-tdsection">
<td class="borde-down spaceleft">
I.- Tramite:
<span>
<div class="box" style="background-color:white !important; width:650px;" >
<input id="txtpedido_val" name="txtpedido_val" type="hidden" value="">
<!-- NUEVO -->
<select onchange='validaRequisitos(1)'
class='form-control pedido-select2' id='cbservicio'
name='cbservicio' required></select>
<!-- -->
</div>
</span>
<!--
<span>
<div class="box" style="background-color:white !important; width:650px;" >
<select style="background-color:white !important" id="cbservicio" onchange="validaRequisitos(1)" name="cbservicio" required>
<option value="">-- Seleccione solicitud --</option>
<?php
foreach($solicitud as $item){
?>
<option value="<?php echo $item["id_tippedido"]?>"><?php echo $item["nombre"]?></option>
<?php
}
?>
</select>
</div>
</span>
-->
</td>
</tr>
<tr id="level1_tramite" name="level1_tramite" class="textleft afr-tdsection">
<div style="padding-lef:260px" > </div>
<td class="borde-down spaceleft">
<h style="color:#0077b9" ><!--I.- Resumen de su pedido:-->I.- Tramite:</h>
<span>
<div class="box" style="background-color:white !important; width:650px;" >
<select style="background-color:white !important" onchange="validaRequisitos(2)" id="cbservicio_sub" name="cbservicio_sub" >
<option value=""></option>
<!-- <?php
foreach($solicitud as $item){
?>
<option value="<?php echo $item["id_tippedido"]?>"><?php echo $item["nombre"]?></option>
<?php
}
?>-->
</select>
</div>
</span>
</td>
</tr>
<tr id="level2_tramite" name="level2_tramite" class="textleft afr-tdsection">
<div style="padding-lef:260px" > </div>
<td class="borde-down spaceleft">
<h style="color:#0077b9" ><!--I.- Resumen de su pedido:-->I.- Tramite:</h>
<span>
<div class="box" style="background-color:white !important; width:650px;" >
<select style="background-color:white !important" onchange="validaRequisitos(3)" id="cbservicio_sub2" name="cbservicio_sub2" >
<option value=""></option>
</select>
</div>
</span>
</td>
</tr>
<tr style="display:none" class="textleft">
<td class="borde-down">
<textarea id="txtresumen" name="txtresumen" placeholder="Detalle su solicitud" class="afr-textarea required" ></textarea>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="borde-down spaceleft">
II. Dependencia o autoridad a quien se dirige: <span id="afr-dependencia" style="font-weight:700">DIRECTOR UGEL 03</span>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="borde-down spaceleft">
III. Datos del solicitante:
</td>
</tr>
<!--
<tr class="textleft">
<td class="spaceleft">
Persona Natural:
<span>
<div class="box" style="width:200px;margin-botton:20px" >
<select>
<option value="1">Persona Natural</option>
<option value="2">Persona Juridica</option>
</select>
</div>
</span>
Tipo Documento:
<span>
<div class="box" style="width:200px;margin-botton:20px" >
<select>
<option value="1">DNI</option>
<option value="2">RUC</option>
</select>
</div>
</span>
<label>DNI N° y/o RUC:</label><input class="textborder required number" style="width:150px; height:24px" type="text" onkeypress="return soloNumeros(event);" maxlength="11" name="txtdoc" id="txtdoc" >
</td>
</tr>
-->
<tr>
<td colspan="2">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr style="height:60px;">
<td style="width:325px; " class="spaceleft">
Tipo Persona*:
<span>
<div class="box" style="width:200px;margin-botton:20px" >
<?php echo "<select class='form-control required' id='cboTipoPersona' name='cboTipoPersona' required='required'>";
if (count($tipopersona)) {
echo "<option value=''>[--Seleccione--]</option>";
foreach ($tipopersona as $list) {
echo "<option value='". $list['id'] . "'>" . $list['descripcion'] . "</option>";
}
}
echo "</select>";
?>
</div>
</span>
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
Tipo Documento*:
<span>
<div class="box" style="width:200px;margin-botton:20px" >
<select class="form-control required" required="required" id="coTipoDocumento" name="coTipoDocumento" >
<option value="0">[--Seleccione--]</option>
</select>
</div>
</span>
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
<label for="numDocide" id="lblNroDoc" name="lblNroDoc" class="control-label required">Número de Documento:<b class="campoRequerido" >*</b></label>
<input class="textborder required number" style="width:120px; height:24px" value="" type="text" onkeypress="return soloNumeros(event);" maxlength="11" name="txtdoc" id="txtdoc" >
<button id="btnbsuquedadni" name="btnbsuquedadni" onclick="myFunction()" style="background-color: #252371;color: white;height: 28px;display:none " ><i class="fa fa-search"></i></button>
<button id="btnbsuquedaruc" name="btnbsuquedaruc" onclick="myFunction2()" style="background-color: #252371;color: white;height: 28px;display:none " ><i class="fa fa-search"></i></button>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2">
<div class="row" id="divNombres" name="divNombres">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr style="height:60px;">
<td style="width:350px; " class="spaceleft">
<label>Apellido Paterno*:</label><input class="textborder" style="width:213px; height:24px" type="text" name="txtapepat" id="txtapepat">
</td>
<td style="width:350px; padding-left:10px;" class="spaceleft">
<label>Apellido Materno :</label><input class="textborder" value=" " style="width:213px; height:24px" type="text" name="txtapemat" id="txtapemat">
</td>
<td style="width:260px; padding-left:10px;" class="spaceleft">
<label>Nombres *:</label><input class="textborder" type="text" value=" " style="width:180px; height:24px" name="txtnombre" id="txtnombre">
</td>
</tr>
</table>
</div>
<div class="row" id="divRazon" name="divRazon" style="display:none;">
<label style="padding-left:30px"> Razón Social*:</label><input disabled value=" " class="textborder" style="width:800px; height:24px" type="text" name="txtrazonsocial" id="txtrazonsocial">
</div>
<input type="hidden" value="" name="txtrazonsocialhid" id="txtrazonsocialhid">
</td>
</tr>
<!--
<tr class="textleft">
<td class="spaceleft">
Persona Jurídica:
</td>
</tr>
<tr class="textleft">
<td colspan="2" class="spaceleft">
<label>Razón Social*:</label><input class="textborder" style="width:833px; height:24px" type="text" name="txtrazonsocial" id="txtrazonsocial">
</td>
</tr>
<tr class="textleft">
<td class="spaceleft">
Tipo de Documento:
</td>
</tr>-->
<tr>
<td colspan="2">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr style="height:60px;">
<!-- <td style="width:272px; " class="spaceleft">
<label>DNI N° y/o RUC:</label><input class="textborder required number" style="width:150px; height:24px" type="text" onkeypress="return soloNumeros(event);" maxlength="11" name="txtdoc" id="txtdoc" >
</td> -->
<td colspan="2" style="width:600px; padding-left:10px;" class="spaceleft">
<!-- <label>IE:</label>
<input class="textborder" style="width:213px; height:24px" type="text" name="txtie" id="txtie"> -->
<label>IE:</label>
<span>
<div class="box" style="width:500px;vertical-align:center:middle" >
<input id="txtie_val" name="txtie_val" type="hidden" value="">
<!-- <select onchange='getvalcboie()' class='form-control required' id='txtie' name='txtie' required='required'> -->
<!-- <?php //echo "<select onchange='getvalcboie()' class='form-control ' id='txtie' name='txtie' >";
//if (count($ie)) {
//echo "<option selected value='0'>[--Seleccione--]</option>";
//foreach ($ie as $list) {
//echo "<option value='".trim($list['PersonaJuridicaId'])."'>" . $list['Descripcion'] . "</option>";
//}
//}
//echo "</select>";
?> -->
<!-- NUEVO -->
<select onchange='getvalcboie()'
class='form-control ie-select2' id='txtie'
name='txtie'></select>
<!-- -->
</div>
</span>
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
<label>Cargo Actual:</label><input class="textborder" type="text" style="width:213px; height:24px" name="txtcargo" id="txtcargo">
</td>
</tr>
</table>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="spaceleft borde-down borde-top" colspan="2">
IV. DIRECCIÓN:
</td>
</tr>
<tr>
<td colspan="2">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="spaceleft">TIPO DE VÍA*:</td>
<td><label>Avenida:</label><input type="radio" name="rbtvia" value="1"></td>
<td><label>Jirón:</label><input type="radio" name="rbtvia" value="2"></td>
<td><label>Calle:</label><input type="radio" name="rbtvia" value="3"></td>
<td><label>Pasaje:</label><input type="radio" name="rbtvia" value="4"></td>
<td><label>Carretera:</label><input type="radio" name="rbtvia" value="5"></td>
<td><label>Prolongación:</label><input type="radio" name="rbtvia" value="6"></td>
<td><label for="rbtvia[]" class="afr-error" style="display:none;">Please choose one.</label></td>
</tr>
</table>
</td>
</tr>
<tr class="textleft">
<td colspan="2" class="spaceleft">
<label style="display:inline-block; width:90px;">Nombre de la vía*:</label><input class="textborder required" style="width:814px; height:24px" type="text" name="txtnomvia" id="txtnomvia" >
</td>
</tr>
<tr class="textleft">
<td colspan="2" class="spaceleft">
<label style="display:inline-block; width:90px;">Referencia*:</label><input class="textborder required" style="width:814px; height:24px" type="text" name="txtreferencia" id="txtreferencia" >
</td>
</tr>
<tr>
<td colspan="2" class="spaceleft">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<label>Código Modular:</label><input class="textborder" style="width: height:24px" type="text" name="txtmodula" id="txtmodula">
</td>
<td>
<label>Teléfonos*:</label><input class="textborder required" style="width: height:24px" onkeypress="return soloNumeros(event);" maxlength="11" type="text" name="txtphone" id="txtphone">
</td>
<td>
<label>Correo Electronico*:</label><input class="textborder email" style="width: height:24px" type="text" name="txtemail" id="txtemail" required >
</td>
</tr>
</table>
</td>
</tr>
<tr class="textleft afr-tdsection fundamentosBuzon" style="display:none" >
<td class="spaceleft borde-down " colspan="2">
V. FUNDAMENTOS DEL PEDIDO:
</td>
</tr>
<tr class="textleft fundamentosBuzon" style="display:none" >
<td style="text-align:left;" class="fundamentosBuzon" style="display:none" colspan="2">
¿ Que información proporcionar? <span id="informacionAdicional" name="informacionAdicional" class="informacionAdicional" ></span>
</td>
</tr>
<tr class="textleft fundamentosBuzon" style="display:none">
<td class="borde-down" colspan="2">
<textarea onkeyup="countChar(this)" id="txtfundpedido" name="txtfundpedido" placeholder="Escriba aquí fundamento de pedido." class="afr-textarea" style="height:60px" required ></textarea>
<p style="padding-top:5px;color:black;padding-left:750px">Cantidad maxima de caracteres <b id="charNum" style="color:#CB5656" >250</b></p>
</td>
</tr>
<span style="display:none" id="informacionAdicional2" name="informacionAdicional2" class="informacionAdicional2" ></span>
<tr class="textleft afr-tdsection">
<td class="spaceleft borde-down " colspan="2">
VI. DOCUMENTOS QUE SE ADJUNTAN:
</td>
</tr>
<tr class="textleft">
<td class="" colspan="2">
<ul id="ulfile">
<li>
<label>* Copia de DNI :</label>
<input type="file" name="afr-file[]" class="required requisito" id="file1" >
</li>
</ul>
</td>
</tr>
<tr class="textleft ">
<td>
<label> * Ingrese Número de Oficio y/o documento de solicitud:</label><input class="textborder" style="width:50px" onkeypress="return soloNumeros(event);" maxlength="4" type="text" name="txtfoficio" id="txtfoficio">
</td>
</tr>
<tr class="textleft ">
<td>
<label> * Ingrese Número de Folio(s):</label><input disabled class="textborder" style="width:50px" onkeypress="return soloNumeros(event);" maxlength="3" type="text" name="txtfolio_" id="txtfolio_">
<input onkeypress="return soloNumeros(event);" maxlength="3" type="hidden" name="txtfolio" id="txtfolio">
</td>
</tr>
<tr class="textleft ">
<td class="spaceleft" colspan="2">
Declaro que los datos presentados en el presente formulario los realizo con caracter de declaración jurada.
</td>
</tr>
<tr class="textleft afr-tdsection">
<td style="background-color:white; color:black" class="spaceleft borde-down borde-top" colspan="2">
<!--
DECLARO que los datos presentados en el presente formulario los realizo con carácter de DECLARACIÓN JURADA
-->
<label class="checkbox checkbox-outline-success">
<input class="textleft " type="checkbox" id="condiciones" name="condiciones" data-toggle="modal" data-target="#exampleModalLong" ><span>(*)Acepto Terminos y condiciones</span><span class="checkmark"></span>
<input id="resultadocheck" name="resultadocheck" type="hidden" value="0">
<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div style="background-color:#c62c2c; color:white" class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Terminos y condiciones</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p style="text-align:justify"> Al dar click en este casillero, usted está autorizando </p>
<p style="text-align:justify"><b> Veracidad de la información declara por el administrado</b></p>
<p style="text-align:justify"> Declaro expresamente que la información ingresa en la Plataforma para el proceso de contratación docente 2020 es verdadera y conforme con lo establecido en el artículo 49 del Texto Único Ordenado de la Ley N° 27444, Ley del Procedimiento Administrativo General, y en caso de resultar falsa la información que proporciono, me sujeto a los alcances de lo establecido en el artículo 411 del Código Penal, concordante con el artículo 33 del Texto Único Ordenado de la Ley N° 27444, Ley del Procedimiento Administrativo General; autorizando a efectuar la comprobación de la veracidad de la información declarada en la presente plataforma.</p>
<p style="text-align:justify"><b> Autorización para la notificación al correo electrónico</b> </p>
<p style="text-align:justify">AUTORIZO de forma expresa y conforme a lo dispuesto por el artículo N° 20 del Texto único Ordenando de la Ley N° 27444 – Ley del Procedimiento Administrativo General, aprobado mediante el DECRETO SUPREMO Nº 004-2019-JUS y modificado mediante el Decreto Legislativo N° 1497, a la UNIDAD DE GESTION EDUCATIVA LOCAL 03 – UGEL 03, que me notifique el/los acto(s) administrativo(s), comunicados o documentación adicional que se emitan a consecuencia del proceso de contratación docente 2020 al correo electrónico consignado en presente plataforma; así mismo acuerdo que el acto administrativo, los comunicados o la documentación adicional pueda estar contenida en un archivo adjunto o un enlace web a través del cual se descargará y/o otros mecanismo que garanticen su notificación.</p>
<p style="text-align:justify">Tengo conocimiento que las notificaciones dirigidas a la dirección de mi correo electrónico señalada en la presente Plataforma se entiende válidamente efectuadas cuando la UGEL 03 reciba la respuesta de recepción de la dirección electrónica antes señalada; a través del acuse de recibo, el mismo que dejará constancia del acto de notificación; en concordancia a lo establecido por el artículo 20 del mencionado Texto Único Ordenado, surtiendo efectos el día siguiente que conste haber sido recibido en mi bandeja de entrada, conforme a lo previsto en el numeral 2 del artículo 25 del citado Texto Único Ordenado.</p>
<p style="text-align:justify">
En atención a la presente autorización me comprometo con las siguientes obligaciones:
1. Señalar una dirección de correo electrónica válida, a la cual tenga acceso y que se mantenga activa durante el proceso de contratación docente 2020.
2. Asegurar que la capacidad del buzón de la dirección de correo electrónico permita recibir los documentos a notificar.
3. Revisar continuamente la cuenta de correo electrónico, incluyendo la bandeja de spam o el buzón de correo no deseado.</p>
<p style="text-align:justify">El no tomar conocimiento oportuno de las notificaciones remitidas por la UNIDAD DE GESTION EDUCATIVA LOCAL 03 – UGEL 03, debido al incumplimiento de las presentes obligaciones, constituye exclusiva responsabilidad de mi persona. </p>
<p style="text-align:justify">DECRETO LEGISLATIVO Nº 1497: DECRETO LEGISLATIVO QUE ESTABLECE MEDIDAS PARA PROMOVER Y FACILITAR CONDICIONES REGULATORIAS QUE CONTRIBUYAN A REDUCIR EL IMPACTO EN LA ECONOMÍA PERUANA POR LA EMERGENCIA SANITARIA PRODUCIDA POR EL COVID- 19
Artículo 3.- Incorporación de párrafo en el artículo 20 de la Ley Nº 27444, Ley del Procedimiento Administrativo General
Incorpórase un último párrafo en el artículo 20 de la Ley Nº 27444, Ley del Procedimiento Administrativo General, cuyo texto queda redactado de la manera siguiente:
“Artículo 20.- Modalidades de notificación
(…)</p>
<p style="text-align:justify">El consentimiento expreso a que se refiere el quinto párrafo del numeral 20.4 de la presente Ley puede ser otorgado por vía electrónica.”</p>
<p style="text-align:justify"><b>Autorización para el tratamiento de los datos personal del administrado</b></p>
<p style="text-align:justify">En atención a los dispuesto por la Ley N° 29733, Ley de Protección de Datos Personales y su Reglamento aprobado por Decreto Supremo N° 003-2013-JUS, AUTORIZO a la UNIDAD DE GESTION EDUCATIVA LOCAL 03 – UGEL 03 al tratamiento de mis datos personales, así como cualquier otra información ingresada en la plataforma para el proceso de contratación docente 2020.</p>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
</label>
</td>
</tr>
</table>
<div style="text-align:right">
<!--
<div id="ap-important">
<b> Acceso a instructivo:</b> <a style=" z-index: 9999;" href="https://www.youtube.com/watch?v=liiPbifXBNk">Enlace</a>
</div>-->
<div id="ap-important">
<b style="color:black" > Acceso al video instructivo Mesa de partes virtual :</b> <a target="_blank" style=" z-index: 9999;" href="https://www.youtube.com/watch?v=liiPbifXBNk">Haga clic al Enlace</a> <br>
<b style="color:black" >Sobre el horario de recepción de documentos (RD Nº 03920-2020-UGEL03 – Artículo 4)</b><br>
<ul>
<li>- La presentación de documentos en la mesa de partes virtual podrá realizarse sin restricción de horario.</li>
<li>- Sin embargo, la recepción se efectuará de acuerdo con el horario de la atención de la UGEL 03 (lunes a viernes de 8:00 a.m. a 4:45 p.m.)</li>
<li>- Pasado este horario, la documentación podrá ser presentada, pero se dará por recibida a partir del día hábil siguiente.</li>
</ul>
<b style="color:black" >Sobre problemas técnicos</b><br>
<p>Si tuviese inconvenientes para ingresar su solicitud, puede escribir al correo electrónico <EMAIL> para recibir mayor orientación.</p>
</div>
<div id="afr-important">
<b>Importante:</b> Antes de enviar el formulario, asegurese que su correo este digitado correctamente y sea válido. <br>
No registrar correos con extension <b>yahoo</b>, tenemos incovenientes por el momento.(*)Obligatorio
</div>
<div style="text-align:center !important;" class="col-md-offset-2 col-md-4">
<div class="g-recaptcha" data-sitekey="<KEY>">
</div>
<input disabled class="solPedido" id= "solPedido" style="vertical-align:middle" type="submit" value="Enviar Solicitud" class="afr-btn" >
</div>
</div>
</form>
</div>
</br></br></br>
</div>
</div>
<div style="clear:both"></div>
<div id="afr-footer">
<div id="afr-ctextfooter">
<div id="afr-textf">
<ul>
<li class="fcontact">(01) 6155800 Anexo: 13018 Informes</li>
<li class="ftime">Atención de 8:30am a 1:00pm y de 2:00pm a 4:00pm</li>
<li class="fhome">UGEL 03 -Av. Iquitos 918, La Victoria </li>
</ul>
</div>
<div id="afr-copy">
UGEL 03 | Equipo de Tecnologia de la Información <?Php echo date("Y");?> © Todos los derechos reservados
</div>
</div>
</div>
</div>
</body>
</html><file_sep>/app/views/tramite/pdf.php
<!DOCTYPE>
<html>
<head>
<?php
?>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>FORMULARIO ÚNICO DE TRAMITE (FUT)</title>
<style>
<style type="text/css">
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
.l-right{
border-right:1px solid #000;
}
.l-left{
border-left:1px solid #000;
}
.l-bottom{
border-bottom:1px solid #000;
}
.l-border{
border-top:1px solid #000;
border-right:1px solid #000;
border-left:1px solid #000;
border-bottom:1px solid #000;
}
.l-top{
border-top:1px solid #000;
}
.vtop{
vertical-align:top;
}
.aright{
text-align:right;
padding-right:2px;
}
.aleft{
text-align:left;
}
.normal{
font-weight:normal;
}
.textleft{
text-align:left;
padding-left:2px;
}
.l-right{
border-right:1px solid #000;
}
td.center{
text-align:center;
vertical-align: middle;
}
td.borde-down{
border-bottom:1px solid #999;
}
td.border-left{
border-left:1px solid #999;
}
td.borde-top{
border-top:1px solid #999;
}
.textborder{
border:1px solid #6CC0FF;
}
td.spaceleft{
padding-left:5px;
}
table{
font-size:13px;
font-family:Arial, Helvetica;
}
table td{
height: 30px;
vertical-align: middle;
}
.textborder{
border:1px solid #6CC0FF;
display:inline-block;
}
label{
display:inline-block;
margin-right:3px;
}
tr.afr-tdsection{
background:#cae4ff;
font-weight:700;
}
#afr-rm{
text-align:center;
font-size:13px;
font-family:Arial, Helvetica;
}
td.spacer{
padding-right:24px;
text-align:left;
}
</style>
</head>
<body>
<div id="afr-wrapper">
<div id="afr-bgcontaniner" style=" background:none">
<div id="afr-container">
<div id="afr-contform">
<img src="<?php echo site_resource('admin') ?>/img/logo-ugel03.jpg" >
<div id="afr-rm">
<b>RM N° 0445-2012-ED</b>
</div>
<form id="afr-frmfut" name="afr-frmfut" action="<?php echo(site_url("tramite/enviar"))?>" method="post" enctype="multipart/form-data">
<table id="afr-tblmain" border="0" cellpadding="0" cellspacing="0" class="l-border center">
<tr class="">
<td class="borde-down center" style="font-size:15px">
<b>FORMULARIO ÚNICO DE TRAMITE (FUT)</b>
</td>
<!-- <td rowspan="6" class="borde-down l-left" style="width:200px">
</td>-->
</tr>
<tr class="textleft afr-tdsection">
<td class="borde-down spaceleft" style="">
<b>I.- RESUMEN DE SU PEDIDO:</b><span style="display:inline-block; margin-left:8px"> <?php echo @$servicio ?></span>
</td>
</tr>
<tr class="textleft">
<td class="borde-down spaceleft vtop" style=" min-height:55px;vertical-align:top">
<?php echo @$resumen?>
</td>
</tr>
<tr class="textleft">
<td class="borde-down spaceleft">
<b>II. DEPENDENCIA O AUTORIDAD A QUIEN SE DIRIGE:</b> <span style="font-weight:700; font-size:14px"><?php echo $dependencia ?></span>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="borde-down spaceleft">
<b>III. DATOS DEL SOLICITANTE:</b>
</td>
</tr>
<tr class="textleft">
<td class="spaceleft">
<b>Persona Natural:</b>
</td>
</tr>
<tr>
<td colspan="2">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr style="height:60px;">
<td style="width:325px; " class="spaceleft">
<label>Apellido Paterno:</label><input type="text" class="textborder" style="width:150px;height:24px" value="<?php echo @$apepat?>">
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
<label>Apellido Materno:</label><input class="textborder" style="width:150px; height:24px" type="text" name="txtapemat" id="txtapemat" value="<?php echo @$apemat?>">
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
<label>Nombres:</label><input class="textborder" type="text" style="width:150px; height:24px" name="txtnombre" id="txtnombre" value="<?php echo @$nombre?>">
</td>
</tr>
</table>
</td>
</tr>
<tr class="textleft">
<td class="spaceleft">
<b>Persona Jurídica:</b>
</td>
</tr>
<tr class="textleft">
<td colspan="2" class="spaceleft">
<label>Razón Social:</label><input class="textborder" style="width:833px; height:24px" type="text" name="txtrazonsocial" id="txtrazonsocial" value="<?php echo @$razonsocial?>">
</td>
</tr>
<tr class="textleft">
<td class="spaceleft">
<b>Tipo de Documento:</b>
</td>
</tr>
<tr>
<td colspan="2">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr style="height:60px;">
<td style="width:272px; " class="spaceleft">
<label>DNI N° y/o RUC:</label><input class="textborder" style="width:100px; height:24px" type="text" name="txtdoc" id="txtdoc" value="<?php echo @$doc?>">
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
<label>IE:</label><input class="textborder" style="width:213px; height:24px" type="text" name="txtie" id="txtie" value="<?php echo @$ie?>">
</td>
<td style="width:325px; padding-left:10px;" class="spaceleft">
<label>Cargo Actual:</label><input class="textborder" type="text" style="width:213px; height:24px" name="txtcargo" id="txtcargo" value="<?php echo @$cargo?>">
</td>
</tr>
</table>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="spaceleft borde-down borde-top" colspan="2">
<b>IV. DIRECCIÓN:</b>
</td>
</tr>
<tr>
<td colspan="2">
<table id="" border="0" cellpadding="0" cellspacing="2">
<tr>
<td class="spaceleft" style="padding-right:8px"><b>TIPO DE VÍA:</b></td>
<td><label>Avenida: </label></td>
<td class="spacer" >
<input type="radio" <?php echo (($via==1)? 'checked="checked"': '')?> >
</td>
<td><label>Jirón:</label></td>
<td class="spacer"><input type="radio" <?php echo (($via==2)? 'checked="checked"': '')?> ></td>
<td><label>Calle:</label></td>
<td class="spacer"><input type="radio" <?php echo (($via==3)? 'checked="checked"': '')?> ></td>
<td><label>Pasaje:</label></td>
<td class="spacer"><input type="radio" <?php echo (($via==4)? 'checked="checked"': '')?> ></td>
<td><label>Carretera:</label></td>
<td class="spacer"><input type="radio" <?php echo (($via==5)? 'checked="checked"': '')?> ></td>
<td><label>Prolongación:</label></td>
<td><input type="radio" <?php echo (($via==6)? 'checked="checked"': '')?> ></td>
</tr>
</table>
</td>
</tr>
<tr class="textleft">
<td colspan="2" class="spaceleft">
<label style="display:inline-block; width:90px;">Nombre de la vía:</label><input class="textborder" style="width:814px; height:24px" type="text" name="txtnomvia" id="txtnomvia" value="<?php echo @$nombvia?>">
</td>
</tr>
<tr class="textleft">
<td colspan="2" class="spaceleft">
<label style="display:inline-block; width:90px;">Referencia:</label><input class="textborder" style="width:814px; height:24px" type="text" name="txtreferencia" id="txtreferencia" value="<?php echo @$referencia?>">
</td>
</tr>
<tr>
<td colspan="2" class="spaceleft">
<table id="" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<label>Teléfonos:</label><input class="textborder" style="width:200px; height:24px" type="text" name="txtphone" id="txtphone" value="<?php echo @$telefono?>">
</td>
<td>
<label>Código Modular:</label><input class="textborder" style="width:200px; height:24px" type="text" name="txtmodula" id="txtmodula" value="<?php echo @$modular?>">
</td>
<td>
<label>Correo:</label><input class="textborder" style="width:200px; height:24px" type="text" name="txtemail" id="txtemail" value="<?php echo @$email?>">
</td>
</tr>
</table>
</td>
</tr>
<tr class="textleft afr-tdsection">
<td class="spaceleft borde-down borde-top" colspan="2">
DECLARO que los datos presentados en el presente formulario los realizo con carácter de DECLARACIÓN JURADA
</td>
</tr>
<?php if($fundamento){?>
<tr class="textleft afr-tdsection">
<td class="spaceleft borde-down " colspan="2">
<b>V. FUNDAMENTOS DEL PEDIDO:</b>
</td>
</tr>
<tr class="textleft">
<td class="" colspan="2" style="text-align:justify; padding:0 8px; height:140px; vertical-align:top">
<div><?php echo @$fundamento ?></div>
</td>
</tr>
<?php }?>
<!-- <tr class="textleft ">
<td class="spaceleft" colspan="2">
Declaro que los datos presentados en el presente formulario los realizo con caracter de declaración jurada.
</td>
</tr>-->
<?php /*?><tr class="textleft afr-tdsection">
<td class="spaceleft borde-down " colspan="2">
VI. DOCUMENTOS QUE SE ADJUNTAN:
</td>
</tr>
<tr class="textleft">
<td class="" colspan="2">
<ul id="ulfile">
<li>
<input type="file" name="afr-file[]" >
</li>
<li>
<input type="file" name="afr-file[]" >
</li>
<li>
<input type="file" name="afr-file[]" >
</li>
</ul>
</td>
</tr><?php */?>
</table>
</form>
</div>
</div>
</div>
<div style="clear:both"></div>
</div>
</body>
</html><file_sep>/admin/models/old/Model_boleta.php
<?php
class Model_boleta extends CI_Model
{
function __construct()
{
parent::__construct();
}
function getCount($params = ''){
$params['count'] = true;
return $this->getAll($params);
}
function getAll($params = ''){
$select = $where = $limit = $order = '';
$where = " WHERE ";//"WHERE c.cupon_id=tc.cupon_id AND tc.id_categoria=ct.id_categoria";
#$where = "WHERE (d.State=1 OR d.State=-1) AND a.IdDisco=d.IdDisco";
//writer($params['idUser']); exit;
if (is_array($params)) {
if (isset($params['start'],$params['limit']))
$limit = "LIMIT " . $params['start'] . ", " . $params['limit'];
if (isset($params['orderBy'],$params['sentido']))
$order = "ORDER BY " . $params['orderBy'] . " " . $params['sentido'];
if (isset($params['status']))
$where .= " (b.status = '".$params['status']."')";
if(isset($params['search2']))
$where .= " AND b.idperiodo = ".$params['search2'];
;
if(isset($params['search']))
$where .= " AND (CONCAT(b.nombre) LIKE('%".$params['search']."%') OR b.dni LIKE('".$params['search']."%'))";
;
}
if (isset($params['count'])){
$select = "SELECT COUNT(*) AS total";
}
else{
$select = "SELECT b.* ";
//$select = "SELECT c.*, ct.categoria_name ";
}
$sql = "$select
FROM boleta b
$where
$order
$limit";
$query = $this->db->query($sql);
if (isset($params['count'])) {
$result = $query -> row();
return $result -> total;
}
else
if ( $query -> result() )
return $query -> result();
else
return false;
}
//obtenemos las localidades dependiendo de la provincia escogida
function search($buscar)
{
/*$sql = "SELECT * FROM boleta where idboleta =".$buscar;*/
$sql = "SELECT * FROM boleta where idboleta IN (".$buscar.")";
$query = $this->db->query($sql);
$result = $query->result_array();
if($result){
return $result;
}
else{
return false;
}
}
function save($data){
$this->db->insert("boleta",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
function saveperiodo($data){
$this->db->insert("periodo",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
function update_periodo($data){
$id = $this->db->update('periodo', $data, array('idperiodo' => $data['idperiodo']));
if($id){
return true;
}
else{
return false;
}
}
function Obt_Periodo(){
$sql = "SELECT * FROM periodo WHERE status=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->result();
}
else
return false;
}
function Get_TotPagosVenta($id){
$sql = "SELECT SUM(monto) AS total FROM tb_cobro WHERE status=1 AND id_venta=".$id;
$query = $this->db->query($sql);
if($query->result()){
return $query->row()->total;
}
else
return false;
}
function Get_VentaById($id){
$sql = "SELECT SUM(total) AS monto, CONCAT(p.name,' ',p.lastname) AS cliente,v.id_venta FROM tb_detventa dv, tb_venta v, persona p,
cliente cl WHERE dv.id_venta=$id
AND dv.status>0
AND dv.id_venta=v.id_venta AND v.id_cliente=cl.id_cliente AND cl.id_persona=p.id_persona";
//die($sql);
$query = $this->db->query($sql);
if($query->result()){
$data = $query->row();
$data->monto = $data->monto - str_replace(",","",$this->Get_pagos($id));
$data->cobros = str_replace(",","",$this->Get_pagos($id));
return $data;
}
else{
return false;
}
}
function delete($data){
$id = $this->db->update('boleta', $data, array('idboleta' => $data['idboleta']));
if($id){
return true;
}
else{
return false;
}
}
}<file_sep>/app/models/Model_login.php
<?php
class Model_login extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function Get_user($correo,$pass)
{
//$sql = "SELECT FROM tb_usuarios u, tb_usutipopersona c WHERE u.idTipPer=c.idTipPer AND u.correo='".$correo."' AND c.pass='". $pass."' AND u.estado='1' AND c.estado='1'";
$sql = "SELECT * FROM tb_usuarios WHERE correo='".$correo."' AND pass='".$pass."' AND estado=1" ;
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
public function Get_user2($id){
$sql = "SELECT u.*, c.pass FROM tb_usuarios u, tb_creden c WHERE u.id_usuario = c.id_usuario AND u.correo='".$id."' AND u.flg=1 AND c.flg=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
public function obtenerUsuario($id){
$sql = "SELECT * FROM tb_usuarios WHERE id_usuario='".$id."'";
$query = $this->db->query($sql);
$result = $query->row();
if($result){
return $result;
}
else
return false;
}
// MUESTRA EN UNA LISTA LOS DEPARTAMENTOS
/*public function getubicacion(){
$data = array();
$this->db->where('estado','1');
$this->db->order_by('departamento','asc');
$query = $this->db->get('tb_ubdepartamento');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}*/
/*public function getubicacion(){
$this->db->order_by('departamento','asc');
$query = $this->db->get('tb_ubdepartamento');
//print_r($query->result());
return $query->result();
}*/
public function getubicacion(){
$data = array();
$this->db->where('estado','1');
$query = $this->db->get('tb_ubdepartamento');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function getprovincia($id_depa){
$this->db->where('idDepa',$id_depa);
$this->db->order_by('provincia','asc');
$provincias = $this->db->get('tb_ubprovincia');
if($provincias->num_rows()>0)
{
return $provincias->result();
}
}
public function getdistrito($id_prov){
$this->db->where('idProv',$id_prov);
$this->db->order_by('distrito','asc');
$id_prov = $this->db->get('tb_ubdistrito');
if($id_prov->num_rows()>0)
{
return $id_prov->result();
}
}
public function save_primerlogin($data)
{
$this->db->insert("tb_primerlogin",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
// MUESTRA LOS VALORES DE UNA TABALA DEPENDIENTE //
public function gettipopersona(){
$data = array();
$this->db->where('estado','1');
$query = $this->db->get('tb_usutipopersona');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
// MUESTRA LOS VALORES DE UNA TABALA DEPENDIENTE //
public function getTipoDoc($tipodoc){
$this->db->where('idTipPer',$tipodoc);
$this->db->order_by('descripcion','desc');
$tipodoc = $this->db->get('tb_usutipodocumento');
if($tipodoc->num_rows()>0)
{
return $tipodoc->result();
}
}
// MUESTRA LOS VALORES DE UNA SOLA TABLA //
public function gettipocargo(){
$data = array();
$this->db->where('estado','1');
$this->db->order_by('descripcion_cargo','desc');
$query = $this->db->get('tb_usucargo');
if($query->num_rows()>0)
{
foreach($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
// MUESTRA LOS VALORES DE UNA SOLA TABLA //
public function gettipovia(){
$data = array();
$this->db->where('estado','1');
$this->db->order_by('descripcion','asc');
$query = $this->db->get('tb_ubvia');
if($query->num_rows()>0)
{
foreach($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
// MUESTRA LOS VALORES DE UNA SOLA TABLA //
public function gettipozona(){
$data = array();
$this->db->where('estado','1');
$this->db->order_by('descripcion','desc');
$query = $this->db->get('tb_ubzona');
if($query->num_rows()>0)
{
foreach($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function buscaEmail($email){
$sql = "SELECT count(*) as num FROM tb_usuarios WHERE correo='".$email."' AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}else{
return false;
}
}
public function buscaDni($dni){
$sql = "SELECT count(*) as num FROM tb_usuarios WHERE nroDocumento='".$dni."' AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
/* INGRESA CAMPOS A LA TABLA USUARIOS */
public function save_registroUsuario($data){
$this->db->insert("tb_usuarios",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
/* ACTUALIZA CAMPOS A LA TABLA USUARIOS */
/*public function save_actualizacionUsuario($data){
$this->db->update("tb_usuarios",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}*/
function update_datosPersonales($data){
$id = $this->db->update('tb_usuarios', $data);
if($id){
return true;
}
else{
return false;
}
}
/* INGRESA CAMPOS A LA TABLA USUARIOS */
public function save_direccionusuario($data){
$this->db->insert("tb_ubusuario",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
public function buscaIdUsuario($dni){
$sql = "SELECT id_usuario as usu FROM tb_usuarios WHERE nroDocumento='".$dni."' AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
public function save_credencialUsuario($data){
$this->db->insert("tb_creden",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
/***********************************************************************/
public function save_meritonuevo($data)
{
$this->db->insert("tb_merito",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
public function getcargo()
{
$data = array();
$this->db->where('vista','1');
$this->db->order_by('descripcion_cargo','asc');
$query = $this->db->get('tb_cargo');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function getmodalidad()
{
$data = array();
$this->db->where('vista','1');
$this->db->order_by('descripcion_modalidad','asc');
$query = $this->db->get('tb_modalidad');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function getfase()
{
$data = array();
$this->db->where('vista','1');
$this->db->order_by('descripcion_fase','asc');
$query = $this->db->get('tb_fase');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function getFaseEspecifico($etapa)
{
$this->db->where('id_etapa',$etapa);
$this->db->where('vista','1');
$this->db->order_by('descripcion_fase','asc');
$fase = $this->db->get('tb_fase');
if($fase->num_rows()>0)
{
return $fase->result();
}
}
public function getnivel()
{
$data = array();
$this->db->where('vista','1');
$this->db->order_by('descripcion_nivel','asc');
$query = $this->db->get('tb_nivel');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function getetapa()
{
$data = array();
$this->db->where('vista','1');
$this->db->order_by('descripcion_etapa','asc');
$query = $this->db->get('tb_etapa');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function getNivelEspecifico($modalidad)
{
$this->db->where('id_modalidad',$modalidad);
$this->db->where('vista','1');
$this->db->order_by('descripcion_nivel','asc');
$nivel = $this->db->get('tb_nivel');
if($nivel->num_rows()>0)
{
return $nivel->result();
}
}
public function getcurricular()
{
$data = array();
$this->db->where('vista','1');
$this->db->order_by('descripcion_curricular','asc');
$query = $this->db->get('tb_curricular');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function getCurricularEspecifico($cargo)
{
$this->db->where('id_cargo',$cargo);
$this->db->where('vista','1');
$this->db->order_by('descripcion_curricular','asc');
$curricular = $this->db->get('tb_curricular');
if($curricular->num_rows()>0)
{
return $curricular->result();
}
}
public function getCurricularEspecifico2($nivel)
{
$this->db->where('id_nivel',$nivel);
$this->db->where('vista','1');
$this->db->order_by('descripcion_curricular','asc');
$curricular = $this->db->get('tb_curricular');
if($curricular->num_rows()>0)
{
return $curricular->result();
}
}
public function buscaMerito($dni)
{
$sql = "SELECT count(*) as num FROM tb_merito WHERE dni ='".$dni."' and estado=1 ";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
public function buscaAdjudicado($dni)
{
$sql = "SELECT count(*) as num FROM tb_merito WHERE dni='".$dni."' and flg = 1 and estado=1 ";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
public function buscaTiempo($dni)
{
$sql = "SELECT f.fechaini, f.fechafin FROM tb_merito m, tb_control_adju ca, tb_fechas f WHERE m.control_id = ca.id_control and ca.id_fecha = f.id_fecha and m.dni='".$dni."' and m.flg = 0 and m.estado = '1' and ca.estado = '1' and f.estado = '1' ";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
public function Get_userChangePass($data = array())
{
$sql = "SELECT * FROM tb_postulante WHERE nroDoc='".$data['dni']."' and email='".$data['email']."' and pass='".$data['passaActual']."' and flg='1'";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
public function Change_PasswordUser($data)
{
$id = $this->db->update('tb_postulante', $data, array('nroDoc' => $data['nroDoc'],'email' => $data['email']));
if($id){
return true;
}
else{
return false;
}
}
}
<file_sep>/admin/helpers/comun_helper.php
<?php
## Funciones Comunes ##
// // funciones de fechas
/**
* dateSmart
*/
function dateSmart($dateIn, $template='{hour}:{min} {day}-{month:name}-{year}'){
$dateIn .= (strlen($dateIn)<=10) ? " 00:00:00":'';
$dateOut = $template;
$dater['year'] = substr ($dateIn,0,4);
$dater['month'] = substr ($dateIn,5,2);
$dater['day'] = substr ($dateIn,8,2);
$dater['hour'] = substr ($dateIn,11,2);
if( $dater['hour'] >12) {
$dater['hour'] = $dater['hour'] - 12;
$dater['meridian'] = 'pm';
}else{
$dater['meridian'] = 'am';
}
$dater['min'] = substr ($dateIn,14,2);
$dater['seg'] = substr ($dateIn,17,2);
$dateOut = str_replace('{year}', $dater['year'] ,$dateOut );
$dateOut = str_replace('{month}', $dater['month'] ,$dateOut );
$dateOut = str_replace('{day}', $dater['day'] ,$dateOut );
$dateOut = str_replace('{hour}', $dater['hour'] ,$dateOut );
$dateOut = str_replace('{min}', $dater['min'] ,$dateOut );
$dateOut = str_replace('{seg}', $dater['seg'] ,$dateOut );
$dateOut = str_replace('{meridian}', $dater['meridian'] ,$dateOut );
if( substr_count($dateOut, '{month:name}') ){
$dateOut = str_replace('{month:name}', date_month_name($dater['month']) ,$dateOut );
}
if( substr_count($dateOut, '{day:name}') ){
$mkdate = mktime(0,0,0,$dater['month'], $dater['day'], $dater['year']);
$dateOut = str_replace('{day:name}', date_day_name( date("w", $mkdate) ) , $dateOut );
}
return $dateOut;
}
function daySmart($numberDay,$template='{day:name}'){
$dateOut = $template;
$dateOut = str_replace('{day:name}', date_day_name($numberDay) ,$dateOut );
return $dateOut;
}
function date_month_name( $mm ){
if(trim($mm)=='') return '';
$months = array('','Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre');
return $months[ abs( $mm )];
}
function date_day_name( $mm ){
if(trim($mm)=='') return '';
$days = array('Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sabado');
return $days[ abs( $mm )];
}
function dateNow( $format = "Y-m-d H:i:s" ){
return date( $format, ( time()-18000 ) );
//return date("Y-m-d H:i:s" );
}
function dateAgo( $str ){
list( $date, $hour) = split( ' ', $str );
list( $yy, $mm, $dd) = split( ' ', $date );
if ( substr_count( ":", $hour ) == 0 ){
$hh = $ii = $ss = 0;
}else{
list( $hh, $ii, $ss) = split( ' ', $hour );
}
$tmp = time() - mktime($hh, $ii, $ss, $mm, $dd, $yy);
}
function days_in_month($month = 0, $year = '')
{
if ($month < 1 OR $month > 12)
{
return 0;
}
if ( ! is_numeric($year) OR strlen($year) != 4)
{
$year = date('Y');
}
if ($month == 2)
{
if ($year % 400 == 0 OR ($year % 4 == 0 AND $year % 100 != 0))
{
return 29;
}
}
$days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
return $days_in_month[$month - 1];
}
/* Funciones iconodelamoda */
function get_porcentaje($param1, $param2, $precision=2) {
if ( $param2 ) {
$value = round($param1 * 100 / $param2, $precision) * 100;
$result = str_pad($value, 5,' ',0);
$prefijo_cero = ( $value < 100 ) ? '0' : '';
return $prefijo_cero . trim(substr($result,0,3)) . "." . trim(substr($result,3,2));
}
else
return "0.00";
}
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
if (isset($_COOKIE['fbs_' . $app_id])){
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
}
return $args;
}
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
function show_embed_video($url) {
$media = $url;
$media = str_replace("http://","",$media);
$media = str_replace("www.youtube.com/","",$media);
$media = str_replace("watch?v=","",$media);
return '<a href="'.$url.'" target="_blank"><img width="145" src="http://i2.ytimg.com/vi/'.$media.'/default.jpg"/></a>';
}
function format_date($fecha, $type=''){
$hour='';
$meridiano='';
if(strlen(trim($fecha))==19):
list($fecha,$hour,$meridiano) = explode(" ",$fecha);
endif;
//formato fecha americana
switch($type)
{
default:
$result=date("d/m/Y",strtotime($fecha));
break;
case 'en':
$result=date("Y-m-d",strtotime(str_replace("/","-",$fecha)));
break;
}
return trim($result." ".$hour);
}
function makehrs_real($hour){
if(strstr($hour,'pm'))
{
switch(substr($hour,0,2))
{
case '12':
$hreal=str_replace(substr($hour,0,2),'12',$hour);
break;
case '11':
$hreal=str_replace(substr($hour,0,2),'23',$hour);
break;
case '10':
$hreal=str_replace(substr($hour,0,2),'22',$hour);
break;
case '09':
$hreal=str_replace(substr($hour,0,2),'21',$hour);
break;
case '08':
$hreal=str_replace(substr($hour,0,2),'20',$hour);
break;
case '07':
$hreal=str_replace(substr($hour,0,2),'19',$hour);
break;
case '06':
$hreal=str_replace(substr($hour,0,2),'18',$hour);
break;
case '05':
$hreal=str_replace(substr($hour,0,2),'17',$hour);
break;
case '04':
$hreal=str_replace(substr($hour,0,2),'16',$hour);
break;
case '03':
$hreal=str_replace(substr($hour,0,2),'15',$hour);
break;
case '02':
$hreal=str_replace(substr($hour,0,2),'14',$hour);
break;
case '01':
$hreal=str_replace(substr($hour,0,2),'13',$hour);
break;
}
}
else
{
switch(substr($hour,0,2))
{
case '12':
$hreal=str_replace(substr($hour,0,2),'00',$hour);
break;
default:
$hreal=$hour;
break;
}
}
return $hreal;
}
function Delete_Directory($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
function site_resource($ext=""){
return base_url().str_replace("//","/","resource/".$ext);
}
function writer($var){
echo("<pre>".print_r($var,true)."</pre>");
}
function CutText($texto,$size){
$texto = strip_tags(trim($texto));
if(strlen($texto)>$size){
for($i=$size;$i>0;$i--){
if(substr($texto,$i,1)==" "){
return substr($texto,0,$i)."...";
break;
}
}
} else {
return $texto;
}
}
function Get_DatesOfBetween($dateStart,$dateEnd){//Retorna todas las fechas que hay entre dos fechas
$date_Start=strtotime($dateStart);
$date_End=strtotime($dateEnd);
$dateArray = array();
for($i=$date_Start; $i<=$date_End; $i+=86400){
array_push($dateArray, date("d-m-Y", $i));
}
return $dateArray;
}
function makedays(){
$digit='00';
for($i=1;$i<32;$i++){
echo '<option value="'.substr($digit,0,strlen($digit)-strlen($i)).$i.'">'.substr($digit,0,strlen($digit)-strlen($i)).$i.'</option>';
}
}
function makemonths($name=''){
$digit='00';
$mes=array('1'=>'ENERO', '2'=>'FEBRERO', '3'=>'MARZO', '4'=>'ABRIL', '5'=>'MAYO', '6'=>'JUNIO', '7'=>'JULIO', '8'=>'AGOSTO', '9'=>'SETIEMBRE', '10'=>'OCTUBRE', '11'=>'NOVIEMBRE', '12'=>'DICIEMBRE');
switch($name){
default:
case '':
for($i=1;$i<=12;$i++){
echo '<option value="'.substr($digit,0,strlen($digit)-strlen($i)).$i.'">'.substr($digit,0,strlen($digit)-strlen($i)).$i.'</option>';
}
break;
case 'SHORTNAME':
for($i=1;$i<=12;$i++){
echo '<option value="'.substr($digit,0,strlen($digit)-strlen($i)).$i.'">'.substr($mes[$i],0,3).'</option>';
}
break;
case 'shortname':
for($i=1;$i<=12;$i++){
echo '<option value="'.substr($digit,0,strlen($digit)-strlen($i)).$i.'">'.ucfirst(strtolower(substr($mes[$i],0,3))).'</option>';
}
break;
case 'NAME':
for($i=1;$i<=12;$i++){
echo '<option value="'.substr($digit,0,strlen($digit)-strlen($i)).$i.'">'.$mes[$i].'</option>';
}
break;
case 'name':
for($i=1;$i<=12;$i++){
echo '<option value="'.substr($digit,0,strlen($digit)-strlen($i)).$i.'">'.ucfirst(strtolower($mes[$i])).'</option>';
}
break;
}
}
function makeyears($inicio='',$fin=''){
if(!empty($inicio) and !empty($fin)){
$start=$inicio;
$end = $fin;
}
else{
$start = date('Y')-95;
$end = date('Y');
}
for($i=$end;$i>=$start;$i--){
echo '<option value="'.$i.'">'.$i.'</option>';
}
}
function Get_Days_Month($date=''){
$days = array();
if(empty($date)):
$maxDays = date("t",mktime(0,0,0,date("n"),date("j"),date("Y")));
else:
$date = substr($date,0,10);
list($anio,$mes,$dia)= explode("-",$date);
$maxDays = date("t",mktime(0,0,0,(int)$mes,(int)$dia,(int)$anio));
endif;
for($d=1;$d<=$maxDays;$d++){
array_push($days,$d);
}
return $days;
}
function Get_Calendary($date = ''){
$_cal = array();
if(empty($date)):
$day_start = date("N",mktime(0,0,0,date("n"),date("j"),date("Y")));
$ndays = Get_Days_Month(date('Y-m-d'));
$day_end = date('N',mktime(0,0,0,date("n"),(int)$ndays[count($ndays)-1],date("Y")));
else:
list($anio,$mes,$dia)= explode("-",$date);
$day_start = date('N',mktime(0,0,0,(int)$mes,(int)$dia,(int)$anio));
$ndays = Get_Days_Month($date);
$day_end = date('N',mktime(0,0,0,(int)$mes,(int)$ndays[count($ndays)-1],(int)$anio));
endif;
$NroOfWeek = ceil((count($ndays)+($day_start-1))/7);
for($j=1;$j<=($day_start-1);$j++){
array_unshift($ndays,"");
}
for($h=1;$h<=(7-$day_end);$h++){
array_push($ndays,"");
}
$_cal['day_star'] = $day_start;
$_cal['day_end'] = $day_end;
$_cal['ndays'] = $ndays;
$_cal['nweek'] = $NroOfWeek;
return $_cal;
}
function To_Upper($str){
$_search = array("á","é","í","ó","ú");
$_replace = array("Á","É","Í","Ó","Ú");
$res = strtoupper($str);
return str_replace($_search,$_replace,$res);
}
function cleanString($string)
{
$string = trim($string);
$string = str_replace(
array('á', 'à', 'ä', 'â', 'ª', 'Á', 'À', 'Â', 'Ä'),
array('a', 'a', 'a', 'a', 'a', 'A', 'A', 'A', 'A'),
$string
);
$string = str_replace(
array('é', 'è', 'ë', 'ê', 'É', 'È', 'Ê', 'Ë'),
array('e', 'e', 'e', 'e', 'E', 'E', 'E', 'E'),
$string
);
$string = str_replace(
array('í', 'ì', 'ï', 'î', 'Í', 'Ì', 'Ï', 'Î'),
array('i', 'i', 'i', 'i', 'I', 'I', 'I', 'I'),
$string
);
$string = str_replace(
array('ó', 'ò', 'ö', 'ô', 'Ó', 'Ò', 'Ö', 'Ô'),
array('o', 'o', 'o', 'o', 'O', 'O', 'O', 'O'),
$string
);
$string = str_replace(
array('ú', 'ù', 'ü', 'û', 'Ú', 'Ù', 'Û', 'Ü'),
array('u', 'u', 'u', 'u', 'U', 'U', 'U', 'U'),
$string
);
$string = str_replace(
array('ñ', 'Ñ', 'ç', 'Ç'),
array('n', 'N', 'c', 'C',),
$string
);
//Esta parte se encarga de eliminar cualquier caracter extraño
$string = str_replace(
array("\\", "¨", "º", "-", "~",
"#", "@", "|", "!", "\"",
"·", "$", "%", "&", "/",
"(", ")", "?", "'", "¡",
"¿", "[", "^", "`", "]",
"+", "}", "{", "¨", "´",
">", "<", ";", ",", ":",
" "),
'',
$string
);
return $string;
}
function Get_Ip_User() {
return getenv('HTTP_X_FORWARDED_FOR') ? getenv('HTTP_X_FORWARDED_FOR') : getenv('REMOTE_ADDR');
}
function Add_Ceros($suma,$field){
$cantceros = strlen($field)-strlen($suma);
return str_repeat("0",$cantceros).$suma;
}
function Agrupa_Piezas($data = array()){
$result = array();
$tempArr = array();
$obj = new stdClass;
$peso = $precio = 0;
if(count($data)>0){
$count = ceil(count($data)/2);
for($i=0;$i<$count;$i++){
array_push($tempArr,array_slice($data,$i*2,2));
}
foreach($tempArr as $key=>$items){
foreach($items as $item){
$peso = $peso + $item->peso;
$precio = $item->precio;
}
$obj->peso = $peso;
$result[$key] = array('peso'=>$peso,'precio'=>$precio);
$peso = $precio = 0;
}
return $result;
}
else{
return false;
}
}
function generateRandomPass($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ijklmnopqrstuvwxyzABCDEFGHIJ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function llamadoApi($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($curl, CURLOPT_USERPWD, "[adj<PASSWORD>]$[ug3l03]:=?wsadj-ap");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
$result = json_decode($result);
curl_close($curl);
return $result;
}
?><file_sep>/app/controllers/Usuario.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct()
{
parent::__construct();
ini_set("max_execution_time", 0);
$this->load->library("session");
$this->load->model("Model_login","login");
$this->load->library('My_PHPMailer');
$this->load->library('My_dom');
}
public function index()
{
$this->load->view('usuario/vistausuario');
}
}
<file_sep>/admin/views/login/home.php
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Mesa de Partes Virtual | Ugel03 </title>
<link href="https://fonts.googleapis.com/css?family=Nunito:300,400,400i,600,700,800,900" rel="stylesheet" />
<link href="<?php echo site_resource('adjudicacion')?>/css/themes/lite-blue.min.css" rel="stylesheet" />
<link href="<?php echo site_resource('adjudicacion')?>/css/plugins/perfect-scrollbar.min.css" rel="stylesheet" />
<script src="<?php echo site_resource('adjudicacion')?>/js/plugins/jquery-3.3.1.min.js"></script>
<script src="<?php echo site_resource('admin') ?>/js/jquery.validate.min.js"></script>
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo site_resource('mdp')?>/images/laptop.png">
<script src="https://www.google.com/recaptcha/api.js?render=6LfZBasUAAAAAOJ8aj-pNqZQTFny0QFeH1nN7mHb"></script>
<style>
.layout-horizontal-bar .main-content-wrap {margin-top: 110px !important;}
.afr-error{ background: #ffe1e1; }
.layout-horizontal-bar .main-header { background:#09bf94 !important; }
.mb-2{ color:white; }
@media (max-width: 4268px) {
.mb-2:after {
content:'REASIGNACION DOCENTE NO PRESENCIAL - UGEL03 ';
font-size:14px;
}
.layout-horizontal-bar .header-topnav {
background-color: #bf090973;
}
}
@media (max-width: 768px) {
.mb-2:after {
content:'Reasignacion Ugel03';
}
.layout-horizontal-bar .main-content-wrap {
margin-top: 60px !important;
}
.layout-horizontal-bar .main-header .header-icon {
font-size: 30px;
}
}
@media (max-width: 468px) {
.card-body {
flex: 1 1 auto;
padding: 0.25rem;
}
.col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-auto, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-sm-auto, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-md-auto, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-lg-auto, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl, .col-xl-auto {
position: relative;
width: 100%;
min-height: 1px;
padding-right: 0px;
padding-left: 0px;
}
.col-md-9{
padding-right: 15px !important;
padding-left: 15px ;
text-align: justify;
}
}
.container-fluid { background-color: #eee !important; }
.layout-horizontal-bar .header-topnav .topnav a { color: black!important; }
.any:hover { background-color: white; }
.any2:hover { color: white !important; }
.bg-transparent {text-align: center; }
.layout-horizontal-bar .header-topnav .topnav a, .layout-horizontal-bar .header-topnav .topnav label {
display: flex;
flex-direction: row;
align-items: center;
padding: 13px 20px;
height: 54px;
font-size: .955rem;
}
</style>
</head>
<script type="text/javascript">
var cbo;
var dependencia = [];
$(window).resize(function() {
$('#afr-cmessage').css({
left: ($(window).width() - $('#afr-cmessage').outerWidth(true))/2,
top: ($(window).height() - $('#afr-cmessage').outerHeight(true))/2
});
});
$(function() {
$("#ap-frmLogin").validate({
rules: {
userLogin: "required",
userLogin: {
required: true,
email: false
}
},
errorElement: "span",
errorClass: "afr-error",
errorPlacement: function(error, element) {},
submitHandler: function(forms) {
enviarLogueo();
}
})
});
function enviarLogueo() {
var datastring = $("#ap-frmLogin").serialize();
$.ajax({
url: $("#ap-frmLogin").attr('action'),
method: "POST",
data: datastring,
dataType: "JSON",
beforeSend: function() {
},
success: function(data) {
switch (data.resp) {
case 100:
$(this).closest('form').find("input[type=text]").val("");
window.location.href = "<?php echo site_url('Adjudicacalifica') ?>";
break;
case 10:
alert(data.text);
break;
default:
}
}
})
}
</script>
<body>
<div class="app-admin-wrap layout-horizontal-bar">
<div class="main-header">
<div class="logo"><img src="<?php echo site_resource('adjudicacion')?>/images/logo.png" alt=""></div>
<div class="menu-toggle">
<div></div>
<div></div>
<div></div>
</div>
<div class="d-flex align-items-center">
<h5 class="mb-2 t-font-boldest"></h5>
</div>
<div style="margin: auto"></div>
<div class="header-part-right">
<!-- Full screen toggle--><i class="i-Full-Screen header-icon d-none d-sm-inline-block"
data-fullscreen=""></i>
</div>
</div>
<!-- =============== Horizontal bar End ================-->
<div class="main-content-wrap d-flex flex-column">
<!-- ============ Body content start ============= -->
<div class="main-content">
<div class="2-columns-form-layout">
<div>
<div class="row">
<div class="col-lg-12">
<div class="card text-left">
<div class="card-body">
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item"><a class="nav-link active show " id="contact-basic-tab"
data-toggle="tab" href="#contactBasic" role="tab"
aria-controls="contactBasic" aria-selected="true">Acceder</a></li>
</ul>
<!-- LOGIN -->
<div class="card-header bg-transparent">
<h3 class="card-title"
style="margin-bottom: 0rem !important;font-size: 1rem !important;">
Bienvenido</h3>
</div>
<form id="ap-frmLogin" name="ap-frmLogin" action="<?php echo(site_url('login/enviarLogin'))?>" method="post" enctype="multipart/form-data">
<div class="card-body">
<input type="hidden" name="_token" value="<KEY>">
<div class="form-group row">
<label
class="ul-form__label ul-form--margin col-lg-5 col-form-label"
for="staticEmail6">DNI:</label>
<div class="col-lg-2">
<input class="form-control" id="userLogin" name="userLogin" type="email"
placeholder="" /><small
class="ul-form__text form-text" id="passwordHelpBlock">
Por favor ingrese usuario
</small>
</div>
</div>
<div class="custom-separator"></div>
<div class="form-group row">
<label
class="ul-form__label ul-form--margin col-lg-5 col-form-label"
for="staticEmail6">Contraseña:</label>
<div class="col-lg-2">
<input class="form-control" id="passuser" name="passuser" type="<PASSWORD>"
placeholder="" /><small
class="ul-form__text form-text" id="passwordHelpBlock">
Por favor ingrese contraseña
</small>
</div>
</div>
<div class="custom-separator"></div>
</div>
<div class="card-footer">
<div class="mc-footer">
<div class="row text-center">
<div class="col-lg-12">
<button type="submit" value="Enviar" class="btn btn-primary m-1">ACCEDER</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- end of main row -->
</div>
</div><!-- end of main-content -->
</div>
<!-- Footer Start -->
<div class="flex-grow-1"></div>
<div class="app-footer">
<div class="row">
<div class="col-md-9">
<p><strong>MISIÓN</strong></p>
<p>
Garantizar un servicio educativo de calidad en todos los niveles y modalidades,
fortaleciendo las capacidades de gestión pedagógica y administrativa, impulsando la cohesión
social y promoviendo el aporte de los gobiernos locales e instituciones privadas
especializadas para mejorar la calidad del servicio educativo.
<sunt></sunt>
</p>
</div>
</div>
<div class="footer-bottom border-top pt-3 d-flex flex-column flex-sm-row align-items-center">
<a class="btn btn-primary text-white btn-rounded" href="#" target="_blank">
UGEL03</a>
<span class="flex-grow-1"></span>
<div class="d-flex align-items-center">
<img class="logo" src="<?php echo site_resource('adjudicacion')?>/images/logo.png" alt="">
<div>
<p class="m-0">© 2020 ETI | APP</p>
<p class="m-0">Todos los derechos reservados</p>
</div>
</div>
</div>
</div>
<!-- fotter end -->
</div>
</div>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('6LfZBasU<KEY>', {
action: 'homepage'
}).then(function(token) {
document.getElementById("token").value = token;
});
});
</script>
<script src="<?php echo site_resource('adjudicacion')?>/js/plugins/bootstrap.bundle.min.js"></script>
<script src="<?php echo site_resource('adjudicacion')?>/js/plugins/perfect-scrollbar.min.js"></script>
<script src="<?php echo site_resource('adjudicacion')?>/js/scripts/script.min.js"></script>
<script src="<?php echo site_resource('adjudicacion')?>/js/scripts/sidebar-horizontal.script.js"></script>
</body>
</html><file_sep>/admin/models/Model_login.php
<?php
class Model_login extends CI_Model
{
function __construct()
{
//$this->db_sinad = $this->load->database('db_sinad', TRUE);
parent::__construct();
}
function getInfoUsuario($id)
{
$sql = "SELECT * FROM tb_usuario WHERE id='".$id."' AND flg=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
function Get_user($id,$pass)
{
$sql = "SELECT * FROM tb_usuarios WHERE dni='".$id."' AND contraseña='". sha1($pass)."' AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
function buscaDni($id){
$sql = "SELECT * FROM tb_usuario WHERE nroDoc='".$id."' AND flg=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
}<file_sep>/app/views/usuario/usuario.php
<!DOCTYPE html>
<html lang="en" class="h-100">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Ugel 03 - Mesa de Partes Virtual</title>
<link href="<?php echo site_resource('mdp')?>/css/style.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.lineicons.com/2.0/LineIcons.css">
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo site_resource('mdp')?>/images/logo-full.png">
<script src="<?php echo site_resource('mdp')?>/js/plugins/jquery-3.3.1.min.js"></script>
</head>
<script type="text/javascript">
function soloNumeros(e)
{
var key = window.Event ? e.which : e.keyCode
return ((key >= 48 && key <= 57) || (key==8))
}
$(window).resize(function() {
$('#afr-cmessage').css({
left: ($(window).width() - $('#afr-cmessage').outerWidth(true))/2,
top: ($(window).height() - $('#afr-cmessage').outerHeight(true))/2
});
});
$(function(){
if(<?=$data_usuario->idTipPer?> == "1"){
//document.getElementById('DivapPaterno').style.display='block';
//document.getElementById('DivapMaterno').style.display='block';
document.getElementById('tipoPersona').placeholder="PERSONA NATURAL";
}
if(<?=$data_usuario->idTipPer?> == "2"){
document.getElementById('lblnroDoc').innerHTML="NUMERO DE R.U.C";
document.getElementById('DivapPaterno').style.display='none';
document.getElementById('DivapMaterno').style.display='none';
document.getElementById('tipoPersona').placeholder="PERSONA JURIDICA";
}
if(<?=$data_usuario->idTipPer?> == "3"){
document.getElementById('lblnroDoc').innerHTML="CODIGO MODULAR Y/O LOCAL";
document.getElementById('lblNombre').innerHTML="NOMBRE INSTITUCION EDUCATIVA";
document.getElementById('DivapPaterno').style.display='none';
document.getElementById('DivapMaterno').style.display='none';
document.getElementById('tipoPersona').placeholder="INSTITUCION EDUCATIVA";
if(<?=$data_usuario->idCargo?> == "12"){
document.getElementById('DivCargo').style.display='block';
}
}
if(<?=$data_usuario->idTipPer?> == "4"){
document.getElementById('lblnroDoc').innerHTML="D.N.I";
//document.getElementById('DivapPaterno').style.display='block';
//document.getElementById('DivapMaterno').style.display='block';
document.getElementById('tipoPersona').placeholder="MENOR DE EDAD";
}
})
$(function(){
$('#comunicadoadjudicacion').modal('show');
$('#show').mousedown(function(){
$('#password1').removeAttr('type');
});
$('#show').mouseup(function(){
$('#password1').attr('type','password');
});
$('#show').mousedown(function(){
$('#password2').removeAttr('type');
});
$('#show').mouseup(function(){
$('#password2').attr('type','password');
});
$("#cbDepartamento").change(function(){
$("#cbDepartamento option:selected").each(function() {
depa_id = $('#cbDepartamento').val();
$.post(
"<?php echo(site_url("Login/getprovincia"))?>",
{depa_id:depa_id},
function(data)
{
$("#cbProvincia").html(data);
}
);
});
});
$("#cbProvincia").change(function(){
$("#cbProvincia option:selected").each(function() {
id_prov = $('#cbProvincia').val();
$.post(
"<?php echo(site_url("Login/getdistrito"))?>",
{id_prov:id_prov},
function(data)
{
$("#cbDistrito").html(data);
}
);
});
});
$("#ap-frmActualizacion").validate({
errorElement: "span",
errorClass: "afr-error",
errorPlacement: function(error, element) {},
submitHandler: function(forms) {
enviarFormDatosPersonales()
}
})
$("#afr-btnclose").click(function() {
$("#afr-cmessage").fadeOut(500, function() {
$("#afr-overlay").fadeOut(700);
});
});
$('#afr-cmessage').css({
left: ($(window).outerWidth() - $('#afr-cmessage').outerWidth(true)) / 2,
top: ($(window).outerHeight() - $('#afr-cmessage').outerHeight(true)) / 2
});
setTimeout(function() {
$("#afr-msg").fadeOut(12000);
}, 1800);
$("#ap-frmActualizacion").validate({
rules: {
userLogin: "required",
userLogin: {
required: true,
email: true
}
},
messages: {
userLogin: "Error en Nombre."
},
errorElement: "span",
errorClass: "afr-error",
errorPlacement: function(error, element) {},
submitHandler: function(forms) {
enviarFormDatosPersonales();
}
})
})
function enviarFormDatosPersonales__() {
var datastring = $("#ap-frmActualizacion").serialize();
$(".loader").css("display", "block");
$(".alert-success").css("display", "none");
$(".alert-danger").css("display", "none");
$.ajax({
url: $("#ap-frmActualizacion").attr('action'),
method: "POST",
data: datastring,
dataType: "JSON",
beforeSend: function() {
},
success: function(data) {
switch (data.error) {
case 0:
$(".alert-success").text(data.msg);
$(".alert-success").css("display", "block");
$(".alert-danger").css("display", "none");
$(".loader").css("display", "none");
break;
case 1:
$(".alert-danger").text(data.msg);
$(".alert-danger").css("display", "block");
$(".alert-success").css("display", "none");
$(".loader").css("display", "none");
break;
case 2:
$(".alert-danger").text(data.msg);
$(".alert-danger").css("display", "block");
$(".alert-success").css("display", "none");
$(".loader").css("display", "none");
break;
case 3:
$(".alert-danger").text(data.msg);
$(".alert-danger").css("display", "block");
$(".alert-success").css("display", "none");
$(".loader").css("display", "none");
break;
default:
}
if (data.error == 3) {
} else {
}
}
})
}
function enviarFormDatosPersonales() {
var datastring = $("#ap-frmActualizacion").serialize();
$.ajax({
url: $("#ap-frmActualizacion").attr('action'),
method: "POST",
data: datastring,
dataType: "JSON",
beforeSend: function() {
},
success: function(data) {
switch (data.resp) {
case 100:
$(this).closest('form').find("input[type=text]").val("");
alert(data.text);
break;
case 10:
alert(data.text);
break;
default:
// code block
}
}
})
}
</script>
<style>
.Contra{
position: relative;
}
.Contra i{
position: absolute;
right:0;
margin-right:15px;
top:50px;
width:80px;
height:55px;
color: black;
text-align: center;
font-size: 15px;
}
</style>
<body>
<!--- MODAL DE AVISO DE LLENAR CAMPOS DE DATOS -->
<div class="modal fade" id="comunicadoadjudicacion" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">COMUNICADO</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p style="text-align:justify"><b>Lenado de Formulario</b></p>
<p style="text-align:justify">Porfavor debe Completar el formulario de Vivienda ya que contamos con un Courier para poder entregar documentos necesarios y determinar la ubicacion.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
<div id="preloader">
<div class="sk-three-bounce">
<div class="sk-child sk-bounce1"></div>
<div class="sk-child sk-bounce2"></div>
<div class="sk-child sk-bounce3"></div>
</div>
</div>
<div id="main-wrapper">
<div class="nav-header">
<a href="index.html" class="brand-logo">
<img class="logo-abbr" src="<?php echo site_resource('mdp')?>/images/logo.png" alt="">
<!--<img class="logo-abbr" src="./images/logo.png" alt="">-->
</a>
<div class="nav-control">
<div class="hamburger">
<span class="line"></span><span class="line"></span><span class="line"></span>
</div>
</div>
</div>
<!--**********************************
Header start
***********************************-->
<div class="header">
<div class="header-content">
<nav class="navbar navbar-expand">
<div class="collapse navbar-collapse justify-content-between">
<div class="header-left">
<div class="dashboard_bar">
Datos Personales
</div>
</div>
<ul class="navbar-nav header-right">
<li class="nav-item dropdown header-profile">
<a class="nav-link" href="#" role="button" data-toggle="dropdown">
<img src="<?php echo site_resource('mdp')?>/images/default.jpg" width="20" alt="">
<div class="header-info">
<!--<span class="text-black" style="display:none"><?=$data_usuario->nombre?></span>-->
<span class="text-black"><?=$data_usuario->nombre."\n".$data_usuario->apPaterno;?></span>
<p class="fs-12 mb-0">USUARIO</p>
</div>
</a>
<div class="dropdown-menu dropdown-menu-right">
<a href="<?php echo(site_url('Login'))?>" class="dropdown-item ai-icon">
<svg id="icon-logout" xmlns="http://www.w3.org/2000/svg" class="text-danger"
width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
<polyline points="16 17 21 12 16 7"></polyline>
<line x1="21" y1="12" x2="9" y2="12"></line>
</svg>
<span class="ml-2">Cerrar Sesión </span>
</a>
</div>
</li>
</ul>
</div>
</nav>
</div>
</div>
<div class="deznav">
<div class="deznav-scroll">
<ul class="metismenu mm-show" id="menu">
<li class="mm-active">
<a class="has-arrow ai-icon" href="javascript:" aria-expanded="false">
<i class="flaticon-381-networking"></i>
<span class="nav-text">Datos Personales</span>
</a>
<ul class="mm-collapse mm-show" aria-expanded="false">
<li class="mm-active">
<a href="vista-principal-usuario.html" class="mm-active">Perfil</a>
</li>
</ul>
</li>
<li>
<a class="ai-icon" href="tramite-usuario.html" aria-expanded="false">
<i class="flaticon-381-television"></i>
<span class="nav-text">Nuevo Tramite</span>
</a>
</li>
<li>
<a class="ai-icon" href="seguimiento-usuario.html" aria-expanded="false">
<i class="flaticon-381-television"></i>
<span class="nav-text">Seguimiento</span>
</a>
</li>
</ul>
<div class="copyright">
<p><strong>UGEL 03</strong><br>© Derechos Reservados</p>
</div>
</div>
</div>
<div class="content-body">
<div class="container-fluid">
<div class="page-titles">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="javascript:">Datos Personales</a></li>
<li class="breadcrumb-item active"><a href="javascript:">Perfil</a></li>
</ol>
</div>
<div class="row">
<div class="col-xl-12 col-lg-12">
<div class="card">
<div class="card-header">
<h3 class="fs-24 text-black font-w600 mr-auto mb-2 pr-3">Perfil</h3>
<!--a href="javascript:" class="btn btn-dark light btn-rounded mr-3 mb-2">Cancelar</a>
<a href="javascript:" class="btn btn-primary btn-rounded mb-2">Guardar Cambios</a>
<div class="text-center mt-1">
<button type="submit" class="btn btn-primary btn-rounded mb-2">
<i class="fa fa-check color-info"></i> Guardar Cambios
</button>
</div>-->
</div>
<div class="card-body">
<form id="ap-frmActualizacion" name="ap-frmActualizacion" action="<?php echo(site_url('Login/enviarActualizarDatos'))?>" method="POST" enctype="multipart/form-data" >
<div class="mb-5">
<div class="title mb-4">
<span class="fs-18 text-black font-w600">Datos Personales</span>
</div>
<div class="row">
<div class="col-xl-3 col-sm-6" id="DivTipoPersona">
<div class="form-group">
<label class="font-weight-bold">TIPO</label>
<input class='form-control' type='text' id='tipoPersona' name='tipoPersona' placeholder="TIPO PERSONA" disabled>
</div>
</div>
<!--- DIV DE PRUEBA PARA JALAR EL NUMERO DE TIPO DE PERSONA --->
<div class="col-xl-3 col-sm-6" id="DivTipoPersona1" style="display: none;" >
<div class="form-group">
<label class="font-weight-bold">TIPO PERSONA</label>
<input class='form-control' type='text' id='tipoPersona1' name='tipoPersona1' value="<?=$data_usuario->idTipPer?>" disabled>
</div>
</div>
<div class="col-xl-3 col-sm-6" id="DivNumeroDocumento">
<div class="form-group">
<label class='font-weight-bold' id="lblnroDoc">NUMERO DE DOCUMENTO</label>
<input class='form-control' type='text' id='nroDocumento' name='nroDocumento' value="<?=$data_usuario->nroDocumento?>" disabled>
</div>
</div>
<div class="col-xl-3 col-sm-6" id="DivNombres">
<div class="form-group">
<label class="font-weight-bold" id="lblNombre">NOMBRES</label>
<input class='form-control' type='text' id='nombre' name='nombre' value="<?=$data_usuario->nombre?>" disabled>
</div>
</div>
<div class="col-xl-3 col-sm-6" id="DivapPaterno">
<div class="form-group">
<label class="font-weight-bold">APELLIDO PATERNO</label>
<input class='form-control' type='text' id='apPaterno' name='apPaterno' value="<?=$data_usuario->apPaterno?>" disabled>
</div>
</div>
<div class="col-xl-3 col-sm-6" id="DivapMaterno">
<div class="form-group">
<label class="font-weight-bold">APELLIDO MATERNO</label>
<input class='form-control' type='text' id='apMaterno' name='apMaterno' value="<?=$data_usuario->apMaterno?>" disabled>
</div>
</div>
<div class="col-xl-3 col-sm-6" id="DivCargo" style="display: none;">
<div class="form-group">
<label class="font-weight-bold">CARGO</label>
<input class='form-control' type='text' id='cargo' name='cargo' value="<?=$data_usuario->descripcion_cargo?>" disabled>
</div>
</div>
<div class="col-xl-3 col-sm-6" >
<div class="form-group">
<label class="font-weight-bold">CELULAR</label>
<input class='form-control' type='phone' onkeypress="return soloNumeros(event);" maxlength="9" id='celular' name='celular' style='color:black;' value="<?=$data_usuario->celular?>">
</div>
</div>
<div class="col-xl-3 col-sm-6" id="CodModular">
<div class="form-group">
<label class="font-weight-bold">CORREO ELECTRONICO</label>
<input class='form-control' type='text' id='correo' name='correo' style='color:black;' value="<?=$data_usuario->correo?> ">
</div>
</div>
<div class="col-xl-3 col-sm-6 Contra" >
<div class="form-group">
<label class="font-weight-bold">CONTRASEÑA</label> <i class="fa fa-eye" id="show"></i>
<input class='form-control' maxlength="6" type='password' id='password1' name='password1' style='color:black;' value="<?=$data_usuario->pass?>">
</div>
</div>
<div class="col-xl-3 col-sm-6 Contra" >
<div class="form-group">
<label class="font-weight-bold">CONFIRMAR CONTRASEÑA</label>
<input class='form-control' maxlength="6" type='password' id='password2' name='password2' style='color:black;' value="<?=$data_usuario->pass?>">
</div>
</div>
</div>
</div>
<!--------------------- DATOS DE DOMICILIO ----------------->
<div class="mb-5">
<div class="title mb-4">
<span class="fs-18 text-black font-w600">Dirección</span>
</div>
<div class="row">
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold" for="cbDepartamento">Departamento</label>
<?php
echo "<select class='form-control' id='cbDepartamento' name='cbDepartamento' required='required' >";
if (count($ubicacion)) {
echo "<option value='0'>[--Seleccione--]</option>";
foreach ($ubicacion as $list) {
echo "<option value='". $list['idDepa'] . "'>" . $list['departamento'] . "</option>";
}
}
echo "</select>";
?>
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold" >Provincia</label>
<select class="form-control" data-width="100%" id="cbProvincia" name="cbProvincia">
<option value="" >[--Seleccione--]</option>
</select>
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Distrito</label>
<select class="form-control" data-width="100%" name="cbDistrito" id="cbDistrito">
<option value="" selected="selected">[--Seleccione--]</option>
</select>
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Tipo de Vía</label>
<?php
echo "<select class='form-control' id='cbVia' name='cbVia'>";
if (count($Via)) {
echo "<option value=''>[--Seleccione--]</option>";
foreach ($Via as $list) {
echo "<option value='". $list['idVia'] . "'>" . $list['descripcion'] . "</option>";
}
}
echo "</select>";
?>
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Tipo de Zona</label>
<?php
echo "<select class='form-control' id='cbZona' name='cbZona'>";
if (count($Zona)) {
echo "<option value=''>[--Seleccione--]</option>";
foreach ($Zona as $list) {
echo "<option value='". $list['idZona'] . "'>" . $list['descripcion'] . "</option>";
}
}
echo "</select>";
?>
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Nombre de la Vía</label>
<input type="text" class="form-control" id="txtvia" name="txtvia">
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Nombre de la Zona</label>
<input type="text" class="form-control" id="txtzona" name="txtzona">
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Referencia</label>
<input type="text" class="form-control" id="txtreferencia" name="txtreferencia">
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Nro Inmueble</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Block</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Piso</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Manzana</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Lote</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-xl-4 col-sm-6">
<div class="form-group">
<label class="font-weight-bold">Kilometro</label>
<input type="text" class="form-control">
</div>
</div>
</div>
<div class="text-right ">
<button type="submit" class="btn btn-primary btn-rounded mr-3 mb-2">
<i class="fa fa-check color-info"></i> Guardar Cambios
</button>
<button type="submit" class="btn btn-dark light btn-rounded mr-3 mb-2">
Cancelar
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="copyright">
<p><strong>Unidad de Gestión Educativa Local N° 3</strong><br>© Derechos Reservados</p>
</div>
</div>
</div>
<script src="<?php echo site_resource('mdp')?>/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/vendor/global/global.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/custom.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/deznav-init.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/plugins/bootstrap.bundle.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/jquery.validate.min.js"></script>
</body>
</html>
<file_sep>/app/views/login/registro2.php
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Reasignación | Ugel03 </title>
<link href="https://fonts.googleapis.com/css?family=Nunito:300,400,400i,600,700,800,900" rel="stylesheet" />
<link href="<?php echo site_resource('adjudicacion')?>/css/themes/lite-blue.min.css" rel="stylesheet" />
<link href="<?php echo site_resource('adjudicacion')?>/css/plugins/perfect-scrollbar.min.css" rel="stylesheet" />
<script src="<?php echo site_resource('adjudicacion')?>/js/plugins/jquery-3.3.1.min.js"></script>
<script src="<?php echo site_resource('admin') ?>/js/jquery.validate.min.js"></script>
<link rel="icon" type="image/png" sizes="32x32" href="<?php echo site_resource('adjudicacion') ?>/icon/adjudicaciones.png">
<script src="https://www.google.com/recaptcha/api.js?render=6Ld3b9EZAAAAAIIrnNIJsV1bRdL-ES_muj_fDSa3"></script>
<script>
$(function() {
$('#condiciones').click(function() {
if ($(this).is(':checked')) {
$("#resultadocheck").val(1);
}else{
$("#resultadocheck").val(0);
}
});
$('#panelCui [data-toggle="tooltip"]').tooltip({
animated: 'fade',
placement: 'bottom',
html: true
});
});
</script>
<style>
.layout-horizontal-bar .main-content-wrap {
margin-top: 110px !important;
}
.afr-error{
background: #ffe1e1;
}
.layout-horizontal-bar .main-header {
background: #003473 !important;
}
.mb-2{
color:white;
}
@media (max-width: 4268px) {
.mb-2:after {
content:'REASIGNACIÓN DOCENTE NO PRESENCIAL - UGEL03 ';
font-size:20px;
}
.layout-horizontal-bar .header-topnav {
background-color: #FFFFFF;
}
}
@media (max-width: 768px) {
.mb-2:after {
content:'REASIGNACIÓN ONLINE';
}
.layout-horizontal-bar .main-content-wrap {
margin-top: 60px !important;
}
.layout-horizontal-bar .main-header .header-icon {
font-size: 30px;
}
}
@media (max-width: 468px) {
.card-body {
flex: 1 1 auto;
padding: 0.25rem;
}
.col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-auto, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-sm-auto, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-md-auto, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-lg-auto, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl, .col-xl-auto {
position: relative;
width: 100%;
min-height: 1px;
padding-right: 0px;
padding-left: 0px;
}
.col-md-9{
padding-right: 15px !important;
padding-left: 15px ;
text-align: justify;
}
}
.container-fluid {
background-color: #eee !important;
}
.layout-horizontal-bar .header-topnav .topnav a {
color: black!important;
}
.any:hover {
background-color: white;
}
.any2:hover {
color: white !important;
}
.bg-transparent {
text-align: center;
}
.layout-horizontal-bar .header-topnav .topnav a, .layout-horizontal-bar .header-topnav .topnav label {
display: flex;
flex-direction: row;
align-items: center;
padding: 13px 20px;
height: 54px;
font-size: .955rem;
}
</style>
<script type="text/javascript">
var cbo;
var dependencia = [];
$(window).resize(function() {
$('#afr-cmessage').css({
left: ($(window).width() - $('#afr-cmessage').outerWidth(true))/2,
top: ($(window).height() - $('#afr-cmessage').outerHeight(true))/2
});
});
$(function() {
$("#limpiarForm").click(function(){
$("#ap-frmRecamo")[0].reset();
});
$("#enviarForm").click(function(){
document.getElementById('enviarForm').disabled = true;
});
/***************ap-05122018**********************/
$("#coTipoDocumento").change(function() {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if (valueSelected == 1) {
$("#numDocumento").attr('maxlength', 8);
$("#numDocumento").attr('minlength', 8);
$("#numDocumento").val("");
document.getElementById('numCui').disabled = false;
}else{
$("#numDocumento").attr('maxlength', 11);
$("#numDocumento").attr('minlength', 11);
$("#numDocumento").val("");
$("#numCui").val("");
document.getElementById('numCui').disabled = true;
}
});
$("#coEtapa").change(function() {
$("#coEtapa option:selected").each(function() {
etapa = $('#coEtapa').val();
$.post("<?php echo(site_url('homeAdjudicaciones/getfase'))?>", {etapa:etapa},
function(data) {
$("#coFase").html(data);
});
});
});
$("#cboModalidad").change(function() {
$("#cboModalidad option:selected").each(function() {
modalidad = $('#cboModalidad').val();
$.post("<?php echo(site_url('homeAdjudicaciones/getnivel'))?>", {modalidad:modalidad},
function(data) {
$("#cboNivel").html(data);
if (modalidad == 0) {
$("#cboNivel").val(0);
document.getElementById('cboNivel').disabled = true;
} else{
document.getElementById('cboNivel').disabled = false;
}
});
});
});
$("#cboCargo").change(function() {
$("#cboCargo option:selected").each(function() {
cargo = $('#cboCargo').val();
$.post("<?php echo(site_url('homeAdjudicaciones/getcurricular'))?>", {cargo:cargo},
function(data) {
$("#cboCurricular").html(data);
document.getElementById('cboCurricular').disabled = false;
});
});
});
$("#cboNivel").change(function() {
$("#cboNivel option:selected").each(function() {
nivel = $('#cboNivel').val();
cargo = $('#cboCargo').val();
if(cargo == 7 || cargo == 9){
if(nivel == 5 || nivel == 6 || nivel == 7 || nivel == 8){
$.post("<?php echo(site_url('homeAdjudicaciones/getcurricular2'))?>", {nivel:nivel},
function(data) {
$("#cboCurricular").html(data);
document.getElementById('cboCurricular').disabled = false;
});
}else{
if(cargo==7){
$("#cboCurricular").val(19);
document.getElementById('cboCurricular').disabled = false;
}
if(cargo==9){
$("#cboCurricular").val(21);
document.getElementById('cboCurricular').disabled = false;
}
}
}
});
});
/***************************************************/
$("#ap-frmRecamo").validate({
errorElement: "span",
errorClass: "afr-error",
errorPlacement: function(error, element) {},
submitHandler: function(forms) {
//$('.afr-btn').attr("disabled","disabled");
// forms.submit();
enviarFormDatosPersonales()
}
})
$("#afr-btnclose").click(function() {
$("#afr-cmessage").fadeOut(500, function() {
$("#afr-overlay").fadeOut(700);
});
});
$('#afr-cmessage').css({
left: ($(window).outerWidth() - $('#afr-cmessage').outerWidth(true)) / 2,
top: ($(window).outerHeight() - $('#afr-cmessage').outerHeight(true)) / 2
});
setTimeout(function() {
$("#afr-msg").fadeOut(12000);
}, 1800);
$("#ap-frmLogin").validate({
rules: {
userLogin: "required",
userLogin: {
required: true,
email: true
}
},
errorElement: "span",
errorClass: "afr-error",
errorPlacement: function(error, element) {},
submitHandler: function(forms) {
enviarLogueo();
//$('.afr-btn').attr("disabled","disabled");
// forms.submit();
}
})
})
function enviarFormDatosPersonales() {
var datastring = $("#ap-frmRecamo").serialize();
$(".loader").css("display", "block");
$(".alert-success").css("display", "none");
$(".alert-danger").css("display", "none");
$.ajax({
url: $("#ap-frmRecamo").attr('action'),
method: "POST",
data: datastring,
dataType: "JSON",
beforeSend: function() {
// $("#in-pogress").html("Processing daata");
},
success: function(data) {
// alert(data.msg);
switch (data.error) {
case 0:
$(".alert-success").text(data.msg);
$(".alert-success").css("display", "block");
$(".alert-danger").css("display", "none");
$(".loader").css("display", "none");
/*
<?php $this->session->sess_destroy(); ?>
location.reload();*/
break;
case 1:
$(".alert-danger").text(data.msg);
$(".alert-danger").css("display", "block");
$(".alert-success").css("display", "none");
$(".loader").css("display", "none");
break;
case 2:
$(".alert-danger").text(data.msg);
$(".alert-danger").css("display", "block");
$(".alert-success").css("display", "none");
$(".loader").css("display", "none");
break;
case 3:
$(".alert-danger").text(data.msg);
$(".alert-danger").css("display", "block");
$(".alert-success").css("display", "none");
$(".loader").css("display", "none");
break;
default:
// code block
}
if (data.error == 3) {
} else {
}
}
})
}
function enviarContra() {
var datastring = $("#ap-frmLogin").serialize();
$.ajax({
url: $("#ap-frmLogin").attr('action'),
method: "POST",
data: datastring,
dataType: "JSON",
beforeSend: function() {
// $("#in-pogress").html("Processing daata");
},
success: function(data) {
switch (data.resp) {
case 0:
$(".alert-success").text(data.msg);
$(".alert-success").css("display", "block");
$(".alert-danger").css("display", "none");
$(".loader").css("display", "none");
break;
case 1:
$(".alert-danger").text(data.msg);
$(".alert-danger").css("display", "block");
$(".alert-success").css("display", "none");
$(".loader").css("display", "none");
break;
case 100:
$(this).closest('form').find("input[type=text]").val("");
window.location.href = "<?php echo site_url('adjudicaciones') ?>";
break;
case 10:
alert(data.text);
break;
default:
// code block
}
}
})
}
function countChar(val) {
var len = val.value.length;
if (len >= 500) {
val.value = val.value.substring(0, 500);
} else {
$('#charNum').text(500 - len);
}
};
</script>
<script>
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
// Added to allow decimal, period, or delete
//if (charCode == 110 || charCode == 190 || charCode == 46)
// return true;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function isCharKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return true;
return false;
}
function isCharKey2(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122))
return false;
return true;
}
</script>
<script>
$(document).ready(function() {
//$('#comunicadoadjudicacion').modal('show');
});
</script>
</head>
<body>
<div class="modal fade" id="comunicadoadjudicacion" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">COMUNICADO</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<a target="_blank" href="<?php echo site_resource('adjudicacion') ?>/comunicados/Comunicado55.pdf" >
<img class="img-fluid" src="<?php echo site_resource('adjudicacion') ?>/comunicados/comunicado55.PNG"></img>
</a>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
<div class="app-admin-wrap layout-horizontal-bar">
<div class="main-header">
<div class="logo"><img src="<?php echo site_resource('adjudicacion')?>/images/logo.png" alt=""></div>
<div class="menu-toggle">
<div></div>
<div></div>
<div></div>
</div>
<div class="d-flex align-items-center">
<h5 class="mb-2 t-font-boldest"></h5>
</div>
<div style="margin: auto"></div>
<div class="header-part-right">
</div>
</div>
<!-- header top menu end-->
<div class="horizontal-bar-wrap">
<div class="header-topnav">
<div class="container-fluid">
<div class="topnav rtl-ps-none" id="" data-perfect-scrollbar="" data-suppress-scroll-x="true">
<ul class="menu float-left">
<!--
<li>
<div>
<div class="any">
<a class="any2" href="<?php echo(site_url('homeAdjudicaciones'))?>"><i class="nav-icon mr-2 i-Shop-4"></i> Inicio</a>
</div>
</div>
</li>
<li>
<div>
<div class="any">
<a class="any2" href="#"><i class="i-Professor"> </i> Resultados</a>
</div>
</div>
</li>
<li>
<div>
<div class="any">
<a class="any2" href="#"><i class="i-Computer-Secure"> </i> Cronograma</a>
</div>
</div>
</li>
<li>
<div>
<div class="any">
<a class="any2" href="<?php echo(site_url('resultados'))?>"><i class="nav-icon i-File-Horizontal-Text"></i> Plazas</a>
</div>
</div>
</li>
<li>
<div>
<div class="any">
<a class="any2" href="<?php echo(site_url('cronograma"'))?>"><i class="nav-icon i-Checked-User"> </i> Adjudicados</a>
</div>
</div>
</li>
<li>
<div>
<div class="any">
<a class="any2" href="<?php echo(site_url('cronograma"'))?>"><i class="nav-icon i-download"> </i> Tutorial</a>
</div>
</div>
</li> -->
<li>
<div>
<div class="any">
<a class="any2" target="_blank" href="<?php echo site_resource('pdf') ?>/Guía_de_Aplicativo_Reasignacion_2020.pdf"><i class="nav-icon i-download"> </i> GUÍA PARA EL REGISTRO Y ENVÍO DE DOCUMENTACIÓN</a>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- =============== Horizontal bar End ================-->
<div class="main-content-wrap d-flex flex-column">
<!-- ============ Body content start ============= -->
<div class="main-content">
<div class="2-columns-form-layout">
<div>
<div class="row">
<div class="col-lg-12">
<div class="card text-left">
<div class="card-body">
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item"><a class="nav-link " id="home-basic-tab"
data-toggle="tab" href="#registro" role="tab"
aria-controls="registro" aria-selected="false">Registrarse</a></li>
<li class="nav-item"><a class="nav-link active show " id="contact-basic-tab"
data-toggle="tab" href="#contactBasic" role="tab"
aria-controls="contactBasic" aria-selected="true">Recuperar contraseña</a></li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade " id="registro" role="tabpanel"
aria-labelledby="home-basic-tab">
<!-- REGISTRAR -->
<div class="card-header bg-transparent">
<h3 class="card-title"
style="margin-bottom: 0rem !important ; font-size: 1rem !important;">
Datos Personales</h3>
</div>
<form id="ap-frmRecamo" name="ap-frmRecamo" action="<?php echo(site_url('homeAdjudicaciones/enviarRegistroDatos'))?>" method="post" enctype="multipart/form-data">
<div class="card-body">
<div class="form-group row">
<label
class="ul-form__label ul-form--margin col-lg-1 col-form-label"
for="staticEmail19">TIPO DE PERSONA:</label>
<div class="col-lg-2">
<div class="input-group-prepend">
<div class="input-group-text bg-transparent"><i class="i-Checked-User"></i>
</div>
<select class="form-control valid" id="cboTipoPersona" name="cboTipoPersona" required="required" aria-required="true" aria-invalid="false"><option value="1">Persona Natural</option></select>
</div>
<small class="ul-form__text form-text" id="passwordHelpBlock"> Seleccione tipo de persona </small>
</div>
<label
class="ul-form__label ul-form--margin col-lg-1 col-form-label"
for="staticEmail20">DOCUMENTO :</label>
<div class="col-lg-2">
<div class="input-group-prepend">
<div class="input-group-text bg-transparent"><i class="i-id-card"></i>
</div>
<select class="form-control valid" required="required" id="coTipoDocumento" name="coTipoDocumento" required="required" aria-required="true" aria-invalid="false">
<option value="0">[--Seleccione--] </option>
<option value="1">DNI/LE</option>
<option value="2">Carnet de Extranjería</option>
</select>
</div>
<small class="ul-form__text form-text" id="passwordHelpBlock"> Seleccione tipo de documento </small>
</div>
<label
class="ul-form__label ul-form--margin col-lg-1 col-form-label"
for="staticEmail21">NUMERO DOCUMENTO:</label>
<div class="col-lg-3">
<div class="input-group mb-3">
<div class="input-group-prepend">
<div class="input-group-text bg-transparent"><i
class="i-File-Horizontal-Text"></i></div>
</div>
<input type="text" class="form-control" id="numDocumento" required="required" name="numDocumento" placeholder="Ingrese número de documento" minlength="8" maxlength="8" onkeypress="return isNumberKey(event)">
</div><small class="ul-form__text form-text"
id="passwordHelpBlock">
* Ingrese número de documento </small>
</div>
<div id="panelCui" class="">
<a class="ul-form__label ul-form--margin col-lg-1 col-form-label" data-toggle="tooltip" title="<img src='http://sistemas01.ugel03.gob.pe/adjudicacionesOnline/resource/adjudicacion/images/cui.png' />">
<i class="nav-icon mr-1 i-Cursor-Click"></i>CUI
</a>
</div>
<div class="col-lg-1">
<div class="input-group mb-3">
<input type="text" class="form-control" id="numCui" required="required" name="numCui" placeholder="CUI" minlength="1" maxlength="1" onkeypress="return isNumberKey(event)">
</div><small class="ul-form__text form-text"
id="passwordHelpBlock">
* Ingrese número de CUI
</small>
</div>
</div>
<div class="custom-separator"></div>
<div class="form-group row">
<label
class="ul-form__label ul-form--margin col-lg-1 col-form-label"
for="staticEmail22">NOMBRES:</label>
<div class="col-lg-3">
<div class="input-right-icon">
<input type="text" class="form-control" id="txtnombres" required="required" name="txtnombres" placeholder="Ingrese nombres completos" maxlength="40" onkeypress="return isCharKey(event)">
<span
class="span-right-input-icon"><i
class="ul-form__icon i-Male"></i></span>
</div>
<small
class="ul-form__text form-text" id="passwordHelpBlock">
* Campo Obligatorio
</small>
</div>
<label
class="ul-form__label ul-form--margin col-lg-1 col-form-label"
for="staticEmail23">APELLIDO PATERNO:</label>
<div class="col-lg-3">
<div class="input-right-icon">
<input type="text" class="form-control" id="txtapePaterno" required="required" name="txtapePaterno" placeholder="Ingrese apellido paterno" maxlength="30" onkeypress="return isCharKey(event)">
<span
class="span-right-input-icon"><i
class="ul-form__icon i-Business-Woman"></i></span>
</div>
<small class="ul-form__text form-text"
id="passwordHelpBlock">
* Campo Obligatorio
</small>
</div>
<label
class="ul-form__label ul-form--margin col-lg-1 col-form-label"
for="staticEmail24">APELLIDO MATERNO:</label>
<div class="col-lg-3">
<div class="input-right-icon">
<input type="text" class="form-control" id="txtapeMaterno" required="required" name="txtapeMaterno" placeholder="Ingrese apellido materno" maxlength="30" onkeypress="return isCharKey(event)">
<span
class="span-right-input-icon"><i
class="ul-form__icon i-Administrator"></i></span>
</div>
<small class="ul-form__text form-text"
id="passwordHelpBlock">
* Campo Obligatorio
</small>
</div>
</div>
<div class="custom-separator"></div>
<div class="form-group row">
<label class="ul-form__label ul-form--margin col-lg-1 col-form-label" for="staticEmail20"> ETAPA :</label>
<div class="col-lg-2">
<!-- <div class="input-group mb-2"> -->
<div class="input-group-prepend">
<div class="input-group-text bg-transparent"><i class="i-globe"></i>
</div>
<!-- </div> -->
<?php echo "<select class='form-control' id='coEtapa' name='coEtapa' required='required' >";
if (count($etapa)) {
echo "<option value='0'>[--Seleccione--]</option>";
foreach ($etapa as $list) {
echo "<option value='". $list['id_etapa'] . "'>" . $list['descripcion_etapa'] . "</option>";
}
}
echo "</select>";
?>
</div>
<small class="ul-form__text form-text" id="passwordHelpBlock"> * Seleccione etapa
</small>
</div>
<label class="ul-form__label ul-form--margin col-lg-1 col-form-label" for="staticEmail20"> FASE :</label>
<div class="col-lg-1">
<div class="input-group-prepend">
<div class="input-group-text bg-transparent"><i class="i-flag"></i>
</div>
<?php echo "<select class='form-control' id='coFase' name='coFase' required='required' >";
if (count($fase)) {
echo "<option value='0'>[--Seleccione--]</option>";
foreach ($fase as $list) {
echo "<option value='". $list['id_fase'] . "'>" . $list['descripcion_fase'] . "</option>";
}
}
echo "</select>";
?>
</div>
<small class="ul-form__text form-text" id="passwordHelpBlock"> * Seleccione fase
</small>
</div>
<label class="ul-form__label ul-form--margin col-lg-1 col-form-label" for="staticEmail20"> CAUSAL :</label>
<div class="col-lg-2">
<div class="input-group-prepend">
<div class="input-group-text bg-transparent"><i class="i-shield"></i>
</div>
<select class="form-control valid" required="required" id="coCausa" name="coCausa" aria-required="true" aria-invalid="false">
<option value="0">[--Seleccione--] </option>
<option value="1">Interés Personal</option>
<option value="2">Unidad Familiar</option>
</select>
</div>
<small class="ul-form__text form-text" id="passwordHelpBlock"> * Seleccione causal
</small>
</div>
<label class="ul-form__label ul-form--margin col-lg-1 col-form-label" for="staticEmail20"> CARGO :</label>
<div class="col-lg-3">
<div class="input-group-prepend">
<div class="input-group-text bg-transparent"><i class="i-Professor"></i>
</div>
<?php echo "<select class='form-control' id='cboCargo' name='cboCargo' required='required' >";
if (count($cargo)) {
echo "<option value='0'>[--Seleccione--]</option>";
foreach ($cargo as $list) {
echo "<option value='". $list['id_cargo'] . "'>" . $list['descripcion_cargo'] . "</option>";
}
}
echo "</select>";
?>
</div>
<small class="ul-form__text form-text" id="passwordHelpBlock"> * Seleccione cargo
</small>
</div>
</div>
<div class="custom-separator"></div>
<div class="form-group row">
<label class="ul-form__label ul-form--margin col-lg-1 col-form-label" for="staticEmail20"> MODALIDAD:</label>
<div class="col-lg-3">
<div class="input-group-prepend">
<div class="input-group-text bg-transparent"><i class="i-Suitcase"></i>
</div>
<?php echo "<select class='form-control' id='cboModalidad' name='cboModalidad' required='required' >";
if (count($modalidad)) {
echo "<option value='0'>[--Seleccione--]</option>";
foreach ($modalidad as $list) {
echo "<option value='". $list['id_modalidad'] . "'>" . $list['descripcion_modalidad'] . "</option>";
}
}
echo "</select>";
?>
</div>
<small class="ul-form__text form-text" id="passwordHelpBlock"> * Seleccione modalidad
</small>
</div>
<label class="ul-form__label ul-form--margin col-lg-1 col-form-label" for="staticEmail20"> NIVEL:</label>
<div class="col-lg-3">
<div class="input-group-prepend">
<div class="input-group-text bg-transparent"><i class="i-Loading-3"></i>
</div>
<?php echo "<select disabled class='form-control' id='cboNivel' name='cboNivel' required='required' >";
if (count($nivel)) {
echo "<option value='0'>[--Seleccione--]</option>";
foreach ($nivel as $list) {
echo "<option value='". $list['id_nivel'] . "'>" . $list['descripcion_nivel'] . "</option>";
}
}
echo "</select>";
?>
</div>
<small class="ul-form__text form-text" id="passwordHelpBlock"> * Seleccione nivel
</small>
</div>
<label class="ul-form__label ul-form--margin col-lg-1 col-form-label" for="staticEmail20"> ÁREA CURRICULAR :</label>
<div class="col-lg-3">
<div class="input-group-prepend">
<div class="input-group-text bg-transparent"><i class="i-book"></i>
</div>
<?php echo "<select disabled class='form-control' id='cboCurricular' name='cboCurricular' required='required' >";
if (count($curricular)) {
echo "<option value='0'>[--Seleccione--]</option>";
foreach ($curricular as $list) {
echo "<option value='". $list['id_curricular'] . "'>" . $list['descripcion_curricular'] . "</option>";
}
}
echo "</select>";
?>
</div>
<small class="ul-form__text form-text" id="passwordHelpBlock"> * Seleccione área curricular
</small>
</div>
</div>
<div class="custom-separator"></div>
<div class="form-group row">
<label
class="ul-form__label ul-form--margin col-lg-1 col-form-label"
for="staticEmail25">CELULAR:</label>
<div class="col-lg-2">
<div class="input-right-icon">
<input type="text" class="form-control" required="required" id="numCelular" name="numCelular" minlength="9" maxlength="9" placeholder="Número celular" onkeypress="return isNumberKey(event)">
<span
class="span-right-input-icon"><i
class="ul-form__icon i-Telephone"></i></span>
</div><small class="ul-form__text form-text"
id="passwordHelpBlock">
* Campo Obligatorio
</small>
</div>
<label
class="ul-form__label ul-form--margin col-lg-1 col-form-label"
for="staticEmail25">CORREO:</label>
<div class="col-lg-3">
<div class="input-right-icon">
<input type="email" class="form-control" id="txtemail" name="txtemail" required="required" placeholder="Ingrese correo" maxlength="80">
<span
class="span-right-input-icon"><i
class="ul-form__icon i-New-Mail"></i></span>
</div><small class="ul-form__text form-text"
id="passwordHelpBlock">
* Campo Obligatorio
</small>
</div>
<label
class="ul-form__label ul-form--margin col-lg-1 col-form-label"
for="staticEmail25">REPETIR CORREO:</label>
<div class="col-lg-3">
<div class="input-right-icon">
<input type="email" class="form-control" id="txtemail2" name="txtemail2" required="required" placeholder="Ingrese correo" maxlength="80">
<span
class="span-right-input-icon"><i
class="ul-form__icon i-New-Mail"></i></span>
</div><small class="ul-form__text form-text"
id="passwordHelpBlock">
* Campo Obligatorio
</small>
</div>
</div>
<div style="display:none;text-align: center;" class="loader loader-bubble loader-bubble-info m-6"></div>
</div>
<label class="checkbox checkbox-outline-success">
<input type="checkbox" id="condiciones" name="condiciones" data-toggle="modal" data-target="#exampleModalLong" ><span>(*)Acepto Terminos y condiciones</span><span class="checkmark"></span>
<input id="resultadocheck" name="resultadocheck" type="hidden" value="0">
<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Terminos y condiciones</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p style="text-align:justify"> Al dar click en este casillero, usted está autorizando </p>
<p style="text-align:justify"><b> Veracidad de la información declara por el administrado</b></p>
<p style="text-align:justify"> Declaro expresamente que la información ingresa en la Plataforma para el proceso de contratación docente 2020 es verdadera y conforme con lo establecido en el artículo 49 del Texto Único Ordenado de la Ley N° 27444, Ley del Procedimiento Administrativo General, y en caso de resultar falsa la información que proporciono, me sujeto a los alcances de lo establecido en el artículo 411 del Código Penal, concordante con el artículo 33 del Texto Único Ordenado de la Ley N° 27444, Ley del Procedimiento Administrativo General; autorizando a efectuar la comprobación de la veracidad de la información declarada en la presente plataforma.</p>
<p style="text-align:justify"><b> Autorización para la notificación al correo electrónico</b> </p>
<p style="text-align:justify">AUTORIZO de forma expresa y conforme a lo dispuesto por el artículo N° 20 del Texto único Ordenando de la Ley N° 27444 – Ley del Procedimiento Administrativo General, aprobado mediante el DECRETO SUPREMO Nº 004-2019-JUS y modificado mediante el Decreto Legislativo N° 1497, a la UNIDAD DE GESTION EDUCATIVA LOCAL 03 – UGEL 03, que me notifique el/los acto(s) administrativo(s), comunicados o documentación adicional que se emitan a consecuencia del proceso de contratación docente 2020 al correo electrónico consignado en presente plataforma; así mismo acuerdo que el acto administrativo, los comunicados o la documentación adicional pueda estar contenida en un archivo adjunto o un enlace web a través del cual se descargará y/o otros mecanismo que garanticen su notificación.</p>
<p style="text-align:justify">Tengo conocimiento que las notificaciones dirigidas a la dirección de mi correo electrónico señalada en la presente Plataforma se entiende válidamente efectuadas cuando la UGEL 03 reciba la respuesta de recepción de la dirección electrónica antes señalada; a través del acuse de recibo, el mismo que dejará constancia del acto de notificación; en concordancia a lo establecido por el artículo 20 del mencionado Texto Único Ordenado, surtiendo efectos el día siguiente que conste haber sido recibido en mi bandeja de entrada, conforme a lo previsto en el numeral 2 del artículo 25 del citado Texto Único Ordenado.</p>
<p style="text-align:justify">
En atención a la presente autorización me comprometo con las siguientes obligaciones:
1. Señalar una dirección de correo electrónica válida, a la cual tenga acceso y que se mantenga activa durante el proceso de contratación docente 2020.
2. Asegurar que la capacidad del buzón de la dirección de correo electrónico permita recibir los documentos a notificar.
3. Revisar continuamente la cuenta de correo electrónico, incluyendo la bandeja de spam o el buzón de correo no deseado.</p>
<p style="text-align:justify">El no tomar conocimiento oportuno de las notificaciones remitidas por la UNIDAD DE GESTION EDUCATIVA LOCAL 03 – UGEL 03, debido al incumplimiento de las presentes obligaciones, constituye exclusiva responsabilidad de mi persona. </p>
<p style="text-align:justify">DECRETO LEGISLATIVO Nº 1497: DECRETO LEGISLATIVO QUE ESTABLECE MEDIDAS PARA PROMOVER Y FACILITAR CONDICIONES REGULATORIAS QUE CONTRIBUYAN A REDUCIR EL IMPACTO EN LA ECONOMÍA PERUANA POR LA EMERGENCIA SANITARIA PRODUCIDA POR EL COVID- 19
Artículo 3.- Incorporación de párrafo en el artículo 20 de la Ley Nº 27444, Ley del Procedimiento Administrativo General
Incorpórase un último párrafo en el artículo 20 de la Ley Nº 27444, Ley del Procedimiento Administrativo General, cuyo texto queda redactado de la manera siguiente:
“Artículo 20.- Modalidades de notificación
(…)</p>
<p style="text-align:justify">El consentimiento expreso a que se refiere el quinto párrafo del numeral 20.4 de la presente Ley puede ser otorgado por vía electrónica.”</p>
<p style="text-align:justify"><b>Autorización para el tratamiento de los datos personal del administrado</b></p>
<p style="text-align:justify">En atención a los dispuesto por la Ley N° 29733, Ley de Protección de Datos Personales y su Reglamento aprobado por Decreto Supremo N° 003-2013-JUS, AUTORIZO a la UNIDAD DE GESTION EDUCATIVA LOCAL 03 – UGEL 03 al tratamiento de mis datos personales, así como cualquier otra información ingresada en la plataforma para el proceso de contratación docente 2020.</p>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
</label>
<div class="card-footer">
<div class="mc-footer">
<div style="display:none" class="alert alert-card alert-success" role="alert"> <strong>Registro Exitoso!</strong> el sistema enviara un correo con los accesos. <button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span></div>
<div style="display:none" class="alert alert-card alert-danger" role="alert"><strong>Ocurrio un error !</strong> vuelva a registrar nuevamente.<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span></div>
<div class="row text-center">
<div class="col-lg-12">
<button id="enviarForm" name="enviarForm" type="submit" value="Enviar" class="btn btn-primary m-1">ENVIAR</button>
<button id="limpiarForm" name="limpiarForm" class="btn btn-outline-secondary m-1" type="button">LIMPIAR</button>
</div>
</div>
</div>
</div>
<input type="hidden" id="token" name="token">
</form>
</div>
<div class="tab-pane fade active show " id="contactBasic" role="tabpanel"
aria-labelledby="contact-basic-tab">
<!-- LOGIN -->
<div class="card-header bg-transparent">
<h3 class="card-title"
style="margin-bottom: 0rem !important;font-size: 1rem !important;">
ENVIAR CONTRASEÑA</h3>
</div>
<form id="ap-frmLogin" name="ap-frmLogin" action="<?php echo(site_url('homeAdjudicaciones2/enviarContra'))?>" method="post" enctype="multipart/form-data">
<div class="card-body">
<div class="form-group row">
<label
class="ul-form__label ul-form--margin col-lg-5 col-form-label"
for="staticEmail6">Correo:</label>
<div class="col-lg-2">
<input class="form-control" id="userLogin" name="userLogin" type="email"
placeholder="" /><small
class="ul-form__text form-text" id="passwordHelpBlock">
Por favor ingrese correo
</small>
</div>
</div>
<div class="row text-center">
<div class="col-lg-12">
<a href="<?php echo(site_url('HomeAdjudicaciones'))?>" class="ul-form__text form-text"> Regresar al login </a>
</div>
</div>
</div>
<div class="card-footer">
<div class="mc-footer">
<div class="row text-center">
<div class="col-lg-12">
<button type="submit" value="Enviar" class="btn btn-primary m-1">ENVIAR</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end of main row -->
</div>
</div><!-- end of main-content -->
</div><!-- Footer Start -->
<div class="flex-grow-1"></div>
<div class="app-footer">
<div class="row">
<div class="col-md-9">
<p><strong>MISIÓN</strong></p>
<p>
Garantizar un servicio educativo de calidad en todos los niveles y modalidades,
fortaleciendo las capacidades de gestión pedagógica y administrativa, impulsando la cohesión
social y promoviendo el aporte de los gobiernos locales e instituciones privadas
especializadas para mejorar la calidad del servicio educativo.
<sunt></sunt>
</p>
</div>
<div class="custom-separator"></div>
<div class="col-md-9">
<p><strong>PROBLEMAS TÉCNICOS</strong></p>
<p>
Numeros de Contacto para problemas técnicos de registro: <b style="color:#ae3e3e">936097738-934871792-922905743-986874528- 902487385</b></br>
<b>*La atención es de 8:00 a 13:00 y 14:00 hasta las 5:00 p.m.</b>
<sunt></sunt>
</p>
</div>
</div>
<div class="footer-bottom border-top pt-3 d-flex flex-column flex-sm-row align-items-center">
<a class="btn btn-primary text-white btn-rounded" href="http://www.ugel03.gob.pe/" target="_blank">
UGEL03</a>
<span class="flex-grow-1"></span>
<div class="d-flex align-items-center">
<img class="logo" src="<?php echo site_resource('adjudicacion')?>/images/logo.png" alt="">
<div>
<p class="m-0">© 2020 ETI | APP</p>
<p class="m-0">Todos los derechos reservados</p>
</div>
</div>
</div>
</div>
<!-- fotter end -->
</div>
</div>
<!-- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -->
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<KEY>', {
action: 'homepage'
}).then(function(token) {
document.getElementById("token").value = token;
});
});
</script>
<script src="<?php echo site_resource('adjudicacion')?>/js/plugins/bootstrap.bundle.min.js"></script>
<script src="<?php echo site_resource('adjudicacion')?>/js/plugins/perfect-scrollbar.min.js"></script>
<script src="<?php echo site_resource('adjudicacion')?>/js/scripts/script.min.js"></script>
<script src="<?php echo site_resource('adjudicacion')?>/js/scripts/sidebar-horizontal.script.js"></script>
</body>
</html>
<file_sep>/app/views/login/home.php
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Mesa de Partes Virtual | Ugel03 </title>
<link href="https://fonts.googleapis.com/css?family=Nunito:300,400,400i,600,700,800,900" rel="stylesheet" />
<link href="<?php echo site_resource('adjudicacion')?>/css/themes/lite-blue.min.css" rel="stylesheet" />
<link href="<?php echo site_resource('adjudicacion')?>/css/plugins/perfect-scrollbar.min.css" rel="stylesheet" />
<script src="<?php echo site_resource('adjudicacion')?>/js/plugins/jquery-3.3.1.min.js"></script>
<script src="<?php echo site_resource('admin') ?>/js/jquery.validate.min.js"></script>
<link href="<?php echo site_resource('mdp')?>/css/style.css" rel="stylesheet" />
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo site_resource('mdp')?>/images/laptop.png">
<script src="https://www.google.com/recaptcha/api.js?render=6LfZBasUAAAAAOJ8aj-pNqZQTFny0QFeH1nN7mHb"></script>
<style>
.container-fluid { background-color: #09bf94 !important; }
.layout-horizontal-bar .main-content-wrap {margin-top: 70px !important;}
.afr-error{ background: #ffe1e1; }
.layout-horizontal-bar .main-header { background:#40189D !important; }
.mb-2{ color:white; }
@media (max-width: 4268px) {
.mb-2:after {
content:'BIENVENIDO A MESA DE PARTES VIRTUAL - UGEL03 ';
font-size:16px;
}
}
.mb-1{ font-size:22px; }
.layout-horizontal-bar .header-topnav .topnav a { color: black!important; }
.any:hover { background-color: white; }
.any2:hover { color: white !important; }
.bg-transparent {text-align: center; }
</style>
</head>
<script type="text/javascript">
var cbo;
var dependencia = [];
$(window).resize(function() {
$('#afr-cmessage').css({
left: ($(window).width() - $('#afr-cmessage').outerWidth(true))/2,
top: ($(window).height() - $('#afr-cmessage').outerHeight(true))/2
});
});
$(function() {
$("#ap-frmLogin").validate({
rules: {
userLogin: "required",
userLogin: {
required: true,
email: false
}
},
errorElement: "span",
errorClass: "afr-error",
errorPlacement: function(error, element) {},
submitHandler: function(forms) {
enviarLogueo();
}
})
});
function enviarLogueo() {
var datastring = $("#ap-frmLogin").serialize();
$.ajax({
url: $("#ap-frmLogin").attr('action'),
method: "POST",
data: datastring,
dataType: "JSON",
beforeSend: function() {
},
success: function(data) {
switch (data.resp) {
case 100:
$(this).closest('form').find("input[type=text]").val("");
window.location.href = "<?php echo site_url('Tramite') ?>";
break;
case 10:
alert(data.text);
break;
default:
}
}
})
}
</script>
<body>
<div class="app-admin-wrap layout-horizontal-bar">
<div class="main-header">
<div class="logo"><img src="<?php echo site_resource('adjudicacion')?>/images/logo.png" alt="">
</div>
<div class="d-flex align-items-center">
<h5 class="mb-2 t-font-boldest"></h5>
</div>
<div style="margin: auto">
</div>
</div>
<!-- =============== Horizontal bar End ================-->
<div class="main-content-wrap d-flex flex-column">
<!-- ============ Body content start ============= -->
<div class="main-content">
<div class="authincation h-100">
<div class="container h-100">
<div class="row justify-content-center h-100 align-items-center">
<div class="col-md-6">
<div class="authincation-content">
<div class="row no-gutters">
<div class="col-xl-12">
<div class="auth-form">
<form id="ap-frmLogin" name="ap-frmLogin" action="<?php echo(site_url('Login/enviarLogin'))?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<p class="text-white"><strong>Email</strong></p>
<input type="email" class="form-control" id="userLogin" name="userLogin" placeholder="<EMAIL>">
</div>
<div class="form-group">
<p class="text-white"><strong>Contraseña</strong></p>
<input type="<PASSWORD>" class="form-control" id="passuser" name="passuser" placeholder="<PASSWORD>">
</div>
<div class="form-row d-flex justify-content-between mt-4 mb-3">
<div class="form-group">
</div>
<div class="form-group">
<a class="text-white" href="<?php echo(site_url('Login/olvidar'))?>">¿Olvidaste tu contraseña?</a>
</div>
</div>
<div class="text-center">
<button type="submit" value="Enviar" class="btn bg-white text-primary btn-block">Ingresar</button>
</div>
</form>
<div class="new-account mt-3">
<p class="text-white">¿No tienes cuenta? <a class="text-white" href="<?php echo(site_url('Login/registrate'))?>">Registrate</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Footer Start -->
<div class="main-content">
<div class="flex-grow-1"></div>
<div class="app-footer">
<div class="footer-bottom border-top pt-3 d-flex flex-column flex-sm-row align-items-center">
<a class="btn btn-primary text-white btn-rounded" href="#" target="_blank">
UGEL03</a>
<span class="flex-grow-1"></span>
<div class="d-flex align-items-center">
<img class="logo" src="<?php echo site_resource('adjudicacion')?>/images/logo.png" alt="">
<div>
<p class="m-0">© 2020 ETI | APP</p>
<p class="m-0">Todos los derechos reservados</p>
</div>
</div>
</div>
</div>
</div>
<!-- fotter end -->
</div>
</div>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<KEY>', {
action: 'homepage'
}).then(function(token) {
document.getElementById("token").value = token;
});
});
</script>
<script src="<?php echo site_resource('mdp')?>/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/custom.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/deznav-init.js"></script>
<script src="<?php echo site_resource('adjudicacion')?>/js/plugins/bootstrap.bundle.min.js"></script>
<script src="<?php echo site_resource('adjudicacion')?>/js/plugins/perfect-scrollbar.min.js"></script>
<script src="<?php echo site_resource('adjudicacion')?>/js/scripts/script.min.js"></script>
<script src="<?php echo site_resource('adjudicacion')?>/js/scripts/sidebar-horizontal.script.js"></script>
</body>
</html><file_sep>/admin/models/old/Model_adjudicaciones.php
<?php
class Model_adjudicaciones extends CI_Model
{
private $db_sinad;
function __construct()
{
//$this->db_sinad = $this->load->database('db_sinad', TRUE);
parent::__construct();
}
/********** RECLAMOS ************/
function save_registroUsuario($data){
$this->db->insert("tb_usuario",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
function save_Consultabuzon($data){
$this->db->insert("tb_buzonConsultas",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
function save_Reclamo($data){
$this->db->insert("test",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
function update_datosPersonales($data){
$id = $this->db->update('tb_usuario', $data, array('nroDoc'=>$data['nroDoc']));
if($id){
return true;
}
else{
return false;
}
}
function update_reclamo($data){
$id = $this->db->update('test', $data, array('dato1'=>$data['dato1']));
if($id){
return true;
}
else{
return false;
}
}
function getInfoUsuario($id)
{
$sql = "SELECT * FROM tb_ussuario WHERE id='".$id."' AND flg=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
function Get_user($id,$pass)
{
$sql = "SELECT * FROM tb_postulante WHERE email='".$id."' AND pass='". $pass."' AND flg=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
function buscaDni($id){
$sql = "SELECT * FROM tb_usuario WHERE nroDoc='".$id."' AND flg=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
function buscaie($codmodular){
$sql = "SELECT nombre as num FROM ie WHERE id_modular='".$codmodular."' AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
//return true;
}else{
return false;
//return false;
}
}
function buscaTelefono($email,$dni){
$sql = "SELECT celular as num FROM tb_usuario WHERE email='".$email."' AND nroDoc='".$dni."' AND flg=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
//return true;
}else{
return false;
//return false;
}
}
function buscaEmail($email){
$sql = "SELECT count(*) as num FROM tb_usuario WHERE email='".$email."' AND flg=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
//return true;
}else{
return false;
//return false;
}
}
/*******************************/
function getCount($params = ''){
$params['count'] = true;
return $this->getAll($params);
}
function getAll($params = ''){
$select = $where = $limit = $order = '';
$where = " WHERE ";//"WHERE c.cupon_id=tc.cupon_id AND tc.id_categoria=ct.id_categoria";
#$where = "WHERE (d.State=1 OR d.State=-1) AND a.IdDisco=d.IdDisco";
//writer($params['idUser']); exit;
if (is_array($params)) {
if (isset($params['start'],$params['limit']))
$limit = "LIMIT " . $params['start'] . ", " . $params['limit'];
if (isset($params['orderBy'],$params['sentido']))
$order = "ORDER BY " . $params['orderBy'] . " " . $params['sentido'];
if (isset($params['status']))
$where .= " (b.status = '".$params['status']."')";
if(isset($params['search2']))
$where .= " AND b.idperiodo = ".$params['search2'];
;
if(isset($params['search']))
$where .= " AND (CONCAT(b.nombre) LIKE('%".$params['search']."%') OR b.dni LIKE('".$params['search']."%'))";
;
}
if (isset($params['count'])){
$select = "SELECT COUNT(*) AS total";
}
else{
$select = "SELECT b.* ";
//$select = "SELECT c.*, ct.categoria_name ";
}
$sql = "$select
FROM boleta b
$where
$order
$limit";
$query = $this->db->query($sql);
if (isset($params['count'])) {
$result = $query -> row();
return $result -> total;
}
else
if ( $query -> result() )
return $query -> result();
else
return false;
}
//obtenemos las localidades dependiendo de la provincia escogida
function Get_TipPedido($buscar)
{
$sql = "SELECT * FROM tb_tippedido WHERE id_tippedido=$buscar AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row()->nombre;
}
else
return false;
}
function Get_Requisito($buscar)
{
$sql = "SELECT * FROM tb_requisitos WHERE id_tippedido=$buscar AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
$data["requisitos"] = $query->result();
$data["costo"] = $this->Get_Costo($buscar);
return $data;
}
else
return false;
}
function Get_Costo($id)
{
$sql = "SELECT * FROM tb_costopedido WHERE id_tippedido=$id AND estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->result();
}
else
return false;
}
function Get_AllTipPedido(){
$sql = "SELECT * FROM tb_tippedido WHERE estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->result_array();
}
else
return false;
}
function save_pedido($data){
$this->db->insert("tb_solicitud",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
/**********************************************************************/
function testSinad(){
$sql = "SELECT TOP 1 * FROM [db_sinad].[dbo].[t_Expediente]";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function Get_userChangePass($data = array())
{
$sql = "SELECT * FROM tb_usuario WHERE nroDoc='".$data['dni']."' and email='".$data['email']."' and pass='".$data['passaActual']."' and flg='1'";
$query = $this->db->query($sql);
if($query->result()){
return $query->row_array();
}
else
return false;
}
function Change_PasswordUser($data){
$id = $this->db->update('tb_usuario', $data, array('nroDoc' => $data['nroDoc'],'email' => $data['email']));
if($id){
return true;
}
else{
return false;
}
}
function getConsultaBuzon($dni){
$sql = "SELECT * FROM tb_buzonConsultas WHERE idUsuario='".$dni."' and estado='1'";
$query = $this->db->query($sql);
$result = $query->result();
if($result){
return $result;
}else{
return false;
}
}
function numeroRegistro(){
$sql = "SELECT count(*) as 'num' FROM tb_buzonConsultas where flg='1'";
$query = $this->db->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function validaEmail($email){
$sql = "SELECT*FROM tb_usuario where email='$email' and flg='1'";
$query = $this->db->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function verificaNroDocumento($nroDocumento){
$sql = "SELECT*FROM t_Persona where NumeroDocumento='$nroDocumento' and Estado='1'";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function saveDataPersonal($Nombres,$Apellidos,$TipoDocumento,$NumeroDocumento,$Telefono1,$Telefono2,$Email,$CodigoUbigeo,$CodigoUbigeoDes,$PaisId,$Direccion,$UsuarioCreador,$FechaCreacion){
$sql = "EXEC [dbo].[ADM_INS_PersonaNaturalInsertarU] '$Nombres','$Apellidos',$TipoDocumento,'$NumeroDocumento','$Telefono1','$Telefono2','$Email',NULL,'$CodigoUbigeoDes','$PaisId','$Direccion','$UsuarioCreador','$FechaCreacion'";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function saveDataPersonalJuridica($Descripcion,$CodigoModular,$TipoSectorId,$TipoSectorDes,$TipoDocumento, $NumeroDocumento, $Telefono1, $Telefono2, $Email, $CodigoUbigeo,$CodigoUbigeoDes ,$PaisId ,$Direccion,$UsuarioCreador,$FechaCreacion){
$sql = "EXEC [dbo].[ADM_INS_PersonaJuridicaInsertarU] '$Descripcion','$CodigoModular',$TipoSectorId,'$TipoSectorDes',$TipoDocumento, '$NumeroDocumento', '$Telefono1', '$Telefono2', '$Email',NULL,'$CodigoUbigeoDes' ,$PaisId ,'$Direccion','$UsuarioCreador','$FechaCreacion'";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function saveExpediente($SedeId,$Anio,$Numero,$NumeroExpediente,$TipoExpediente,$TupaTramiteId ,$SedeTramiteId,$TipoRegistro ,$Prioridad,$RecepcionSinConformidad,
$Subsanar,$CantidadFolios,$TipoDocumentoTramite,$NumeroDocumentoTramite,$Cerrado,$FechaCerrado ,$SolicitanteId ,$TipoSolicitante ,$Confidencial ,
$FechaRegistroParcial,$FechaRegistroTotal,$FechaRegistroExpediente,$UsuarioCreador,$FechaCreacion,$WorkflowInstanceId,$Anulado,$SolicitudAccesoId,$CanalAtencionId){
$sql = "EXEC [dbo].[GEX_INS_ExpedienteSolicitudInsertarU3] $SedeId,$Anio,$Numero,$NumeroExpediente,$TipoExpediente,$TupaTramiteId ,$SedeTramiteId,$TipoRegistro ,$Prioridad,$RecepcionSinConformidad,
$Subsanar,$CantidadFolios,$TipoDocumentoTramite,$NumeroDocumentoTramite,$Cerrado,$FechaCerrado ,$SolicitanteId ,$TipoSolicitante ,$Confidencial ,
$FechaRegistroParcial,$FechaRegistroTotal,$FechaRegistroExpediente,$UsuarioCreador,$FechaCreacion,$WorkflowInstanceId,$Anulado,$SolicitudAccesoId,$CanalAtencionId";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function saveEstadoExpediente($SedeId,$Anio,$Numero,$EstadoId,$FechaInicio,$Accion){
$sql = "EXEC [dbo].[GEX_INS_ExpedienteEstadoInsertarUg3l] $SedeId,$Anio,$Numero,$EstadoId,'$FechaInicio',$Accion";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function saveEtapaExpediente($UltimoEstadoId,$TipoAccion ,$Accion ,$AsuntoAccion,$Prioridad,$OficinaRemitenteId,$OficinaActualId,$CodigoEtapa,$RequiereRespuesta,$SolicitaRespuesta,
$PadreEtapaExpedienteId,$TipoDocumentoRespuesta,$NumeroDocumentoRespuesta,$AsuntoRespuesta,$Observaciones,$Devolucion,$Anulada,$AccionEtapa,$SedeId,
$Anio,$Numero,$UsuarioCreador,$FechaCreacion,$WorkflowInstanceId,$DescripcionAcciones,$ObservacionesRuta,
$TupaTramiteEtapaId,$CantidadFoliosEtapa,$PadreEtapaReingresoId){
$sql = "EXEC [dbo].[GEX_INS_EtapaExpedienteInsertarUg3l] $UltimoEstadoId,$TipoAccion ,$Accion ,$AsuntoAccion,$Prioridad,$OficinaRemitenteId,$OficinaActualId,$CodigoEtapa,$RequiereRespuesta,$SolicitaRespuesta,
$PadreEtapaExpedienteId,$TipoDocumentoRespuesta,$NumeroDocumentoRespuesta,$AsuntoRespuesta,$Observaciones,$Devolucion,$Anulada,$AccionEtapa,$SedeId,
$Anio,$Numero,$UsuarioCreador,$FechaCreacion,'00000000-0000-0000-0000-000000000000',$DescripcionAcciones,NULL,
$TupaTramiteEtapaId,$CantidadFoliosEtapa,$PadreEtapaReingresoId";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->result_array();
}
else{
return false;
}
}
function saveEtapaEstadoExpediente($EtapaExpedienteId,$EstadoId,$WorkflowInstanceId,$FechaInicio){
$sql = "EXEC [dbo].[GEX_INS_EtapaEstadoInsertarUg3l] $EtapaExpedienteId,$EstadoId,'$WorkflowInstanceId','$FechaInicio'";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function saveProgramacionExpediente($SedeId ,$Anio ,$Numero,$TipoDestino,$TipoUbicacion,$Courier,$TipoAccion,$Accion,$AsuntoAccion,$Prioridad,$Observaciones,$OficinaDestinoId,$PersonaDestinoId,
$TipoPersonaDestino,$EtapaExpedienteId,$Devolucion , $TipoDevolucion ,$MotivoDevolucion ,$FechaDevolucion ,$RutaProcesada ,$UsuarioCreador,$FechaCreacion ,
$WorkflowInstanceId ,$RepresentanteDestinoId ,$TipoDocumentoRespuesta ,$NumeroDocumentoRespuesta ,$AsuntoRespuesta , $DetalleExpedienteId,$AccionesRuta ,
$DescripcionAcciones ,$SolicitaRespuestaCongreso){
$sql = "EXEC [dbo].[GEX_INS_ProgramacionRutaInsertar] $SedeId ,$Anio ,$Numero,$TipoDestino,$TipoUbicacion,$Courier,$TipoAccion,$Accion,$AsuntoAccion,$Prioridad,$Observaciones,$OficinaDestinoId,$PersonaDestinoId,
$TipoPersonaDestino,$EtapaExpedienteId,$Devolucion , $TipoDevolucion ,$MotivoDevolucion ,$FechaDevolucion ,$RutaProcesada ,$UsuarioCreador,$FechaCreacion ,
$WorkflowInstanceId ,$RepresentanteDestinoId ,$TipoDocumentoRespuesta ,$NumeroDocumentoRespuesta ,$AsuntoRespuesta , $DetalleExpedienteId,$AccionesRuta ,
$DescripcionAcciones ,$SolicitaRespuestaCongreso";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function saveAsignacionExpediente($NumeroExpediente,$NumeroHojaEnvio,$Asunto ,$Prioridad ,$GeneraRespuesta,$EspecialistaPrincipal,$EtapaExpedienteId,
$Accion,$PersonaNaturalId ,$Indicaciones ,$Estado,$FechaBaja,$Observaciones ,$UsuarioCreador,$FechaCreacion ,$Acciones){
$sql = "EXEC [dbo].[GEX_INS_AsignacionEspecialistaInsertar] $NumeroExpediente,$NumeroHojaEnvio,$Asunto ,$Prioridad ,$GeneraRespuesta,$EspecialistaPrincipal,$EtapaExpedienteId,
$Accion,$PersonaNaturalId ,$Indicaciones ,$Estado,$FechaBaja,$Observaciones ,$UsuarioCreador,$FechaCreacion ,$Acciones";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function getTicket($SedeId,$Anio,$Numero){
$sql = "EXEC [dbo].[REP_SEL_TicketTramite] $SedeId,$Anio,$Numero";
$query = $this->db_sinad->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
function save_solicitudTransparencia($data){
$this->db->insert("tb_solicitudtransparencia",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
function save_detallePedido($data){
$this->db->insert("tb_pedido_detalle",$data);
$id = $this->db->insert_id();
if($id){
return $id;
}
else{
return false;
}
}
function update_periodo($data){
$id = $this->db->update('periodo', $data, array('idperiodo' => $data['idperiodo']));
if($id){
return true;
}
else{
return false;
}
}
function Obt_Periodo(){
$sql = "SELECT * FROM periodo WHERE status=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->result();
}
else
return false;
}
function delete($data){
$id = $this->db->update('boleta', $data, array('idboleta' => $data['idboleta']));
if($id){
return true;
}
else{
return false;
}
}
/***************** ap_051218******************************/
public function getvia() {
$data = array();
$query = $this->db->get('tb_via');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
// var_dump($data);
}
}
$query->free_result();
return $data;
}
public function getie() {
$data = array();
// $this->db->distinct();
//$this->db->select('nombre');
$this->db->order_by('nombre','asc');
$this->db->where('estado','1');
$query = $this->db->get('ie');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
// var_dump($data);
}
}
$query->free_result();
return $data;
}
public function getzona() {
$data = array();
$query = $this->db->get('tb_zona');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
// var_dump($data);
}
}
$query->free_result();
return $data;
}
public function getdepartamento() {
$data = array();
$query = $this->db->get('ubdepartamento');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
/*
public function getarea(){
$data = array();
$query = $this->db->get('db_area');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
*/
public function gettipopersona(){
$data = array();
$this->db->where('estado','1');
$query = $this->db->get('tb_tipopersona');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function gettipopersonaGet($id){
$data = array();
$this->db->where('estado','1');
$this->db->where('id',$id);
$query = $this->db->get('tb_tipopersona');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function getTipoDocCbo($id){
$data = array();
$this->db->where('estado','1');
$this->db->where('id',$id);
$query = $this->db->get('tb_tipodocumento');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function getTipoDoc($tipodoc){
$this->db->where('idTipo',$tipodoc);
$this->db->order_by('descripcion','asc');
$provincias = $this->db->get('tb_tipodocumento');
if($provincias->num_rows()>0)
{
return $provincias->result();
}
}
public function GetcboTipoPersona($id){
$sql = " SELECT descripcion FROM tb_tipopersona WHERE id='$id' and estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
public function GetcboTipoDoc($id){
$sql = "SELECT descripcion FROM tb_tipodocumento WHERE id='$id' and estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
public function GetcboVia($id){
$sql = "SELECT descripcion FROM tb_via WHERE id='$id' and estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
public function GetcboZona($id){
$sql = "SELECT descripcion FROM tb_zona WHERE id='$id' and estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
/*
public function Getcboarea($id){
$sql = "SELECT descripcion FROM db_area WHERE id_area='$id' and estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
*/
public function Getcboequipo($id){
$sql = "SELECT descripcion FROM db_equipo WHERE id_equipo='$id' and estado=1";
$query = $this->db->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
public function GetdescripcioUbigeo($departamento,$provincia,$distrito){
//$sql = "SELECT descripcion FROM db_equipo WHERE id_equipo='$id' and estado=1";
$sql =" SELECT p.departamento ,
(SELECT pro.provincia FROM ubprovincia pro WHERE p.idDepa=pro.idDepa and idProv=$provincia ) as provincia ,
(SELECT dis.distrito FROM ubdistrito dis WHERE idDist=$distrito ) as distrito
FROM ubdepartamento p where p.idDepa='$departamento'";
$query = $this->db->query($sql);
if($query->result()){
return $query->row();
}
else{
return false;
}
}
/**********************************************************/
public function getEquipos($area){
$this->db->where('id_area',$area);
$this->db->order_by('descripcion','asc');
$provincias = $this->db->get('db_equipo');
if($provincias->num_rows()>0)
{
return $provincias->result();
}
}
public function getProvincias($departamento)
{
$this->db->where('idDepa',$departamento);
$this->db->order_by('provincia','asc');
$provincias = $this->db->get('ubprovincia');
if($provincias->num_rows()>0)
{
return $provincias->result();
}
}
public function getDistritos($provincia)
{
$this->db->where('idProv',$provincia);
$this->db->order_by('distrito','asc');
$provincias = $this->db->get('ubdistrito');
if($provincias->num_rows()>0)
{
return $provincias->result();
}
}
}<file_sep>/app/views/login/login.php
<!DOCTYPE>
<html lang="en" class="h-100">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Mesa de Partes Virtual | Ugel03 </title>
<link href="<?php echo site_resource('mdp')?>/css/style.css" rel="stylesheet" />
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo site_resource('mdp')?>/images/logo-full.png">
<script src="<?php echo site_resource('mdp')?>/js/plugins/jquery-3.3.1.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/jquery.validate.min.js"></script>
</head>
<script type="text/javascript">
$(function() {
$("#ap-frmLogin").validate({
rules: {
passuser: "required",
userLogin: {
required: true,
email: true
}
},
messages: {
passuser: "Por favor ingresar contraseña.",
userLogin: "Por favor ingresar email."
},
errorElement: "span",
errorClass: "afr-error",
errorPlacement: function(error, element) {},
submitHandler: function(forms) {
enviarLogueo();
}
})
});
function enviarLogueo() {
var datastring = $("#ap-frmLogin").serialize();
$.ajax({
url: $("#ap-frmLogin").attr('action'),
method: "POST",
data: datastring,
dataType: "JSON",
beforeSend: function() {
},
success: function(data) {
switch (data.resp) {
case 100:
$(this).closest('form').find("input[type=text]").val("");
window.location.href = "<?php echo site_url('Login/usuario') ?>";
alert(data.text);
break;
case 10:
alert(data.text);
break;
default:
}
}
})
}
</script>
<body class="h-100">
<div class="authincation h-100">
<div class="container h-100">
<div class="row justify-content-center h-100 align-items-center">
<div class="col-md-6">
<div class="authincation-content">
<div class="row no-gutters">
<div class="col-xl-12">
<div class="auth-form">
<div class="text-center mb-3">
<a href="index.php"><img src="<?php echo site_resource('mdp')?>/images/logo-full.png" alt=""></a>
</div>
<h4 class="text-center mb-4 text-white">Iniciar Sesión</h4>
<form id="ap-frmLogin" name="ap-frmLogin" action="<?php echo(site_url('Login/enviarLogin'))?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<p class="mb-1 text-white"><strong>Email:</strong></p>
<input type="email" class="form-control" id="userLogin" name="userLogin" placeholder="<EMAIL>">
</div>
<div class="form-group">
<p class="mb-1 text-white"><strong>Contraseña:</strong></p>
<input type="<PASSWORD>" class="form-control" id="passuser" name="passuser" placeholder="********">
</div>
<div class="form-row d-flex justify-content-between mt-4 mb-3">
<div class="form-group">
</div>
<div class="form-group">
<a class="text-white" href="<?php echo(site_url('Login/olvidar'))?>">¿Olvidaste tu contraseña?</a>
</div>
</div>
<div class="text-center">
<button type="submit" value="Enviar" class="btn bg-danger text-white btn-block"> <i class="fa fa-check color-info"></i> Ingresar </button>
</div>
</form>
<div class="new-account mt-3" style="text-align:center;">
<p class="text-white">¿No tienes cuenta? <a class="text-white" href="<?php echo(site_url('login/registrate'))?>">Registrate</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="<?php echo site_resource('mdp')?>/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/custom.min.js"></script>
<script src="<?php echo site_resource('mdp')?>/js/deznav-init.js"></script>
</body>
</html> | 4b5bdda0fd411048fec4abb79cd1313e1b8f91da | [
"PHP"
] | 24 | PHP | JhonelCH/MESA_DE_PARTES_VIRTUAL | f2eb7f6f1e4e5d33f72b79dfb1a23826bba817b6 | 769ab3324b7f6a117c516ab6851435546691fade |
refs/heads/master | <file_sep>import React from 'react'
import { instanceOf, func, object, objectOf, string } from 'prop-types'
import { isSameDay } from 'date-fns'
import { mergeModifiers } from './utils'
import Calendar from './Calendar'
export default function DatePickerCalendar({
locale,
date: selectedDate,
month,
onDateChange,
onMonthChange,
minimumDate,
maximumDate,
modifiers: receivedModifiers,
modifiersClassNames
}) {
const isSelected = date => isSameDay(date, selectedDate)
const modifiers = mergeModifiers({ selected: isSelected, disabled: isSelected }, receivedModifiers)
return (
<Calendar
locale={locale}
month={month}
onMonthChange={onMonthChange}
onDayClick={onDateChange}
minimumDate={minimumDate}
maximumDate={maximumDate}
modifiers={modifiers}
modifiersClassNames={modifiersClassNames}
/>
)
}
DatePickerCalendar.propTypes = {
locale: object.isRequired,
date: instanceOf(Date),
month: instanceOf(Date),
onDateChange: func,
onMonthChange: func,
minimumDate: instanceOf(Date),
maximumDate: instanceOf(Date),
modifiers: objectOf(func),
modifiersClassNames: objectOf(string)
}
| 7024927c1dff551604b630942b4d7a70c328d9b9 | [
"JavaScript"
] | 1 | JavaScript | shklnrj/react-nice-dates | 742ebb42b25e14bea2bb5cfd174848cde59e0a2c | e13ad587072d3f5321f2790e179da4101b0bb553 |
refs/heads/master | <file_sep># --------------------------------------------------------
# Host: localhost
# Server version: 5.1.41
# Server OS: Win32
# HeidiSQL version: 6.0.0.3603
# Date/time: 2011-05-24 02:56:14
# --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
# Dumping structure for table pkt_scanner.data_categories
CREATE TABLE IF NOT EXISTS `data_categories` (
`category_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL COMMENT 'Category name',
`cities_page_current` int(10) unsigned NOT NULL DEFAULT '1' COMMENT 'Current city in category page',
`cities_page_total` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Cities pages count in category view',
`is_complete` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT 'Items count in current city view',
`working` tinyint(1) unsigned NOT NULL DEFAULT '0',
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
# Data exporting was unselected.
# Dumping structure for table pkt_scanner.data_cities
CREATE TABLE IF NOT EXISTS `data_cities` (
`city_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '0',
PRIMARY KEY (`city_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
# Data exporting was unselected.
# Dumping structure for table pkt_scanner.data_objects
CREATE TABLE IF NOT EXISTS `data_objects` (
`object_id` varchar(50) NOT NULL,
`category_id` int(10) unsigned NOT NULL,
`city_id` int(10) unsigned NOT NULL,
`area` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`address` text NOT NULL,
`phone` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`website` varchar(255) NOT NULL,
PRIMARY KEY (`object_id`,`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
# Data exporting was unselected.
# Dumping structure for table pkt_scanner.rel_category_city
CREATE TABLE IF NOT EXISTS `rel_category_city` (
`category_id` int(10) NOT NULL DEFAULT '0',
`city_id` int(10) NOT NULL DEFAULT '0',
`total_items` int(10) DEFAULT '0',
`current_page` int(10) DEFAULT '1',
`is_complete` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`category_id`,`city_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
# Data exporting was unselected.
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
<file_sep><?php
define('SCRIPT_ROOT_URL', 'http://' . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']) . '/');
define('SCRIPT_ROOT_DIR', dirname(__FILE__));
define('SITE_URL', 'http://www.gelbeseiten.de');
define('SITE_CATEGORIES_URL', SITE_URL . '/yp/quick.yp');
?><file_sep><?php
include_once('LIB_library/LIB_http.php');
include_once('phpQuery.php');
include_once(dirname(__FILE__) . '/_constants.php');
include_once(dirname(__FILE__) . '/_functions.php');
include_once(dirname(__FILE__) . '/_db.php');
$charset = 'utf-8';
$categories_page = http_get($target = SITE_CATEGORIES_URL, $referer = '');
$phpQuery_page = phpQuery::newDocumentHTML($categories_page['FILE'], $charset);
$categories = pq('#tabbed_1_content ul li a[id!="cat_az"]');
//var_dump(pq('#tabbed_1_content ul li'));
$secondary_ids = array(1052650, 1053202, 1053300, 1053284, 1053285,
1053311, 1053324, 1053368, 1053390, 1053400,
1053351, 1053410, 1053423, 1053448, 1053496, 1056236);
$count = 0;
foreach ($categories as $category)
{
$db->insert() pq($category)->text();
$rubrikenJson = http_get("http://www.gelbeseiten.de/yp/rubriken.yp?themaID={$secondary_ids[$count++]}&locationHit=", $referer = '');
$secondary_categories = json_decode($rubrikenJson['FILE']);
foreach ($secondary_categories as $secondary_category)
{
$branchenJson = http_get("http://www.gelbeseiten.de/yp/branchen.yp?rubrikId={$secondary_category[1]}&locationHit=", $referer = '');
$third_categories = json_decode($branchenJson['FILE']);
foreach ($third_categories as $third_category)
{
echo pq($category)->text() . ' ' . $secondary_category[0] . ' ' . $third_category[0] . PHP_EOL;
}
}
}
//if (!$page = getHtml($link = SITE_URL))
//{
// _die('CATEGORY PAGE NOT EXISTS. Exiting.' . PHP_EOL . $link . PHP_EOL);
//}
//$sessionDataString = phpQuery::newDocumentHTML('page');
//var_dump(pq('#startpageForm p input')->attr('value'));
//$data = file_get_contents('http://www.gelbeseiten.de/yp/search.yp?sessionDataString=H4sIAAAAAAAAAFWLywrCMBBFv8ZlYDJJOimzU%2FCxEEXBbUnbqRZKlSQI%2Fr1BEHF5zj1Xa9sHi4KqJkPKkgmqDT4oHAiMbonaHpTvwWnyjGjYLHAt8SrtPKZpTFkKb87Nn-pL69WBSmm0ZUw4xJxm%2F5Y%2FZ5xh6SRJid-pNc-pqWlytgFrXgLvEv3mJsokzzD3AnvNQKArg0hAh8-pKR-pBT-pV4sZ6HmipXOe0cvwGm9DY51wAAAA-e-e&at=yp&kindOfSearch=tradelistindex&subject=&location=&distance=-1&execute=Suchen&suggest_choose=on&trade=834');
//var_dump($data);
//phpQuery::ajaxAllowHost('rubriken.yp');
//$json = phpQuery::getJSON('rubriken.yp');
//$json = file_get_contents('http://www.gelbeseiten.de/yp/rubriken.yp?themaID=1052650&locationHit=');
//var_dump(json_decode($json));
//$json_data = Zend_Json::decode($json, Zend_Json::TYPE_OBJECT);
//var_dump($json_data);
?>
<file_sep><?php
include_once('Zend/Db.php');
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSOWRD', '');
define('DB_NAME', 'scrapper_suchen');
$tables = array(
'categories' => 'data_categories',
'cities' => 'data_cities',
'objects' => 'data_objects',
'rel_cc' => 'rel_category_city'
);
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => DB_HOSTNAME,
'username' => DB_USERNAME,
'password' => <PASSWORD>,
'dbname' => DB_NAME,
'charset' => 'utf8'
));
$db->getProfiler()->setEnabled(true);
/* ---------------Functions------------------ */
function getCategoryDataByName($name)
{
global $db, $tables;
$category = $db->select()
->from($tables['categories'])
->where('name like ?', $name)
->query()
->fetch();
if ($category !== false)
{
return $category;
}
$db->insert($tables['categories'], array('name' => $name));
$category = $db->select()
->from( $tables['categories'] )
->where('category_id = ?', $db->lastInsertId())
->query()
->fetch();
return $category;
}
function getCityDataByName($name, $category_id = 0)
{
global $db, $tables;
$city = $db->select()
->from($tables['cities'])
->where('name like ?', $name)
->query()
->fetch();
if ($city === false)
{
$db->insert($tables['cities'], array('name' => $name ));
$city = $db->select()
->from($tables['cities'])
->where('city_id = ?', $db->lastInsertId())
->query()
->fetch();
}
if ($city === false)
{
return false;
}
if (empty( $category_id))
{
return $city;
}
$city['_rel_cc_'] = array();
$rel = $db->select()
->from($tables['rel_cc'])
->where('category_id = ?', $category_id)
->where('city_id = ?', $city['city_id'])
->query()
->fetch();
if ($rel === false)
{
$db->insert($tables['rel_cc'], array('category_id' => $category_id, 'city_id' => $city['city_id']));
$rel = $db->select()
->from($tables['rel_cc'])
->where('category_id = ?', $category_id)
->where('city_id = ?', $city['city_id'])
->query()
->fetch();
}
if ($rel !== false)
{
$city['_rel_cc_'] = $rel;
}
return $city;
}
function addVcard($data)
{
global $db, $tables;
$existing_item = $db->select()
->from($tables['objects'])
->where('object_id = ?', $data['object_id'])
->where('category_id = ?', $data['category_id'])
->query()
->fetch();
if ($existing_item !== false)
{
$data = array_merge($existing_item, $data);
$db->update(
$tables['objects'],
$data,
'object_id = ' . $db->quote($data['object_id'] ) . ' AND category_id = ' . $data['category_id']);
}
else
{
$db->insert($tables['objects'], $data);
}
$db->getProfiler()->getLastQueryProfile();
}
?><file_sep><?php
include_once(SCRIPT_ROOT_DIR . '/phpQuery.php');
if (!class_exists('phpQuery'))
{
echo 'NO PHP QUERY LIB. Exiting.' . PHP_EOL;
die(__FILE__ . ' : ' . __LINE__);
}
/* ------------Functions--------------- */
function getHtml($url = '')
{
if (empty($url))
{
return '';
}
if (function_exists('curl_init'))
{
//return getCurl( $url );
}
$opts = array(
'http' => array(
'method' => 'GET',
'header' =>
"Content-type: application/x-www-form-urlencoded;charset=iso-8859-1" .
"Accept-language: de\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
if (!$html = file_get_contents($url, false, $context))
{
return false;
}
return $html;
}
function getCurl($url = '')
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
function prepareLink($link)
{
$link = preg_replace('/(.*)(;jsessionid.*)$/', '$1', $link);
return $link;
}
function _die($message)
{
ob_end_flush();
echo $message . PHP_EOL;
die(__FILE__ . ' : ' . __LINE__);
}
function _redirect($location, array $params = array())
{
if ( !empty( $params ) )
{
$location .= substr_count($location, '?') > 0 ? '' : '?1';
foreach ( $params as $key => $param )
{
$location .= '&' . $key . '=' . $param;
}
}
ob_end_clean();
header('Location: ' . $location);
die;
}
?><file_sep><?php
set_time_limit(0);
ini_set('memory_limit', '1000M');
session_start();
header('Content-Type: text/plain');
ob_start();
echo date('Y-m-d H:i:s') . PHP_EOL;
include_once(dirname(__FILE__) . '/_constants.php');
include_once(dirname(__FILE__) . '/_functions.php');
include_once(dirname(__FILE__) . '/_db.php');
include_once('Zend\Http\Client.php');
$letter = $letter_orig = 'A';
$next_letter = false;
$category_id = 0;
$city_id = 0;
$city_page = 1;
$charset = 'utf-8';
if (isset($_GET['letter']) && is_string($_GET['letter']) && !empty($_GET['letter']))
{
$letter_orig = (string) $_GET['letter'];
$letter = urlencode($letter_orig);
}
if (!$categories_page = getHtml($link = SITE_CATEGORIES_URL))
{
_die('CATEGORY PAGE NOT EXISTS. Exiting.' . PHP_EOL . $link . PHP_EOL);
}
$categories_page = phpQuery::newDocumentHTML($categories_page, $charset);
$main_categories = $categories_page->find('#tabbed_1_content ul li a');
//-------------------------------------------------------------------------------
foreach ($main_categories as $main_category)
{
echo pq($main_category)->text() . PHP_EOL;
}
die();
//-------------------------------------------------------------------------------
foreach ($categories_letters as $c_letter)
{
$c_letter = pq($c_letter);
if ($c_letter->text() != $letter_orig)
{
continue;
}
$sec = 0;
$tmp = $c_letter->parent();
while (!$next_letter && $sec < 100)
{
$sec++;
$tmp = $tmp->next('li');
if (!(bool) $tmp->text())
{
break;
}
if ($tmp->find('a')->count())
{
$next_letter = $tmp->find('a');
break;
}
}
}
$categories_items = $categories_page->find('.linkListContainer a');
if (!$categories_items->count())
{
_die('NO CATEGORIES EXISTS. Exiting.' . PHP_EOL);
}
$db->update(
$tables['categories'],
array('working' => 0),
array('working = ?' => 1, 'last_update < ?' => $db->quote(date('Y-m-d H:i:s', strtotime('-15min'))))
);
$category_selected = false;
foreach ($categories_items as $category_item)
{
$category_item = pq($category_item);
$category_data = getCategoryDataByName($category_item->text());
if (empty($category_data) || !empty($category_data['is_complete']) || !empty($category_data['working']))
{
continue;
}
$category_data['link'] = SITE_URL . prepareLink($category_item->attr('href'));
$category_selected = true;
break;
}
if (!$category_selected)
{
if ($next_letter)
{
_redirect(SCRIPT_ROOT_URL, array('letter' => $next_letter->text()));
}
_die('NO SELECTED CATEGORY. Exiting.' . PHP_EOL);
}
$db->update(
$tables['categories'],
array('last_update' => date('Y-m-d H:i:s'), 'working' => 1),
array('category_id = ?' => $category_data['category_id'])
);
$category_link = $category_data['link'] . '/' . $category_data['cities_page_current'];
unset($category_data['link']);
if (!$category_page = getHtml($category_link))
{
_redirect(SCRIPT_ROOT_URL, array('letter' => $letter_orig));
die(__FILE__ . ' : ' . __LINE__);
}
$category_page = phpQuery::newDocumentHTML($category_page, $charset);
/**
* Cities in a page
*/
$cities_links = pq('.browseCityList a', $category_page);
if (!$cities_links->count())
{
_redirect(SCRIPT_ROOT_URL, array('letter' => $letter_orig));
}
/**
* Updateing category data
*/
if (empty($category_data['cities_page_total']))
{
$pagination_total = max(1, (int) pq('.locations .cityPaginationLeft span:last', $category_page)->text());
$db->update(
$tables['categories'], array('cities_page_total' => $pagination_total), array('category_id = ?' => $category_data['category_id'])
);
$category_data['cities_page_total'] = $pagination_total;
}
/**
* Looping throughout cities
*/
foreach ($cities_links as $city_link)
{
/**
* Loading city data
*/
$city_link = pq($city_link);
$city_data = array(
'name' => $city_link->text(),
'link' => prepareLink($city_link->attr('href'))
);
$city_data_db = getCityDataByName($city_data['name'], $category_data['category_id']);
if (!$city_data_db || empty($city_data_db['_rel_cc_']) || !empty($city_data_db['_rel_cc_']['is_complete']))
{
continue;
}
$city_data = array_merge($city_data, $city_data_db);
unset($city_data_db);
/**
* Loading city page with objects
*/
$city_html_page = $city_data['_rel_cc_']['current_page'];
for (; $city_html_page < 1000; $city_html_page++)
{
$city_html_link = SITE_URL . $city_data['link'] . $city_html_page . '/?activeSort=sortname|asc';
$city_html = getHtml($city_html_link);
if (!$city_html)
{
if ($city_html_page > 1)
{
$db->update(
$tables['rel_cc'],
array('is_complete' => 1),
array('category_id = ?' => $category_data['category_id'], 'city_id = ?' => $city_data['city_id'])
);
}
break;
}
$city_html = phpQuery::newDocumentHTML($city_html);
$city_total_items = (int) pq('#topBar .resstr strong:last')->text();
if ($city_total_items)
{
$db->update(
$tables['rel_cc'], array('total_items' => $city_total_items), array(
'category_id = ? ' => $category_data['category_id'],
'city_id = ?' => $city_data['city_id']
)
);
}
$vcards = pq('td.vcard', $city_html);
if (!$vcards->count())
{
$db->update(
$tables['rel_cc'], array('is_complete' => 1), 'category_id = ' . $category_data['category_id'] . ' AND city_id = ' . $city_data['city_id']
);
break;
}
foreach ($vcards as $vcard)
{
$vcard = pq($vcard);
$vcard_data = array(
'object_id' => $vcard->attr('id'),
'category_id' => $category_data['category_id'],
'city_id' => $city_data['city_id'],
'name' => trim($vcard->find('h2')->text()),
'address' => $vcard->find('.adr')->text(),
'phone' => $vcard->find('.tel')->text(),
'email' => $vcard->find('.email a')->text(),
'website' => $vcard->find('.url a')->attr('href')
);
$link = $vcard->find('h2 a')->attr('href');
$object_html = @getHtml(SITE_URL . $link);
if (!$object_html)
{
continue;
}
$object_html = phpQuery::newDocumentHTML($object_html);
$object_html = pq('.vcard', $object_html);
$vcard_data['area'] = $object_html->find('.extended-location')->text();
addVcard($vcard_data);
unset($vcard, $object_html, $vcard_data);
}
$db->update(
$tables['rel_cc'],
array('current_page' => $city_html_page + 1),
'category_id = ' . $category_data['category_id'] . ' AND city_id = ' . $city_data['city_id']
);
}
unset($city_html, $vcards);
}
$category_data['is_complete'] = (int) ($category_data['cities_page_current'] == $category_data['cities_page_total']);
$category_data['working'] = 0;
$category_data['last_update'] = date('Y-m-d H:i:s');
if (!$category_data['is_complete'])
{
$category_data['cities_page_current']++;
}
$db->update(
$tables['categories'],
$category_data,
array('category_id = ?' => $category_data['category_id'])
);
_redirect(SCRIPT_ROOT_URL, array('letter' => $letter_orig));
die(__FILE__ . ' : ' . __LINE__);
/**
* Categories
*/
$categories_html = getHtml(SITE_CATEGORIES_URL);
$categories_html = phpQuery::newDocumentHTML($categories_html, $charset = 'utf-8');
$categories_links = pq('#browseContainer dd a', $categories_html);
if (!$categories_links->count())
{
echo 'NO CATEGORIES. Exiting.';
die(__FILE__ . ' : ' . __LINE__);
}
/**
* Loop throughout category links
*/
foreach ($categories_links as $category_link)
{
/**
* Setting category data
*/
$category_link = pq($category_link);
$category_data = array(
'name' => $category_link->text(),
'link' => prepareLink($category_link->attr('href'))
);
if (empty($category_data['name']))
{
continue;
}
$db_data = getCategoryDataByName($category_data['name']);
if (!$db_data)
{
continue;
}
$category_data = array_merge($category_data, $db_data);
unset($db_data);
if (!empty($category_data['is_complete']))
{
continue;
}
/**
* Fetching category page
*/
$category_page = getHtml(SITE_URL . $category_data['link'] . '/' . $category_data['cities_page_current']);
if (!$category_page)
{
continue;
}
$category_page = phpQuery::newDocumentHTML($category_page, $charset = 'utf-8');
/**
* Updateing category data
*/
if (empty($category_data['cities_page_total']))
{
$pagination_total = (int) pq('.locations .cityPaginationLeft span:last', $category_page)->text();
$db->update(
$tables['categories'], array('cities_page_total' => $pagination_total), array('category_id = ?' => $category_data['category_id'])
);
$category_data['cities_page_total'] = $pagination_total;
}
die(__FILE__ . ' : ' . __LINE__);
/**
* Looping throughout city pages
*/
for ($i = $category_data['cities_page_current']; $i <= $category_data['cities_page_total']; $i++)
{
/**
* Updateing category
*/
$db->update(
$tables['categories'], array('cities_page_current' => $i), 'category_id = ' . $category_data['category_id']
);
/**
* Loading new city page
*/
if ($i != $current_city_page)
{
$category_page = getHtml(SITE_URL . $category_data['link'] . '/' . $i);
if (!$category_page)
{
continue;
}
$category_page = phpQuery::newDocumentHTML($category_page, $charset = 'utf-8');
}
/**
* Cities in a page
*/
$cities_links = pq('.browseCityList a', $category_page);
if (!$cities_links->count())
{
continue;
}
/**
* Looping throughout cities
*/
foreach ($cities_links as $city_link)
{
/**
* Loading city data
*/
$city_link = pq($city_link);
$city_data = array(
'name' => $city_link->text(),
'link' => prepareLink($city_link->attr('href'))
);
$city_data_db = getCityDataByName($city_data['name'], $category_data['category_id']);
if (!$city_data_db || empty($city_data_db['_rel_cc_']) || !empty($city_data_db['_rel_cc_']['is_complete']))
{
continue;
}
$city_data = array_merge($city_data, $city_data_db);
unset($city_data_db);
/**
* Loading city page with objects
*/
$city_html_page = $city_data['_rel_cc_']['current_page'];
for (; $city_html_page < 1000; $city_html_page++)
{
$city_html_link = SITE_URL . $city_data['link'] . $city_html_page . '/?activeSort=sortname|asc';
$city_html = @getHtml($city_html_link);
if (!$city_html)
{
if ($city_html_page > 1)
{
$db->update(
$tables['rel_cc'], array('is_complete' => 1), 'category_id = ' . $category_data['category_id'] . ' AND city_id = ' . $city_data['city_id']
);
}
break;
}
$city_html = phpQuery::newDocumentHTML($city_html);
$city_total_items = (int) pq('#topBar .resstr strong:last')->text();
if ($city_total_items)
{
$db->update(
$tables['rel_cc'], array('total_items' => $city_total_items), array(
'category_id = ? ' => $category_data['category_id'],
'city_id = ?' => $city_data['city_id']
)
);
}
$vcards = pq('td.vcard', $city_html);
if (!$vcards->count())
{
$db->update(
$tables['rel_cc'], array('is_complete' => 1), 'category_id = ' . $category_data['category_id'] . ' AND city_id = ' . $city_data['city_id']
);
break;
}
foreach ($vcards as $vcard)
{
$vcard = pq($vcard);
$vcard_data = array(
'object_id' => $vcard->attr('id'),
'category_id' => $category_data['category_id'],
'city_id' => $city_data['city_id'],
'name' => trim($vcard->find('h2')->text()),
'address' => $vcard->find('.adr')->text(),
'phone' => $vcard->find('.tel')->text(),
'email' => $vcard->find('.email a')->text(),
'website' => $vcard->find('.url a')->attr('href')
);
$link = $vcard->find('h2 a')->attr('href');
$object_html = @getHtml(SITE_URL . $link);
if (!$object_html)
{
continue;
}
$object_html = phpQuery::newDocumentHTML($object_html);
$object_html = pq('.vcard', $object_html);
$vcard_data['area'] = $object_html->find('.extended-location')->text();
addVcard($vcard_data);
unset($vcard, $object_html, $vcard_data);
}
$db->update(
$tables['rel_cc'], array('current_page' => $city_html_page + 1), 'category_id = ' . $category_data['category_id'] . ' AND city_id = ' . $city_data['city_id']
);
}
unset($city_html, $vcards);
}
if ($i == $category_data['cities_page_total'])
{
$db->update(
$tables['categories'], array('is_complete' => 1), 'category_id = ' . $category_data['category_id']
);
}
unset($category_page, $cities_links);
}
unset($category_link, $category_page);
}
echo date('Y-m-d H:i:s') . PHP_EOL;
die(__FILE__ . ' : ' . __LINE__);
?><file_sep>select
c.name AS Category, c2.name AS City, o.name AS Title,
address AS Address, area AS Area, phone AS Phone, email AS Email, website AS Website
from data_objects as o
left join data_categories as c on c.category_id = o.category_id
left join data_cities as c2 on c2.city_id = o.city_id
order by c.name, c2.name, o.name | b102871c8e55e3ca0dcc2194ed97990be60a4b15 | [
"SQL",
"PHP"
] | 7 | SQL | mindzee/gelbeseiten_scraper | 061f89971a0288a8c669ce1bfaecedfaeb39e8cb | bf229b9ae5d2bcef6f64768adb96272aa5c36473 |
refs/heads/master | <file_sep>import React, { Component } from 'react'
import { Link, browserHistory } from 'react-router-dom'
import { Jumbotron, Container, Row, Col, Image, Button,InputGroup,FormControl,Modal } from 'react-bootstrap'
import './Questions.css'
export default class Question9 extends Component {
constructor(props) {
super(props);
this.state = {
showModal: false,
shown1: true,
shown2: true
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(){
this.props.history.push("/question10")
}
render(){
return(
<Container className="container">
<Jumbotron>
<h1>9. หากพบเหตุร้าย ฉันจะรีบแจ้งทางการทันที </h1>
<Row>
<div className="answerContainer" onClick={this.handleChange} >
<p>โทรแจ้ง = 5</p>
</div>
<div className="answerContainer" onClick={this.handleChange} >
<p>ไม่โทร = 0</p>
</div>
</Row>
</Jumbotron>
</Container>
)
}
}
| 3bd10e7455db2ee3e44d36148380fd358595132e | [
"JavaScript"
] | 1 | JavaScript | kanyapandey/pah_score_qa | 5a7cd59119c511b63afdc698edc4218b06d9193c | 408894aa74e0500d45623efacb579d743f4edc4e |
refs/heads/master | <file_sep>// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Lightup
{
using Microsoft.CodeAnalysis;
internal interface IOperationWrapper
{
IOperation? WrappedOperation { get; }
////IOperationWrapper Parent { get; }
////OperationKind Kind { get; }
////SyntaxNode Syntax { get; }
ITypeSymbol? Type { get; }
////Optional<object> ConstantValue { get; }
////IEnumerable<IOperationWrapper> Children { get; }
////string Language { get; }
////bool IsImplicit { get; }
////SemanticModel SemanticModel { get; }
}
}
| e4f8637c44403750f5cc22375702e2e1ccf1a326 | [
"C#"
] | 1 | C# | martincostello/StyleCopAnalyzers | ed67842090a8e1ce55e6c29aebc799c3e5de5e17 | bd075cbf3321c1a949cae4cb2d140367deaf9c2f |
refs/heads/master | <file_sep>Video Parallax Plugin
=====================
<file_sep> function checkElementOnWindow(element){
var rect = element.getBoundingClientRect();
return (rect.bottom > 0 && rect.bottom <= rect.height) ||
(rect.top > 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight));
}
function imageParallax(image,check3D) {
var windowHeight = window.innerHeight || document.documentElement.clientHeight,
imageDemension,
ratioScroll ,
topChange;
imageDemension = getDemensions(image);
var container = jQuery(image).parents(".image-parallax-container").first().get(0);
var containerDemension = getDemensions(container);
var maxScrollMove = windowHeight + containerDemension.height;
var maxImageMove = imageDemension.height - containerDemension.height;
ratioScroll = maxImageMove/maxScrollMove;
var left = -(imageDemension.width - containerDemension.width)/2;
if(checkElementOnWindow(container)) {
topChange = Math.floor((containerDemension.top - windowHeight) * ratioScroll);
if(check3D) {
var translate3D = 'translate3d('+left+'px, '+topChange+'px, 0px)';
image.style.cssText =
'-moz-transform:' + translate3D +
';-ms-transform:' + translate3D +
';-o-transform:' + translate3D +
';-webkit-transform:' + translate3D +
';transform:' + translate3D;
;
} else {
image.style.top = topChange+"px";
image.style.left = left +"px";
}
}
}
function check3D() {
var translate3D = 'translate3d(0px, 0px, 0px)',
divElm = document.createElement('div'),
matches;
divElm.style.cssText =
'-moz-transform:' + translate3D +
';-ms-transform:' + translate3D +
';-o-transform:' + translate3D +
';-webkit-transform:' + translate3D +
';transform:' + translate3D;
matches = divElm.style.cssText.match(/translate3d\(0px, 0px, 0px\)/g);
var support3d = matches !== null && matches.length >= 1;
return support3d;
}
function getDemensions(image) {
var rect = image.getBoundingClientRect();
return rect;
}
| 04aabb7e22e75e3e56bb1c92cad750962f6fb717 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | ducna88/video-parallax | bfa02fc32ee0db5662e0ebe00764d923f7946248 | 788a616494268e2344c7984b0fb3d1ced8a1d2b0 |
refs/heads/main | <file_sep>URL: https://danskeci.com/pl/news
Spider name: danskeci
DB Schema:
title
content
date<file_sep>from scrapy import cmdline
cmdline.execute("scrapy crawl danskeci".split()) | d36f19e64ce2b5e0633d01fcd1e47686dfcda959 | [
"Markdown",
"Python"
] | 2 | Markdown | hristo-grudev/danskeci | f8088a96daea0644f8352a4d9211f308fb383089 | 4c8c8d829008dd10fe46596ee8ea24fcf70ca4eb |
refs/heads/master | <repo_name>fitnycdigitalinitiatives/mdid-iiif-demo<file_sep>/js/mdid-iiif-demo.js
$(document).ready(function() {
var viewer = OpenSeadragon({
id: "openseadragon",
maxZoomPixelRatio: 2,
prefixUrl: "https://cdnjs.cloudflare.com/ajax/libs/openseadragon/2.4.1/images/",
tileSources: "https://fitdil.fitnyc.edu/media/iiif/136269/lb_sc_nef_000006/info.json",
showNavigator: true,
navigatorSizeRatio: 0.1,
controlsFadeDelay: 1000,
collectionMode: true,
collectionRows: 4,
collectionLayout: 'vertical'
});
viewer.world.addHandler('add-item', function(event) {
var items = event.eventSource['_items'];
$('.thumb').remove();
for (var i in items) {
var id = items[i].source['@id'];
var thumbURL = id + '/full/100,/0/default.jpg';
var thumbItem = `
<li class="list-group-item thumb">
<button type="button" class="close" aria-label="Close" data-index="` + i + `">
<span aria-hidden="true">×</span>
</button>
<div class="media">
<img src="` + thumbURL + `" class="mr-3 align-self-center">
<div class="media-body text-muted align-self-center">
@id: ` + id + `
</div>
</div>
</li>
`;
$('.list-group').append(thumbItem);
}
$('.close').click(function() {
var thisItem = viewer.world.getItemAt($(this).data('index'));
viewer.world.removeItem(thisItem);
$(this).parent().remove();
viewer.viewport.goHome();
});
var tiledImage = event.item;
viewer.addOnceHandler('reset-size', function() {
viewer.viewport.goHome();
});
});
viewer.world.addHandler('remove-item', function(event) {
var items = event.eventSource['_items'];
$('.thumb').remove();
for (var i in items) {
var id = items[i].source['@id'];
var thumbURL = id + '/full/100,/0/default.jpg';
var thumbItem = `
<li class="list-group-item thumb">
<button type="button" class="close" aria-label="Close" data-index="` + i + `">
<span aria-hidden="true">×</span>
</button>
<div class="media">
<img src="` + thumbURL + `" class="mr-3 align-self-center">
<div class="media-body text-muted align-self-center">
@id: ` + id + `
</div>
</div>
</li>
`;
$('.list-group').append(thumbItem);
}
$('.close').click(function() {
var thisItem = viewer.world.getItemAt($(this).data('index'));
viewer.world.removeItem(thisItem);
$(this).parent().remove();
viewer.viewport.goHome();
});
});
viewer.addHandler('add-item-failed', function(event) {
var alert = `
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Derp!</strong> Invalid IIIF Endpoint. Please enter a url that leads to a valid info.json file.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
`;
$('#add-image').after(alert);
});
$('#add-image').submit(function(event) {
event.preventDefault();
var endpoint = $(this).find('input').val();
const url = new URL(endpoint);
if (url.pathname.includes("/data/record/")) {
endpoint = endpoint.replace("/data/record/", "/media/iiif/") + "info.json"
}
viewer.addTiledImage({
tileSource: endpoint,
preload: true
});
$(this).find('input').val('');
});
}); | f307b89e431e7a7366cf603fae91445d42783075 | [
"JavaScript"
] | 1 | JavaScript | fitnycdigitalinitiatives/mdid-iiif-demo | cdd8a05112ebc1a41b1cede0175a0e62233606a0 | 279af556aa7817442d7581d5c7aed8e11adb23d1 |
refs/heads/master | <repo_name>maxknee/hexo-theme-sb<file_sep>/_gulp/kill.js
const gulp = require('gulp')
const exit = require('gulp-exit')
const wait = require('gulp-wait')
const gulpSequence = require('gulp-sequence')
gulp.task('kill:browser-sync', () => global.bs.exit())
gulp.task('kill:intantly', () => {
global.bs.exit()
return gulp.src(global.config.src)
.pipe(exit())
})
gulp.task('kill:slowly', () => gulp.src(global.config.src)
.pipe(wait(global.config.kill.timeout))
.pipe(exit()))
gulp.task('kill:now', callback => gulpSequence('kill:instantly', 'kill:browser-sync')(callback))
gulp.task('kill:delay', callback => gulpSequence('kill:slowly', 'kill:browser-sync')(callback))
<file_sep>/src/js/foftFontLoading.js
/**
* A better font loading using FontFaceObserver.
*
* @module CriticalFOFT
* @author <NAME>
* @see https://www.zachleat.com/web/comprehensive-webfonts/#critical-foft
*/
/**
* @constructor
* @author <NAME>
* @see https://www.zachleat.com/web/comprehensive-webfonts/#critical-foft
*/
let FontFaceObserver;
// =include fontfaceobserver/fontfaceobserver.js
/**
* @function
* @name Anonymous self-invoked function
* @description Adds classes to document when each font loads successfully.
* If fonts are already loaded, then skip loading.
*/
(function () {
if (window.sessionStorage.criticalFoftDataUriFontsLoaded1) {
document.documentElement.className += ' fonts-stage-1 fonts-stage-2'
return
}
/**
* A subset of default font type.
*
* @const
* @name fontASubset
* @type {Object}
*/
const fontASubset = new FontFaceObserver('Vollkorn Subset', {
weight: 'normal',
style: 'normal'
})
/**
* A promise that adds 'fonts-stage-1' if {@link fontASubset}
* is loaded successfully.
*
* @method
* @name Promise
*/
Promise.all([fontASubset.load()]).then(() => {
document.documentElement.className += ' fonts-stage-1'
/**
* Default font type.
*
* @const
* @name fontA
* @type {Object}
*/
const fontA = new FontFaceObserver('Vollkorn', {
weight: 'normal',
style: 'normal'
})
console.log(`Subset font1 loaded.`)
/**
* A promise that adds 'fonts-stage-2' if
* {@link fontA}
* are loaded successfully.
* Also, set Critical FOFT session variable to true.
*
* @method
* @name Promise
*/
Promise.all([fontA.load()]).then(() => {
document.documentElement.className += ' fonts-stage-2'
// Optimization for Repeat Views
window.sessionStorage.criticalFoftDataUriFontsLoaded1 = true
console.log(`Main font1 loaded.`)
}, () => {
console.log(`Main font1 not loaded.`)
})
}, () => {
console.log(`Subset font1 not loaded.`)
})
})();
(() => {
if (window.sessionStorage.criticalFoftDataUriFontsLoaded2) {
document.documentElement.className += ' fonts-stage-3 fonts-stage-4'
return
}
/**
* A subset of default font type.
*
* @const
* @name fontASubset
* @type {Object}
*/
const fontBSubset = new FontFaceObserver('Playfair Display Bold Subset', {
weight: 700,
style: 'normal'
})
/**
* A promise that adds 'fonts-stage-1' if {@link fontASubset}
* is loaded successfully.
*
* @method
* @name Promise
*/
Promise.all([fontBSubset.load()]).then(() => {
document.documentElement.className += ' fonts-stage-3'
/**
* Default font type.
*
* @const
* @name fontA
* @type {Object}
*/
const fontB = new FontFaceObserver('Playfair Display Bold', {
weight: 700,
style: 'normal'
})
console.log(`Subset font2 loaded.`)
/**
* A promise that adds 'fonts-stage-2' if
* {@link fontA}
* are loaded successfully.
* Also, set Critical FOFT session variable to true.
*
* @method
* @name Promise
*/
Promise.all([fontB.load()]).then(() => {
document.documentElement.className += ' fonts-stage-4'
// Optimization for Repeat Views
window.sessionStorage.criticalFoftDataUriFontsLoaded2 = true
console.log(`Main font2 loaded.`)
}, () => {
console.log(`Main font2 not loaded.`)
})
}, () => {
console.log(`Subset font2 not loaded.`)
})
})()
| f2f96a353e148d58e7ede73c5127e00f3d72632d | [
"JavaScript"
] | 2 | JavaScript | maxknee/hexo-theme-sb | 31bef6ab27981eb4dbd6af0529cc16ab7d502a3d | df03d38a5ee3d8d82f86cd589bf0d328ad350e98 |
refs/heads/main | <repo_name>zeeshanarif513/android-widgets<file_sep>/README.md
# android-widgets
Android widgets implementation
It includes
- Checkbox
- ListView
- Radio Button
- Spinner
<file_sep>/app/src/main/java/com/example/widgets/ListViewImplementation.java
package com.example.widgets;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ListViewImplementation extends AppCompatActivity {
ListView lv;
String [] countries={"Pakistan","Iran","Afghanistan","Saudia Arabia","Turkey","UAE","Qatar","Malayshia","Chaina","America","Rusia","Canada","England","Itly","France","South Koria"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_implementation);
lv=findViewById(R.id.lst);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,countries);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),"You selected "+countries[position],Toast.LENGTH_SHORT).show();
}
});
}
}
<file_sep>/app/src/main/java/com/example/widgets/SpinnerImplementation.java
package com.example.widgets;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class SpinnerImplementation extends AppCompatActivity {
Spinner sp,sp2;
String [] countries={"Pakistan","Iran","Afghanistan","Saudia Arabia","Turkey","UAE","Qatar","Malayshia","Chaina","America","Rusia","Canada","England","Itly","France","South Koria"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_implementation);
sp=(Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,countries);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int index=sp.getSelectedItemPosition();
Toast.makeText(getApplicationContext(),"You select "+ countries[index],Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
sp2=(Spinner)findViewById(R.id.spinner2);
sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),"You select "+ sp2.getSelectedItem(),Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
| 73e813bbdaf0356de72ce3323e8c2f76c1c7232d | [
"Markdown",
"Java"
] | 3 | Markdown | zeeshanarif513/android-widgets | fdbe6b79e8a23a9dbe454a78be4598f3178c3637 | 9ae23ed4383fda149cc6498035e278fc592b3898 |
refs/heads/master | <file_sep>//
// Conversions.swift
// MyWeather
//
// Created by <NAME> on 2018-11-16.
// Copyright © 2018 redesajn interactive solutions ab. All rights reserved.
//
import Foundation
extension Double {
func celsiusToFahrenheit() -> Double {
let t = self * 9 / 5 + 32
return t
}
func fahrenheitToCelsius() -> Double {
let t = (self - 32) * 5 / 9
return t
}
}
<file_sep>//
// WeatherDataModel.swift
// WeatherApp
//
// Created by <NAME> on 2018-11-16
// Copyright (c) 2018 redesajn interactive solutions ab. All rights reserved.
//
import UIKit
class WeatherDataModel {
//Declare your model variables here
var temperature : Double = 0
var conditionCode : Int = 0
var conditionText : String = ""
var city : String = ""
var country : String = ""
var weatherIconName : String = ""
var pressure : Int = 0
var windDeg : Int = 0
var windSpeed : Int = 0
var humidity : Int = 0
var cloudPercentage : Int = 0
var visibility : Int = 0
var sunrise : String = ""
var sunset : String = ""
var latitude : Double = 0
var longitude : Double = 0
var timeOfDataCalc : String = ""
var hasData : Bool = false
var isCelsius = true
//This method turns a condition code into the name of the weather condition image
func updateWeatherIcon(conditionCode: Int) -> String {
switch (conditionCode) {
case 0...299 :
return "tstorm1"
//case 301...500 :
case 300...501 :
return "light_rain"
case 502...599 :
return "shower3"
//case 600...700 :
case 600...699 :
return "snow4"
case 701...771 :
return "fog"
case 772...799 :
return "tstorm3"
case 800 :
return "sunny"
case 801...804 :
return "cloudy2"
case 900...902, 905...1000 :
return "tstorm3"
case 903 :
return "snow5"
case 904 :
return "sunny"
default :
return "dunno"
}
}
func getWeatherInSwedish(conditionCode: Int) -> String {
switch (conditionCode) {
case 200:
return "Åska med lätt regn"
case 201:
return "Åska med regn"
case 202:
return "Åska med kraftigt regn"
case 210:
return "Lätt åska"
case 211:
return "Åska"
case 212:
return "Kraftig åska"
case 221:
return "Utspridd åska"
case 230:
return "Åska med lätt duggregn"
case 231:
return "Åska med duggregn"
case 232:
return "Åska med kraftigt duggregn"
case 300:
return "Lågintensivt duggregn"
case 301:
return "Duggregn"
case 302:
return "Högintensivt duggregn"
case 310:
return "Lågintensivt duggregn"
case 311:
return "Duggregn"
case 312:
return "Högintensivt duggregn"
case 313:
return "Regnskurar och duggregn"
case 314:
return "Kraftiga regnskurar och duggregn"
case 321:
return "Skurar med duggregn"
case 500:
return "Lätt regn"
case 501:
return "Måttligt regn"
case 502:
return "Högintensivt regn"
case 503:
return "Mycket kraftigt regn"
case 504:
return "Extremt regn"
case 511:
return "Underkylt regn"
case 520:
return "Lågintensiva regnskurar"
case 521:
return "Regnskurar"
case 522:
return "Högintensiva regnskurar"
case 531:
return "Utspridda regnskurar"
case 600:
return "Lätt snöfall"
case 601:
return "Snöfall"
case 602:
return "Kraftigt snöfall"
case 611:
return "Snöblandat regn"
case 612:
return "Snöblandade regnskurar"
case 615:
return "Lätt regn och snö"
case 616:
return "Regn och snö"
case 620:
return "Lätta skurar med snö"
case 621:
return "Skurar med snö"
case 622:
return "Kraftiga skurar med snö"
case 701:
return "Dimma"
case 711:
return "Rök"
case 721:
return "Dis"
case 731:
return "Sand, dammvirvlar"
case 741:
return "Kraftig dimma"
case 751:
return "Sand"
case 761:
return "Damm"
case 762:
return "Vulkanisk aska"
case 771:
return "Vindbyar"
case 781:
return "Tornado"
case 800:
return "Klar himmel"
case 801:
return "Enstaka moln"
case 802:
return "Utspridda moln"
case 803:
return "Brutna moln"
case 804:
return "Mulet"
default:
return "?"
}
}
}
<file_sep>//
// DarkSkyWeatherModel.swift
// MyWeather
//
// Created by <NAME> on 2018-12-08.
// Copyright © 2018 Redesajn Interactive Solutions. All rights reserved.
//
import Foundation
class DarkSkyWeatherDataModel {
//Declare your model variables here
var temperature : Double = 0
var dewPoint : Double = 0
var conditionCode : Int = 0
var conditionText : String = ""
var city : String = ""
var country : String = ""
var weatherIconName : String = ""
var pressure : Int = 0
var windDeg : Int = 0
var windSpeed : Int = 0
var humidity : Int = 0
var cloudPercentage : Int = 0
var visibility : Int = 0
var sunrise : String = ""
var sunset : String = ""
var latitude : Double = 0
var longitude : Double = 0
var timeOfDataCalc : String = ""
var hasData : Bool = false
var isCelsius = true
}
<file_sep>//
// ViewController.swift
// WeatherApp
//
// Created by <NAME> on 2018-11-16.
// Copyright (c) 2018 Redesajn Interactive Solutions. All rights reserved.
//
import UIKit
import CoreLocation
import Alamofire
import LatLongToTimezone
import SwiftyJSON
//import LatLongToTimezone
//import StringExtensions
class WeatherViewController: UIViewController, CLLocationManagerDelegate, ChangeCityDelegate {
//Constants
// OpenWeatherMap
let WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather"
let APP_ID = "6d782de5b8f6e4993751482e1bbb8ce3"
// DarkSky
let WEATHER_URL2 = "https://api.darksky.net/forecast"
let APP_ID2 = "54850b7eb2c2f396abe26747ba18d351"
//TODO: Declare instance variables here
let locationManager = CLLocationManager()
let weatherDataModel = WeatherDataModel()
let darkSkyWeatherDataModel = DarkSkyWeatherDataModel()
//Pre-linked IBOutlets
@IBOutlet weak var weatherIcon: UIImageView!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var conditionLabel: UILabel!
@IBOutlet weak var pressureLabel: UILabel!
@IBOutlet weak var windDirectionLabel: UILabel!
@IBOutlet weak var windSpeedLabel: UILabel!
@IBOutlet weak var visibilityLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var cloudsLabel: UILabel!
@IBOutlet weak var sunriseLabel: UILabel!
@IBOutlet weak var sunsetLabel: UILabel!
@IBOutlet weak var latLabel: UILabel!
@IBOutlet weak var longLabel: UILabel!
@IBOutlet weak var timeOfDataCalcLabel: UILabel!
@IBAction func WeatherUpdate(_ sender: Any) {
setCurrentLocation()
}
@IBAction func changeTempUnit(_ sender: Any) {
//let temp : String = String(describing: temperatureLabel.text!.removeTemperatureUnitFromString())
let temp : String = String(describing: temperatureLabel.text!.dropLast())
if temp.isNumeric() {
//if (temperatureLabel.text?.removeLast2Chars().isNumeric())! {
//weatherDataModel.temperature = Double(temp)!
if weatherDataModel.isCelsius {
weatherDataModel.isCelsius = false
weatherDataModel.temperature = weatherDataModel.temperature.celsiusToFahrenheit()
temperatureLabel.text = "\(Int(weatherDataModel.temperature))℉"
}
else {
weatherDataModel.isCelsius = true
weatherDataModel.temperature = weatherDataModel.temperature.fahrenheitToCelsius()
temperatureLabel.text = "\(Int(weatherDataModel.temperature))℃"
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
//TODO:Set up the location manager here.
setCurrentLocation()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(AppInFocus ), name: UIApplication.willEnterForegroundNotification, object: nil)
}
@objc func AppInFocus() {
setCurrentLocation()
}
//MARK: - Networking
/***************************************************************/
//Write the getWeatherData method here:
func getWeatherData(url: String, params: [String : String]){
Alamofire.request(url, method: .get, parameters: params).responseJSON {
response in
if response.result.isSuccess{
//print("Success! Got the weather data")
//print(JSON(response.result.value as Any))
let weatherJSON : JSON = JSON(response.result.value!)
self.updateWeatherData(json: weatherJSON)
}
else {
print("Error \(String(describing: response.result.error))")
self.cityLabel.text = "Connection Issues"
}
}
}
func getDarkSkyWeatherData(url: String, params: [String : String]) {
let requestUrl = url + "/" + APP_ID2 + "/" + params["lat"]! + "," + params["lon"]!
Alamofire.request(requestUrl, method: .get).responseJSON { (response) in
if response.result.isSuccess {
print("Success from DarkSky!")
print(JSON(response.result.value as Any))
let weatherJSON : JSON = JSON(response.result.value!)
self.updateDarkSkyWeatherData(json: weatherJSON)
}
else {
print("Error \(String(describing: response.result.error))")
}
}
//Alamofire.request(requestUrl, method: .get, parameters: params).responseJSON { (response) in
// if response.result.isSuccess {
// print("Success from DarkSky!")
// print(JSON(response.result.value as Any))
// }
// else {
// print("Error \(String(describing: response.result.error))")
// }
//}
}
//MARK: - JSON Parsing
/***************************************************************/
//Write the updateWeatherData method here:
func updateWeatherData(json : JSON){
if let temperature = json["main"]["temp"].double {
weatherDataModel.temperature = temperature // - 273.15)
weatherDataModel.city = json["name"].stringValue
weatherDataModel.country = json["sys"]["country"].stringValue
weatherDataModel.conditionCode = json["weather"][0]["id"].intValue
//weatherDataModel.conditionText = json["weather"][0]["description"].stringValue.firstUppercased //json["weather"][0]["main"].stringValue
weatherDataModel.conditionText = weatherDataModel.getWeatherInSwedish(conditionCode: weatherDataModel.conditionCode)
weatherDataModel.pressure = json["main"]["pressure"].intValue // Int(json["main"]["pressure"].doubleValue)
weatherDataModel.windDeg = json["wind"]["deg"].intValue
weatherDataModel.windSpeed = json["wind"]["speed"].intValue // Int(json["wind"]["speed"].doubleValue)
weatherDataModel.humidity = json["main"]["humidity"].intValue
weatherDataModel.cloudPercentage = json["clouds"]["all"].intValue
weatherDataModel.visibility = json["visibility"].intValue
//let unixTimeStamp = json["sys"]["sunrise"].stringValue
//let myFloat = (unixTimeStamp as NSString).doubleValue
//weatherDataModel.sunrise = unixTimeToDate(unixTime: myFloat)
//weatherDataModel.sunset = json["sys"]["sunset"].doubleValue
//let zone = weatherDataModel.city //json["sys"]["country"].stringValue
//weatherDataModel.sunrise = unixTimeToDate(unixTime: json["sys"]["sunrise"].doubleValue, timeZone: zone)
//weatherDataModel.sunset = unixTimeToDate(unixTime: json["sys"]["sunset"].doubleValue, timeZone: zone)
let lat = json["coord"]["lat"].doubleValue
let long = json["coord"]["lon"].doubleValue
let location = CLLocationCoordinate2D(latitude: lat, longitude: long)
let timeZone = TimezoneMapper.latLngToTimezoneString(location)
weatherDataModel.sunrise = unixTimeToDate(unixTime: json["sys"]["sunrise"].doubleValue, timeZone: timeZone)
weatherDataModel.sunset = unixTimeToDate(unixTime: json["sys"]["sunset"].doubleValue, timeZone: timeZone)
weatherDataModel.latitude = lat
weatherDataModel.longitude = long
//print(unixTimeToDate(unixTime: json["dt"].doubleValue, timeZone: timeZone))
weatherDataModel.timeOfDataCalc = unixTimeToDate(unixTime: json["dt"].doubleValue, timeZone: timeZone)
weatherDataModel.hasData = true
}
else {
weatherDataModel.conditionCode = -1
weatherDataModel.hasData = false
}
weatherDataModel.weatherIconName = weatherDataModel.updateWeatherIcon(conditionCode: weatherDataModel.conditionCode)
self.updateUIWithWeatherData()
}
func updateDarkSkyWeatherData(json: JSON){
if let temperature = json["currently"]["temperature"].double {
darkSkyWeatherDataModel.temperature = temperature
}
}
//MARK: - Converters
/***************************************************************/
func unixTimeToDate(unixTime : Double, timeZone : String) -> String {
let date = Date(timeIntervalSince1970: unixTime)
let dateFormatter = DateFormatter()
//dateFormatter.timeZone = TimeZone(abbreviation: timeZone) // "GMT") //Set timezone that you want
//dateFormatter.timeZone = TimeZone.knownTimeZoneIdentifiers.first(where: timeZone)
dateFormatter.timeZone = TimeZone(identifier: timeZone)
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "HH:mm" //Specify your format that you want
let strDate = dateFormatter.string(from: date)
return strDate
}
//MARK: - UI Updates
/***************************************************************/
//Write the updateUIWithWeatherData method here:
func updateUIWithWeatherData() {
if weatherDataModel.hasData {
conditionLabel.text = weatherDataModel.conditionText
temperatureLabel.text = "\(Int(darkSkyWeatherDataModel.temperature))℃"
cityLabel.text = "\(weatherDataModel.city), \(weatherDataModel.country)"
pressureLabel.text = "\(weatherDataModel.pressure) hPa"
windDirectionLabel.text = "\(weatherDataModel.windDeg)°"
windSpeedLabel.text = "\(weatherDataModel.windSpeed) m/s"
visibilityLabel.text = "Sikt: \(Double(weatherDataModel.visibility/1000)) km"
humidityLabel.text = "Fuktighet: \(weatherDataModel.humidity)%"
cloudsLabel.text = "Moln: \(weatherDataModel.cloudPercentage)%"
sunriseLabel.text = "Soluppgång: \(weatherDataModel.sunrise)"
sunsetLabel.text = "Solnedgång: \(weatherDataModel.sunset)"
//localTimeLabel.text = "Lokal tid: \(weatherDataModel.localTime)"
timeOfDataCalcLabel.text = "Tid för väderberäkning: \(weatherDataModel.timeOfDataCalc) lokal tid"
var lat : String = "Lat: \(weatherDataModel.latitude)"
var long : String = "Long: \(weatherDataModel.longitude)"
if weatherDataModel.latitude > 0 {
lat += " N"
}
else if weatherDataModel.latitude < 0 {
lat += " S"
}
if weatherDataModel.longitude > 0 {
long += " E"
}
else if weatherDataModel.longitude < 0 {
long += " W"
}
latLabel.text = lat
longLabel.text = long
}
else {
conditionLabel.text = ""
cityLabel.text = "Väder ej tillgängligt" // "Weather Unavailable"
temperatureLabel.text = "--℃"
pressureLabel.text = "-- hPa"
windDirectionLabel.text = "--°"
windSpeedLabel.text = "-- m/s"
visibilityLabel.text = "Sikt: -- m"
humidityLabel.text = "Fuktighet: --%"
cloudsLabel.text = "Moln: --%"
sunriseLabel.text = "Soluppgång: --:--"
sunsetLabel.text = "Solnedgång: --:--"
//localTimeLabel.text = "Lokal tid: --:--"
timeOfDataCalcLabel.text = "Tid för väderberäkning: --:--"
latLabel.text = "Lat: --.--"
longLabel.text = "Long: --.--"
}
weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
}
//MARK: - Location Manager Delegate Methods
/***************************************************************/
//Write the didUpdateLocations method here:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[locations.count - 1]
if(location.horizontalAccuracy > 0){
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
print("longitude = \(location.coordinate.longitude), latitude = \(location.coordinate.latitude)")
let long = String(location.coordinate.longitude)
let lat = String(location.coordinate.latitude)
let params : [String : String] = ["lat" : lat, "lon" : long, "units" : "metric", "appid" : APP_ID]
getWeatherData(url: WEATHER_URL, params: params)
let params2 : [String : String] = ["lat" : lat, "lon" : long, "units" : "metric", "appid" : APP_ID2]
getDarkSkyWeatherData(url: WEATHER_URL2, params: params2)
}
}
//Write the didFailWithError method here:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
cityLabel.text = "Plats otillgänglig" // "Location unavailable"
}
//MARK: - Change City Delegate methods
/***************************************************************/
func setCurrentLocation(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
//Write the userEnteredANewCityName Delegate method here:
func UserEnteredANewCityName(city: String) {
let params : [String : String] = ["q" : city, "units" : "metric", "appid" : APP_ID]
getWeatherData(url: WEATHER_URL, params: params)
}
//Write the PrepareForSegue Method here
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "changeCityName" {
let destinationVC = segue.destination as! ChangeCityViewController
destinationVC.delegate = self
}
}
}
<file_sep>//
// StringExtensions.swift
// MyWeather
//
// Created by <NAME> on 2018-11-16.
// Copyright © 2018 redesajn interactive solutions ab. All rights reserved.
//
import Foundation
extension String {
var firstUppercased: String {
guard let first = first else { return "" }
return String(first).uppercased() + dropFirst()
}
// The following code is just another way of doing it, i.e. the following code
// does the same as firstUppercased above
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
func isNumeric() -> Bool {
return Double(self) != nil
}
func removeLast2Chars() -> Substring {
let endIndex = self.index(self.endIndex, offsetBy: -2)
return self[..<endIndex]
}
}
extension Substring {
func isNumeric() -> Bool {
return Double(self) != nil
}
}
| b414f97a8d50afa090361df328bf3997650ea301 | [
"Swift"
] | 5 | Swift | pecen/MyWeather | 42f6502e067043a3eb619da93ac03ce874c60016 | fc9891788f3c2c0240ded3003f66b6c1157a25be |
refs/heads/master | <file_sep>package cn.maiba.control;
import javax.servlet.http.HttpServletRequest;
import cn.maiba.dao.CommentDao;
import cn.maiba.dao.ExpeDao;
import cn.maiba.model.Comment;
import cn.maiba.model.User;
public class CommentControl {
private HttpServletRequest request;
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public String add() {
String articleId = request.getParameter("articleId");
String content = request.getParameter("commContent");
User user = (User) request.getSession().getAttribute("user");
if(user == null) {
request.setAttribute("failure_message", "请先登录!");
return "result/failure.jsp";
}
Comment comment = new Comment(content, Integer.parseInt(articleId), user.getId());
CommentDao dao = new CommentDao();
//用户评论数量+1
ExpeDao.addComment(user.getId()+"");
String result = "";
if(dao.save(comment)) {
result = "/logon/Article_detail.do?articleId="+articleId;
}
return result;
}
}
<file_sep>package cn.maiba.model;
public class Notice {
public static String TABLE_NAME = "t_notice";
private String content;
private String author;
public Notice() {
super();
// TODO Auto-generated constructor stub
}
public Notice(String content, String author) {
super();
this.content = content;
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
<file_sep>package cn.maiba.util;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
public class UrlUtil {
//�Զ���request�ж���url����ʽ��http://localhost:8080/JavaWeb/user/detail.do?userId=1
public static String getURL(HttpServletRequest request) {
String url = "";
url = request.getRequestURI()+"?";
url += param(request);
url = url.replaceFirst("/JavaWeb", "");
return url;
}
private static String param(HttpServletRequest request) {
// TODO Auto-generated method stub
String url = "";
Enumeration param = request.getParameterNames();
while(param.hasMoreElements()) {
String pname = param.nextElement().toString();
url += pname + "=" + request.getParameter(pname) + "&";
}
if(url.endsWith("&")) {
url = url.substring(0, url.lastIndexOf("&"));
}
return url;
}
}
<file_sep>package cn.maiba.control;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.maiba.dao.ExpeDao;
import cn.maiba.dao.ForBiddenUserDao;
import cn.maiba.dao.UserDao;
import cn.maiba.model.User;
import cn.maiba.util.EmailSender;
public class UserControl {
private HttpServletRequest request;
private HttpServletResponse response;
UserDao userDao = new UserDao();
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public String list() {
List<User> userList = null;
User user = (User) request.getSession().getAttribute("user");
if(user == null) {
request.setAttribute("failure_message", "您无此权限查看");
return "result/failure.jsp";
}
if(!user.getIsAdmin()) {
request.setAttribute("failure_message", "您无此权限查看");
return "result/failure.jsp";
}
String searchValue = request.getParameter("searchValue");
if(searchValue != null) {
userList = userDao.usersLike(searchValue);
}else {
userList = userDao.list();
}
request.setAttribute("userList", userList);
return "logon/userList.jsp";
}
public String handleLogon() {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
HttpSession session = request.getSession();
String result = "";
if(userName==null || password==null || "".equals(userName) || "".equals(password)) {
result = "result/failure.jsp";
}
//密码是否输入错误
if(session.getAttribute("errorPwd")!=null) {
String error = (String) session.getAttribute("errorPwd");
System.out.println(error);
if(Integer.parseInt(error) <=1) {
String imgID = request.getParameter("imgID");
System.out.println(imgID+":"+(String)session.getAttribute("rand"));
if(!imgID.equals((String)session.getAttribute("rand"))) {
request.setAttribute("failure_message", "验证码错误!");
return "userLogon.jsp";
}
}else {
//密码错误三次,锁定账号一小时
request.setAttribute("failure_message", "密码错误三次,将锁定账号一小时");
System.out.println("锁定账号" + userName);
//将账户锁定
ForBiddenUserDao.addForbiddenUser(userName);
request.getSession().setAttribute("forbiddenUser", userName);
request.getSession().removeAttribute("errorPwd");
return "userLogon.jsp";
}
}
List<User> userList = userDao.list(userName);
if(userList == null || userList.size()<=0) {
request.setAttribute("failure_message", "你提交的用户不存在");
result = "userLogon.jsp";
}else {
User user = (User)userList.get(0);
if(user.getPassword().equals(password)) {
session.setAttribute("user", user);
session.removeAttribute("errorPwd");
//增加登录次数
ExpeDao.addLogon(user.getId()+"");
String url = (String)session.getAttribute("forwardURL");
if(url!=null) {
session.removeAttribute("forwardURL");
result = url;
}else {
try {
response.sendRedirect("Article_list.do");
return null;
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
//若错误一次,则需要输入验证码
String error = "1";
if(session.getAttribute("errorPwd") != null) {
error = (String)session.getAttribute("errorPwd");
error = (Integer.parseInt(error) + 1) + "";
}
session.setAttribute("errorPwd", error);
request.setAttribute("failure_message", "用户名或者密码错误");
result = "userLogon.jsp";
}
}
return result;
}
public String handleRegister() {
String userName = request.getParameter("username");
String password = request.getParameter("password");
String nickName = request.getParameter("nickName");
String age = request.getParameter("age");
String email = request.getParameter("email");
User user = new User();
user.setUserName(userName);
user.setPassword(<PASSWORD>);
user.setAge(Integer.parseInt(age));
user.setNickName(nickName);
user.setEmail(email);
List userList;
try {
UserDao userDao = new UserDao();
userList = userDao.list(userName);
if(userList == null || userList.size()<=0) {
userDao.save(user);
request.setAttribute("success_message", "注册成功");
//向注册用户发送通知
EmailSender sender = new EmailSender(user.getEmail(), user.getUserName()+",欢迎来到麦吧");
sender.send();
}else {
request.setAttribute("failure_message", "注册失败");
}
} catch (Exception e) {
e.printStackTrace();
}
return "result/success.jsp";
}
public String back() {
List userList = new UserDao().list();
request.setAttribute("userList", userList);
return "logon/userList.jsp";
}
public String Logon() {
return "userLogon.jsp";
}
public String logout() {
request.getSession().removeAttribute("user");
return "userLogon.jsp";
}
public String Register() {
// TODO Auto-generated method stub
return "userRegister.jsp";
}
}
<file_sep>package cn.maiba.model;
public class PageBean {
private int totalPage; //总页数
private int currentPage; //当前页
private int size = 5; //每页记录
private int count; //总记录数
private int start; //第几条开始查询
public PageBean() {
super();
// TODO Auto-generated constructor stub
}
public PageBean(int count, int currentPage, int size) {
super();
this.count = count;
this.currentPage = currentPage;
this.size = size;
}
public int getStart() {
return this.currentPage*this.size;
}
public int getTotalPage() {
return count%size==0?count/size:count/size+1;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
<file_sep>package cn.maiba.model;
public class Type {
public static final String TABLE_NAME = "t_type";
private int id;
private String type;
private int userId;
public Type() {
super();
// TODO Auto-generated constructor stub
}
public Type(String type) {
super();
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
<file_sep>package cn.maiba.util;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailSender {
//发件人邮箱的SMTP服务器
private final String qqHost = "smtp.qq.com";
//发件人的邮箱账号
private String userName = "995011833";
//发件人的邮箱密码
private String password = "<PASSWORD>";
//发件人的邮箱
private String from = "<EMAIL>";
//要发送的邮箱
private String to;
//邮箱标题
private String title = "麦吧论坛通知";
//邮箱内容
private String message;
public void send() {
//创建邮件属性
Properties p = new Properties();
p.put("mail.smtp.host", qqHost);
p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
p.setProperty("mail.smtp.socketFactory.fallback", "false");
p.put("mail.smtp.auth", "true");
Session mailSession = Session.getDefaultInstance(p);
mailSession.setDebug(true);
//创建一个消息
Message msg = new MimeMessage(mailSession);
try {
//发件人地址
InternetAddress fromAddr = new InternetAddress(from);
msg.setFrom(fromAddr);
//收件人的地址
InternetAddress toAddr = new InternetAddress(to);
msg.setRecipient(Message.RecipientType.TO, toAddr);
//添加邮件日期
msg.setSentDate(new Date());
msg.setSubject(title);
//添加内容
if(message != null && message.trim().length() > 0) {
msg.setText(message);
}else {
msg.setText("No message to be sent!");
}
msg.saveChanges();
int nMailPort = 465;
Transport transport = mailSession.getTransport("smtp");
transport.connect(qqHost, nMailPort, userName, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("邮件发送成功");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public EmailSender() {
super();
// TODO Auto-generated constructor stub
}
public EmailSender(String to, String message) {
super();
this.to = to;
this.message = message;
}
public EmailSender(String userName, String password, String from, String to, String title, String message) {
super();
this.userName = userName;
this.password = <PASSWORD>;
this.from = from;
this.to = to;
this.title = title;
this.message = message;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getQqHost() {
return qqHost;
}
}
<file_sep>package cn.maiba.log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UserLog {
public static String logFileName = "";
public static synchronized void log(String content) {
SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd");
logFileName = "E:/Java/eclipse/worksplace/mcba/WebContent/log/"+format.format(new Date()) + ".txt";
File file = new File(logFileName);
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(file, true));
bw.write(new Date() + " : " + content + "\r\n");
bw.flush();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>package cn.maiba.listener;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import cn.maiba.dao.ForBiddenUserDao;
import cn.maiba.model.ForbiddenUser;
@WebListener
public class ContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
//每小时扫描一次,解锁已锁定超过一小时的用户
Timer timer = new Timer(true);
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
List<ForbiddenUser> fUserList = new ForBiddenUserDao().list();
System.out.println(fUserList.size());
if(fUserList != null) {
Calendar now = Calendar.getInstance();
System.out.println("定时器扫描,解除锁定用户");
for (ForbiddenUser fUser : fUserList) {
if(now.getTimeInMillis() - fUser.getForbiddenTime().getTime()>2*60*1000) {
//将被锁定一小时的用户解锁,从t_forbiddenuser表中删除
new ForBiddenUserDao().delete(fUser.getUserName());
System.out.println("un...lock");
}
}
}
}
}, 0, 60*1000);
}
}
<file_sep>package cn.maiba.control;
import javax.servlet.http.HttpServletRequest;
import cn.maiba.dao.UserDao;
import cn.maiba.model.User;
public class LogonControl {
private HttpServletRequest request;
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public String detail() {
// TODO Auto-generated method stub
UserDao userDao = new UserDao();
String result = "";
int userId = Integer.parseInt(request.getParameter("userId"));
User user = (User) request.getSession().getAttribute("user");
if(!user.getIsAdmin() && user.getId()!=userId) {
request.setAttribute("failure_message", "您无此权限查看");
return "result/failure.jsp";
}
User u = userDao.load(userId);
request.setAttribute("u", u);
result = "logon/userDetail.jsp";
return result;
}
public String modify() {
User user = (User) request.getSession().getAttribute("user");
int id = Integer.parseInt(request.getParameter("userId"));
if(!user.getIsAdmin() && user.getId()!=id) {
request.setAttribute("failure_message", "您无此权限查看");
return "result/failure.jsp";
}
String result = "";
request.setAttribute("userId", id);
String userName = request.getParameter("userName");
String password = request.getParameter("password");
int age = Integer.parseInt(request.getParameter("age"));
String nickName = request.getParameter("nickName");
String email = request.getParameter("email");
UserDao userDao = new UserDao();
User u = userDao.load(id);
u.setUserName(userName);
u.setPassword(<PASSWORD>);
u.setAge(age);
u.setEmail(email);
u.setNickName(nickName);
result = "result/success-modify.jsp";
if(userDao.update(u)) {
request.setAttribute("Result_Message", "修改成功");
}else {
request.setAttribute("Result_Message", "修改失败");
}
return result;
}
public String delete(){
User user = (User) request.getSession().getAttribute("user");
if(!user.getIsAdmin()) {
request.setAttribute("failure_message", "您无此权限查看");
return "result/failure.jsp";
}
UserDao userDao = new UserDao();
String result = "result/success-modify.jsp";
int userId = Integer.parseInt(request.getParameter("userId"));
if(userDao.delete(userId)) {
request.setAttribute("Result_Message", "删除用户成功!");
}else {
request.setAttribute("Result_Message", "删除用户失败!");
}
return result;
}
}
<file_sep>package cn.maiba.model;
public class TypeUser {
private Type type;
private User user;
public TypeUser() {
super();
// TODO Auto-generated constructor stub
}
public TypeUser(Type type, User user) {
super();
this.type = type;
this.user = user;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
<file_sep>package cn.maiba.test;
public class Father {
private String father;
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
}
<file_sep>package cn.maiba.model;
import java.util.Date;
public class ForbiddenUser {
public static String TABLE_NAME = "t_forbiddenuser";
private String userName;
private Date forbiddenTime;
public ForbiddenUser() {
super();
// TODO Auto-generated constructor stub
}
public ForbiddenUser(String userName) {
super();
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Date getForbiddenTime() {
return forbiddenTime;
}
public void setForbiddenTime(Date forbiddenTime) {
this.forbiddenTime = forbiddenTime;
}
}
<file_sep># mcba
JavaWeb的大作业:
采用的技术:Servlet,JDBC
特点,封装简易的orm框架,对servlet进行封装,采用一个servlet接收所有请求,做好约定,应用反射根据URL调用相应的控制层类及执行方法,并实现简单的依赖注入
完成的基本功能有:
1.用户管理模块:
a)划分角色和权限:超级管理员(所有用户的管理:增加、删除、查询用户);版主(可以删除本版的帖子);普通用户(可以增删改自己发布的帖子,可以查看并评论所有帖子);游客(可以查看所有帖子,不能评论);
b)经验值:根据登录次数、登录时长、发布帖子数量、评论帖子数量,给予经验值,并且根据经验值给出对应的职位或者称呼;
2.发布帖子模块
a)规定帖子的阅读权限(比如游客不可看),规定评论权限(比如不可评论);
b)为版主提供帖子置顶功能;
c)论坛包括多个版面,比如体育版,生活版,学习版等等,每个版有版主。
3.查询功能模块
a)模糊查询用户;
b)根据标题或者内容,模糊查询帖子;
4.实时功能(使用HttpSessionBindingListener实现)
a)实时在线用户数(包括登录用户和guest游客(没有登录的访问用户))
b)实时登录用户数
c)记录网站的用户登录日志(登录,退出信息等)
5.账号安全
a)用户登录密码错了一次之后,下一次登录需要验证码校验码;
b)同个账号登录,密码错误3次后,锁死账号。(可以是1小时后解锁,或者通过注册邮箱发送链接解锁)
6.站内邮件功能模块
a)发送邮件通知到用户注册邮箱
<file_sep>package cn.maiba.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Reflect {
public static void main(String[] args) throws Exception{
String clazzName = "cn.maiba.test.UserService";
Object obj = Class.forName(clazzName).newInstance();
//获取所有自定的方法
Method[] ms = obj.getClass().getDeclaredMethods();
//获取自定义的所有属性
Field[] field = obj.getClass().getDeclaredFields();
int fLen = field.length;
int mLen = ms.length;
String[] modelName = new String[fLen];
String[] modelType = new String[fLen];
for(int i=0; i<fLen; i++) {
//获取属性的名字
String name = field[i].getName();
modelName[i] = name;
//获取属性的类型
String type = field[i].getType().toString();
modelType[i] = type;
field[i].setAccessible(true);
name = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
if(type.equals("class java.lang.String")){
String value = "cedo";
Method m = obj.getClass().getMethod("set"+name, String.class);
m.invoke(obj, value);
}
}
for (Field f : field) {
System.out.println(f.getType());
}
for(Method m: ms) {
System.out.println(m.getName());
}
System.out.println(field[0].get(obj));
}
}
<file_sep>package cn.maiba.handle;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HandleMapping {
public static Object getControl(String className,
HttpServletRequest request, HttpServletResponse response) {
Object obj = null;
try {
obj = Class.forName("cn.maiba.control."+className+"Control").newInstance();
//获取属性
Field[] field = obj.getClass().getDeclaredFields();
String[] modelName = new String[field.length];
String[] modelType = new String[field.length];
for(int i=0; i<field.length; i++) {
//获取属性名字
String name = field[i].getName();
//获取属性类型
String type = field[i].getGenericType().toString();
modelName[i] = name;
modelType[i] = type;
//设置素有属性为可访问
field[i].setAccessible(true);
//将属性首字符设置为大写,用于获得setter方法,如:setName(String name)
name = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
//根据属性的类型为属性赋值,待改进
if("interface javax.servlet.http.HttpServletRequest".equals(type)) {
//获得setter方法
Method m = obj.getClass().getMethod("set"+name, HttpServletRequest.class);
//执行setter赋值
m.invoke(obj, request);
}
if("interface javax.servlet.http.HttpServletResponse".equals(type)) {
Method m = obj.getClass().getMethod("set"+name, HttpServletResponse.class);
m.invoke(obj, response);
}
}
return obj;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
<file_sep>package cn.maiba.dao;
import cn.maiba.model.Experience;
public class ExpeDao {
//增加登录次数
public static boolean addLogon(String userId) {
Dao dao = new Dao();
Experience exp = (Experience) dao.list(Experience.class, "select * from t_experience where userId=?",
new Object[]{userId}, null).get(0);
exp.setLogonCount(exp.getLogonCount()+1);
return dao.update(exp);
}
//增加发帖数量
public static boolean addPublish(String userId) {
Dao dao = new Dao();
Experience exp = (Experience) dao.list(Experience.class, "select * from t_experience where userId=?",
new Object[]{userId}, null).get(0);
exp.setPublishNums(exp.getPublishNums()+1);
return dao.update(exp);
}
//增加评论数量
public static boolean addComment(String userId) {
Dao dao = new Dao();
Experience exp = (Experience) dao.list(Experience.class, "select * from t_experience where userId=?",
new Object[]{userId}, null).get(0);
exp.setCommentNums(exp.getCommentNums()+1);
return dao.update(exp);
}
//增加登录时长
public static boolean addLogonTimes(String userId, int logonTmes) {
Dao dao = new Dao();
Experience exp = (Experience) dao.list(Experience.class, "select * from t_experience where userId=?",
new Object[]{userId}, null).get(0);
exp.setLogonTimes(exp.getLogonTimes()+logonTmes);
return dao.update(exp);
}
}
<file_sep>package cn.maiba.model;
/**
* @author cedo
*
*/
public class Experience {
public static final String TABLE_NAME = "t_experience";
private int id;
private int userId;
private int logonCount; //登录次数
private int logonTimes; //登录时长
private int publishNums; //发布帖子数量
private int commentNums; //评论帖子数量
public Experience() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getLogonCount() {
return logonCount;
}
public void setLogonCount(int logonCount) {
this.logonCount = logonCount;
}
public int getLogonTimes() {
return logonTimes;
}
public void setLogonTimes(int logonTimes) {
this.logonTimes = logonTimes;
}
public int getPublishNums() {
return publishNums;
}
public void setPublishNums(int publishNums) {
this.publishNums = publishNums;
}
public int getCommentNums() {
return commentNums;
}
public void setCommentNums(int commentNums) {
this.commentNums = commentNums;
}
}
<file_sep>package cn.maiba.filter;
import java.io.IOException;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
@WebFilter(dispatcherTypes={DispatcherType.REQUEST, DispatcherType.FORWARD,DispatcherType.INCLUDE})
public class CharsetFilter implements Filter {
private String encoding;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain arg2)
throws IOException, ServletException {
// TODO Auto-generated method stub
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
arg2.doFilter(request, response);
}
@Override
public void init(FilterConfig fconfig) throws ServletException {
// TODO Auto-generated method stub
encoding = fconfig.getInitParameter("requestEncoding");
if(encoding==null) {
encoding = "utf-8";
}
}
}
| 27e0eb7e2fb0cdb9c9b7b7663a60015d4edc04dc | [
"Markdown",
"Java"
] | 19 | Java | MCeDo/mcba | a93afa6c290e33bc87e1db741419abac154441e5 | 3debead5510f761362eb2235a89d52f1fe369a65 |
refs/heads/master | <repo_name>WoonKang/ita<file_sep>/intro_01.php
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="es">
<head>
<title>I.T.Ayachcho</title>
<meta charset="utf-8">
<link href="css/templatemo_style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="./css/style_head.css">
</head>
<body>
<?php
require_once('ita-menu.php');
?>
<div id="templatemo_main">
<h2 style="margin-left:0px;">=== Saludo de RECTOR ===</h2><br>
<div style="width:300px; float:left; margin-left:30px;" >
<center>
<img src="./images/rector.png" width="153" height="126"
style="margin-top:10px; margin-left:70px;" /><br>
<p style="align:center;"><h1>RECTOR<br><NAME></h1></p>
<img src="./images/saludo.png" width="400"
style="margin-top:0px; float:left;" />
</center>
</div>
<div class="display" style="margin-left:470px;">
<video width="600" height="400" controls autoplay>
<source src="./videos/mvi_0164.mp4" type="video/mp4">
</video>
</div>
</div> <!-- END of templatemo_main -->
<!-- common bottom -->
<?php
require_once('ita-bottom.php');
?>
<file_sep>/contact.php
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="es">
<head>
<title>I.T.Ayachcho</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style_contact.css">
<link rel="stylesheet" href="css/templatemo_style.css" type="text/css" />
<link rel="stylesheet" href="css/style_head.css">
<link rel="javascript" href="js/script.gs">
</head>
<body>
<?php
require_once('ita-menu.php');
?>
<div id="templatemo_main">
<h2>===   CONTACTOS   ===</h2><br>
<div style="width:800px; float:left; margin-left:0px;">
<form id="gform" class="contact_form"
action="https://script.google.com/macros/s/AKfycbwSqFshCBT5HkIHilkrOLrGMcXHwjEwXNCcE4jF/exec"
method="post">
<ul>
<li>
<label form="name">Nombre: </label>
<input TYPE="text" name="name" SIZE="80" required />
</li>
<li>
<label form="email">Email:</label>
<input TYPE="text" name="email" SIZE="80" required />
</li>
<li>
<label form="phone">Telefono:</label>
<input TYPE="text" name="phone" SIZE="80" />
</li>
<li>
<label form="message">Mensaje:</label>
<textarea name="message" cols="80" rows="10" required ></textarea>
</li>
<li>
<button class="submit" type="submit">Enviar</button>
</li>
<br>
<p style="margin-left:110px;">==> Responderemos a su consulta por correo electrónico o por teléfono lo antes posible.</p>
</ul>
</form>
</div>
</div>
<script data-cfasync="false" type="text/javascript"
src="https://cdn.rawgit.com/dwyl/html-form-send-email-via-google-script-without-server/master/form-submission-handler.js">
</script>
<div style="display:none;" id="thankyou_message">
<h2><em>Thanks</em> for contacting us ! We wiil get back to you soon!</h2>
</div>
<!-- common bottom -->
<?php
require_once('ita-bottom.php');
?>
<file_sep>/e-learning-si-menu.php
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="es">
<head>
<title>I.T.A-eLeaning</title>
<meta charset="utf-8">
<link rel="stylesheet" href="./css/style_head.css">
<link rel="stylesheet" href="./css/style_elearning.css">
</head>
<body>
<?php
require_once('ita-elearning-top.php');
?>
<header>Instituto Tecnologico "Ayacucho"    
<a href="e-learning-menu.php" style="color:red; text-decoration:none;">            e-LEARNING system</a>
<a href="e-learning-si-menu.php" style="color:black; font-style: normal; font-size:30px; text-shadow: 2px 2px 8px #FF0000;
float:right; margin-right:150px;">Sistemas Informaticos</a>
</header>
<div class="menu_elearning">
<img src="./images/lgcarrera/information.png"
style="margin-left:250px; width:50%; position:relative; opacity:0.3;">
<div class="menu_carrera">
<div>
<ul>
<li><a style="background-color:blue; color:white; font-size:20px; padding:10px; text-align:center;"><strong>Advanced</strong></a></li><br>
</ul>
<p>   </p>
<ul class="dropdown">
<li><a href="#" class="dropbtn">Nuevos</a></li>
<div class="dropdown-content">
<a href="e-learning-si-099.php">Que es e-learning</a>
<a href="e-learning-si-100.php">Web history</a>
<a href="e-learning-si-901.php">Smart Cities</a>
<a href="#">e-Government</a>
</div></ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn">Educacion</a></li>
<div class="dropdown-content">
<a href="e-learning-si-201.php">TIC Educacion</a>
</div></ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn"></a></li>
</ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn"></a></li>
</ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn"></a></li>
</ul></div>
<p><br><br><br><br></p>
<div>
<ul>
<li><a style="background-color:blue; color:white; font-size:20px; padding:10px; text-align:center;"><strong>WEB</strong></a></li><br>
</ul>
<p>   </p>
<ul class="dropdown">
<li><a href="#" class="dropbtn">HTML</a></li>
<div class="dropdown-content">
<a href="e-learning-si-100.php">00. historia de WEB</a>
<a href="e-learning-si-101.php">01. html tag - basico</a>
<a href="#">02. tags - tipicos</a>
<a href="#">03. salto de linea</a>
<a href="#">04. gramma & img</a>
<a href="#">05. padre hijo y lista</a>
<a href="#">06. estructura del documento</a>
<a href="#">07. rey de tag</a>
</div></ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn">CSS</a></li>
<div class="dropdown-content">
<a href="#">01. aparicion de css</a>
<a href="#">02. cambio revolucionario</a>
<a href="#">03. cómo descubrir las propiedades CSS</a>
<a href="#">04. cómo descubrir el selector de CSS</a>
<a href="#">05. modelo de caja</a>
<a href="#">06. cuadrícula</a>
<a href="#">07. diseño responsivo</a>
<a href="#">08. reutilizando código CSS</a>
</div></ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn">JavaScript</a></li>
<div class="dropdown-content">
<a href="#">01. HTML Script tag</a>
<a href="#">02. Evento</a>
<a href="#">03. Consola</a>
<a href="#">04. Letras y numeros</a>
<a href="#">05. Variables y operadores de asignación</a>
<a href="#">06. Control del navegador web</a>
<a href="#">07. Seleccionar etiqueta para controlar</a>
<a href="#">08. Operadores de comparación</a>
<a href="#">09. Declaración condicional</a>
<a href="#">10. Arreglos y Bucles</a>
<a href="#">11. Funcion</a>
<a href="#">12. Objeto</a>
<a href="#">13. Bibliotecas y marcos</a>
<a href="#">14. UI vs API</a>
</div></ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn">PHP</a></li>
<div class="dropdown-content">
<a href="#">01. instalar php</a>
<a href="#">02. principio de php</a>
<a href="#">03. tipo de datos de php</a>
<a href="#">04. variables de php</a>
<a href="#">05. parámetro url</a>
<a href="#">06. función php</a>
<a href="#">07. control</a>
<a href="#">08. condicional</a>
<a href="#">09. repetir</a>
<a href="#">10. array</a>
<a href="#">11. form & post</a>
<a href="#">12. create, update, delete</a>
<a href="#">13. modularización en archivo php</a>
</div></ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn"></a></li>
</ul></div>
<p><br><br><br><br></p>
<div>
<ul>
<li><a style="background-color:blue; color:white; font-size:20px; padding:10px; text-align:center;"><strong>DATABASE</strong></a></li><br>
</ul>
<p>   </p>
<ul class="dropdown">
<li><a href="#" class="dropbtn">Database</a></li>
<div class="dropdown-content">
<a href="#">Link 21</a>
<a href="#">Link 22</a>
<a href="#">Link 23</a>
</div></ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn">MySQL</a></li>
<div class="dropdown-content">
<a href="#">Link 24</a>
<a href="#">Link 25</a>
<a href="#">Link 26</a>
</div></ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn"></a></li>
</ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn"></a></li>
</ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn"></a></li>
</ul></div>
<p><br><br><br><br></p>
<div>
<ul>
<li><a style="background-color:blue; color:white; font-size:20px; padding:10px; text-align:center;"><strong>SERVER</strong></a></li><br>
</ul>
<p>   </p>
<ul class="dropdown">
<li><a href="#" class="dropbtn">LINUX</a></li>
<div class="dropdown-content">
<a href="#">Link 31</a>
<a href="#">Link 32</a>
<a href="#">Link 33</a>
</div></ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn">AWS(Amazon W.S.)</a></li>
<div class="dropdown-content">
<a href="#">Link 34</a>
<a href="#">Link 35</a>
<a href="#">Link 36</a>
</div></ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn"></a></li>
</ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn"></a></li>
</ul>
<ul class="dropdown">
<li><a href="#" class="dropbtn"></a></li>
</ul></div>
</div>
</div>
<!-- common bottom -->
<?php
require_once('ita-bottom.php');
?>
<file_sep>/index.php
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="es">
<head>
<title>I.T.Ayachcho</title>
<meta charset="utf-8">
<link rel="stylesheet" href="./css/style_head.css">
<!-- Insert to your webpage before the </head> -->
<script src="sliderengineinmob1/jquery.js"></script>
<script src="sliderengineinmob1/amazingslider.js"></script>
<script src="sliderengineinmob1/initslider-1.js"></script>
<!-- End of head section HTML codes -->
</head>
<body>
<?php
require_once('ita-menu.php');
?>
<div style="margin-top:50px; margin-left:120px; padding:0; max-width:1100px; width:1100px; height:350px;">
<!-- Insert to your webpage where you want to display the slider -->
<div id="amazingslider-1" style="display:block;position:relative;margin:0px auto 46px;">
<ul class="amazingslider-slides" style="display:none; ">
<li><img src="slider/ita_ref_201.jpg" alt="TECNOLOGICO AYACUCHO" /></li>
<li><img src="slider/ita_ref_202.jpg" alt="TECNOLOGICO AYACUCHO" /></li>
<li><img src="slider/ita_ref_203.jpg" alt="TECNOLOGICO AYACUCHO" /></li>
</ul>
</div>
</div>
<div style="float:left; margin-left:120px;" >
<img src="./images/ita_campus.jpg" width="770" height="100" />
</div>
<div style="margin-left:900px; margin-top:40px;">
<!-- login -->
<form method="post" action="login.jsp" style="color:black;">
user-id     :   <input type="text" name="userid"><br>
password :   <input type="text" name="passwd">    
<input type="submit" value="Login">
</form>
</div>
<!-- common bottom -->
<?php
require_once('ita-bottom.php');
?>
<file_sep>/php.ini
file_uploads = On ;
; Maximum allowed size for uploaded files.
upload_max_filesize = 400M
; Must be greater than or equal to upload_max_filesize
post_max_size = 400M
<file_sep>/noticias-process-delete-foto.php
<?php
if (isset($_GET['id'])) {
$target_name = "./noticias/fotos/".$_GET['id'];
$target_foto = $target_name . '.jpg';
$check_text = "./noticias/textos/".$_GET['id'];
if(file_exists($target_foto)) {
unlink($target_foto); }
else {
echo "No esta el foto-file"; }
if(file_exists($check_text)) {
unlink('noticias/textos/'.$_GET['id']); }
else {
echo "No esta file-detalle"; }
}
else {
echo "No hay el code id"; }
header( 'Location: ./noticias-admin-fotos.php');
?>
<file_sep>/js/showhide.js
$(document).ready(function(){
// IE6 background image flicker fix
try {
document.execCommand("BackgroundImageCache", false, true);
} catch(e) {}
$('li.headlink').hover(
function() { $('ul', this).css('display', 'block'); },
function() { $('ul', this).css('display', 'none'); });
$(function() {
$("#tabs").tabs();
});
var prev = null;
$('.showhide').bind('click', null,function(event) {
var next = $(event.target).next();
next.toggle();
if (next.is(':visible') )
{
$(event.target).removeClass('showhide');
$(event.target).addClass('showhideopen');
}else
{
$(event.target).removeClass('showhideopen');
$(event.target).addClass('showhide');
}
return false;
});
var elements = $('.showhide');
for( var i = 0; i < elements.length; i++ )
{
ele = $(elements[i]);
ele.next().hide();
}
});<file_sep>/e-learning-si-100.php
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="es">
<head>
<title>I.T.A-eLeaning</title>
<meta charset="utf-8">
<link rel="stylesheet" href="./css/style_head.css">
<link rel="stylesheet" href="./css/style_elearning.css">
<style>
.display {margin-left:150px; margin-top:0px;}
</style>
</head>
<body>
<?php
require_once('ita-elearning-top.php');
?>
<header>Instituto Tecnologico "Ayacucho"    
<a href="e-learning-menu.php" style="color:red; text-decoration:none;">            e-LEARNING system</a>
<a href="e-learning-si-menu.php" style="color:black; font-style: normal; font-size:30px; text-shadow: 2px 2px 8px #FF0000;
float:right; margin-right:150px;">Sistemas Informaticos</a>
</header>
<div class="menu_elearning">
<div><br></div>
<div>
<ul>
<li><a style="background-color:blue; color:white; font-size:20px; padding:10px; text-align:center; margin-top:0px;
font-style:normal;">
<strong>WEB</strong></a></li>
<li><a style="color:Black; font-size:15px; padding:20px; text-align:center; margin-top:0px;
font-style:oblique;">Historia</a></li>
</ul>
</div>
<div class="display">
<video width="800" height="250" controls muted autoplay>
<source src="./data/si_100.mp4" type="video/mp4">
</video>
</div>
<div class="display">
<iframe src="./data/si_100.txt" style="border-color: blue; background-color: gainsboro;
width:800px; height:240px; display:block; text-align:left;"></iframe>
</div>
</div>
<!-- common bottom -->
<?php
require_once('ita-bottom.php');
?>
<file_sep>/index.md
---
aliases: php7, php5, php71
created_by: <NAME>
display_name: PHP
github_url: https://github.com/php
logo: php.png
related: language
released: June 8, 1995
short_description: PHP is a popular general-purpose scripting language that works particularly well for server-side
web development.
topic: php
url: https://secure.php.net/
wikipedia_url: https://en.wikipedia.org/wiki/PHP
---
PHP is a popular general-purpose scripting language that's particularly suited for server-side web development. PHP runtime is generally executed by webpage content, and can be added to HTML and HTML5 webpages. PHP was originally developed in 1994 by <NAME>.
| 5a812157463358a101e7555a43db76d267cca0db | [
"JavaScript",
"Markdown",
"PHP",
"INI"
] | 9 | PHP | WoonKang/ita | 8d1dcb060d7f6ddd0bef29deb5b89ba19cee67e0 | 369977da058f5da8690789bd0f4210b82bcc2331 |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 4.0.10deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 11, 2016 at 09:24 PM
-- Server version: 5.6.27-0ubuntu0.14.04.1
-- PHP Version: 5.5.9-1ubuntu4.14
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `project_school`
--
-- --------------------------------------------------------
--
-- Table structure for table `super_admin`
--
CREATE TABLE IF NOT EXISTS `super_admin` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nikname` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`users_type` int(11) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1',
`is_deleted` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `super_admin`
--
INSERT INTO `super_admin` (`id`, `nikname`, `email`, `password`, `users_type`, `status`, `is_deleted`) VALUES
(1, 'Suman', '<EMAIL>', '<PASSWORD>', 1, 1, 0);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><table border = 1>
<tr>
<th></th>
<?php
foreach( $present_month_date as $date_id => $date){
echo "<th>".$date."</th>";
}
?>
</tr>
<?php
if(!empty($attendance->attendance)){
$already_attend = (array)json_decode($attendance->attendance);
}else{
$already_attend = array();
}
echo "<tr>";
echo "<td>Student Name</td>";
foreach( $present_month_date as $date_id => $date){
echo "<td>";
if(array_key_exists( $date_id, $already_attend )){
echo "Present";
}else{
echo "Absent";
}
?>
</td>
<?php
}
echo "</tr>";
?>
<br>
<?= anchor('school-admin-attendance/student_attendance/giveAttendance/'.$previous_month, 'Previous month', array('title' => 'Previous month')); ?>
<br>
<?= anchor('school-admin-attendance/student_attendance/giveAttendance/'.$next_month, 'Next month', array('title' => 'Next month')); ?>
</table><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
$this->load->model('model_login');
}
public function index()
{
$data = array();
if (!$this->input->post()) {
$this->load->view('login', $data);
} else {
$logindata['user_name'] = $this->input->post('super_admin_email');
$logindata['password'] = md5($this->input->post('<PASSWORD>'));
$result = $this->model_login->login($logindata);
if ($result) {
if ($result->users_type == '1') {
$newdata = (object) array(
'logged_in' => TRUE,
'logged_id' => $result->id,
'users_type' => $result->users_type,
'users_nikname' => $result->nikname
);
$this->session->set_userdata('super_admin', $newdata);
redirect('super-admin-dashboard/dashboard');
} else {
$data['login_error'] = true;
$this->load->view('login', $data);
}
} else {
$data['login_error'] = true;
$this->load->view('login', $data);
}
}
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Session_year extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
$this->load->model('model_session');
if (!$this->session->userdata('super_admin')) {
redirect('super-admin-login/login');
}
}
public function addSession()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
if ($this->input->post()) {
$input_data = array(
'name' => $this->input->post('name'),
'description' => $this->input->post('description'),
'from' => $this->input->post('from_month').'/'.$this->input->post('from_year'),
'to' => $this->input->post('to_month').'/'.$this->input->post('to_year'),
'status' => $this->input->post('status')
);
$this->db->insert( 'class_session', $input_data);
redirect('super-admin-session-year/session_year/addSession');
}else{
$this->load->view('add_session', $data);
}
}
public function viewBatchSession()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
$data['sessions'] = $this->model_session->showAllBatchSession();
$this->load->view('view_batch_session', $data);
}
public function editBatchSession($id)
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
if ($this->input->post()) {
$update_data = array(
'name' => $this->input->post('name'),
'description' => $this->input->post('description'),
'from' => $this->input->post('from_month').'/'.$this->input->post('from_year'),
'to' => $this->input->post('to_month').'/'.$this->input->post('to_year'),
'status' => $this->input->post('status')
);
$this->db->update( 'class_session', $update_data, "id = " . $this->input->post('hid_id') );
redirect('super-admin-session-year/session_year/viewBatchSession');
}else{
$data['session'] = $this->model_session->showAllBatchSessionDetails($id);
$this->load->view('edit_batch_session', $data);
}
}
public function masterPasswordChange()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
if ($this->input->post()) {
$old_password = md5($this->input->post('old_password'));
$result = $this->model_login->checkOldPasswordMaster($old_password, 1);
if($result){
$this->db->update( 'master_password', array( 'password' => md5($this->input->post('new_password'))), "id = " . $data['logged_id']);
redirect('super-admin-settings/settings/masterPasswordChange');
}else{
$data['error'] = "Old password not matched";
$this->load->view('master_password_change', $data);
}
}else{
$this->load->view('master_password_change', $data);
}
}
}
<file_sep>
$("#school_name").blur(function(){
var name = $("#school_name").val();
$.ajax({
url: base_url+'super-admin-school/school/ajaxCheckForSchoolCode',
type: "POST",
data: {
name: name,
},
success: function (data) {
$("#school_code").val(data);
$( "#school_code" ).focus();
}
});
});
$("#school_code").blur(function(){
var code = $("#school_code").val();
$.ajax({
url: base_url+'super-admin-school/school/ajaxCheckForSchoolCodeExist',
type: "POST",
data: {
code: code,
},
success: function (data) {
if( data == "match" ){
$( "#school_code" ).focus();
$( ".alert-warning" ).css('display', 'block');
$( ".alert-warning" ).html('<strong>Warning!</strong> The code of school all ready exist.');
}else{
$( ".alert-warning" ).css('display', 'none');
}
}
});
});
$( "#register_form" ).submit(function( event ) {
var password = $("#password").val();
var retype = $("#retype_password").val();
if(password != retype){
$( ".alert-warning" ).css('display', 'block');
$( ".alert-warning" ).html('<strong>Warning!</strong> Password and retype password not match.');
return false;
}else{
$( ".alert-warning" ).css('display', 'none');
return true;
}
});
$( "#master_password_change_form" ).submit(function( event ) {
var password = $("#new_<PASSWORD>").val();
var retype = $("#retype_password").val();
if(password != retype){
$( ".alert-warning" ).css('display', 'block');
$( ".alert-warning" ).html('<strong>Warning!</strong> Password and retype password not match.');
return false;
}else{
$( ".alert-warning" ).css('display', 'none');
return true;
}
});
function changeStatus(id, table){
$.ajax({
url: base_url+'common/common/ajaxChangeStatus',
type: "POST",
data: {
id: id,
table: table
},
success: function (data) {
$(".status_"+id).html(data);
}
});
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Exam extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->helper('html');
$this->load->library('session');
$this->load->library('form_validation');
$this->load->model('super-admin-session-year/model_session');
$this->load->model('super-admin-exam-type/model_exam_type');
$this->load->model('model_exam');
if (!$this->session->userdata('school_admin')) {
redirect('school-admin-login/login');
}
}
public function entryOfExamReport()
{
$session_details = $this->session->userdata('school_admin');
$data['logged_id'] = $session_details->logged_id;
$data['school'] = $session_details->school;
if ($this->input->post()) {
$this->form_validation->set_rules('subject', 'Subject', 'trim|required|max_length[255]');
$this->form_validation->set_rules('marks', 'Marks', 'trim|required|max_length[255]');
$this->form_validation->set_rules('out_of', 'Total Marks', 'trim|required|max_length[255]');
$this->form_validation->set_rules('taken_by', 'Taken By', 'trim|required|max_length[255]');
$this->form_validation->set_message('required', '%s can\'t be blank');
$this->form_validation->set_message('max_length', 'Max 255 character only allowed');
if( $this->form_validation->run() === FALSE ){
$this->load->view('record_student_of_exam', $data);
}else{
$insert_data = $this->input->post();
$insert_data['school_id'] = $data['logged_id'];
$insert_data['student_id'] = 2;
$this->db->insert('exam_report', $insert_data);
redirect('school-admin-exam/exam/entryOfExamReport');
}
}else{
$data['session'] = $this->model_session->showAllSessionFrontend();
$data['types'] = $this->model_exam_type->showAllTypesFrontend();
$this->load->view('record_student_of_exam', $data);
}
}
public function viewExamTypes()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
$data['types'] = $this->model_exam_type->showAllTypes();
$this->load->view('view_exam_type', $data);
}
public function editExamType($id)
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
if ($this->input->post()) {
$this->form_validation->set_rules('exam_type', 'Exam Type', 'trim|required|max_length[255]');
$this->form_validation->set_message('required', '%s can\'t be blank');
$this->form_validation->set_message('max_length', 'Max 255 character only allowed');
if( $this->form_validation->run() === FALSE ){
$this->load->view('edit_exam_type', $data);
}else{
$this->db->update( 'exam_type', $this->input->post(), "id = " . $this->input->post('id'));
redirect('super-admin-exam-type/exam_type/viewExamTypes');
}
}else{
$data['type'] = $this->model_exam_type->showExamTypeDetails($id);
$this->load->view('edit_exam_type', $data);
}
}
}
<file_sep>
<?= form_open(); ?>
<?php
$attributes = array(
'name' => 'student_id',
'placeholder' => 'Student Id',
);
echo form_input($attributes);
?>
<?php
$attributes = array(
'name' => 'student_password',
'autocomplete' => 'off',
'placeholder' => '<PASSWORD>',
);
echo form_password($attributes);
?>
<?= form_submit('mysubmit', 'Login'); ?>
<?= form_close(); ?><file_sep><?php
Class Model_school extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function checkForShortCode($data) {
$query = $this->db->get_where('school_register', array('register_code' => $data));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
function showAllSchool() {
$query = $this->db->get_where('school_register', array('is_deleted' => 0));
$result = ($query->num_rows() > 0) ? $query->result(): '';
return $result;
}
function showAllSchoolDetails($data) {
$query = $this->db->get_where('school_register', array('id' => $data));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
}<file_sep><?= heading('Welcome Dashboard!', 1); ?>
<?= br(1); ?>
<?= anchor('school-admin-logout/logout', 'Logout', array('title' => 'Logout')); ?>
<?= br(1); ?>
<?= anchor('school-admin-student/student_register', 'Student Register', array('title' => 'Student Register')); ?>
<?= br(1); ?>
<?= anchor('school-admin-attendance/student_attendance/giveAttendance', 'Student Attendance', array('title' => 'Student Attendance')); ?>
<?= br(1); ?>
<?= anchor('school-admin-exam/exam/entryOfExamReport', 'Student Exam Report', array('title' => 'Student Exam Report')); ?>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Student_attendance extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->helper('html');
$this->load->library('session');
$this->load->model('school-admin-attendance/model_school_attendance');
if (!$this->session->userdata('student_session_jksjad787e')) {
redirect('student-login/login');
}
}
public function showAttendance( $attendance_month = NULL )
{
$session_details = $this->session->userdata('student_session_jksjad787e');
$data['logged_id'] = $session_details->logged_id;
$data['student_name'] = $session_details->student_name;
if( $attendance_month != NULL ){
$present_date_array = explode("-",$attendance_month);
$next_date = $present_date_array[0]."-".$present_date_array[1]."-01";
$data['present_month'] = $attendance_month;
}else{
$present_date = date('Y-m-d', time());
$present_date_array = explode("-",$present_date);
$next_date = $present_date_array[0]."-".$present_date_array[1]."-01";
$data['present_month'] = date('Y-m', strtotime($next_date));
}
$present_month_date[$next_date] = $next_date."<br>".date('D', strtotime($next_date));
$previous_month_date = date('Y-m-d', strtotime($next_date .' -1 day'));
$data['previous_month'] = date('Y-m', strtotime($previous_month_date));
$date_variable = 1;
$attendance = $this->model_school_attendance->showStudentAttendance( $data['logged_id'], $data['present_month'] );
//print_r($attendance); die;
while($date_variable == 1) {
$current_date_array = explode("-",$next_date);
$next_date = date('Y-m-d', strtotime($next_date .' +1 day'));
$next_ber = date('D', strtotime($next_date));
$present_date_array = explode("-",$next_date);
if( ($present_date_array[2] - $current_date_array[2]) != 1 ){
$date_variable = 2;
$first_date_next_month = $next_date;
break;
}else{
$present_month_date[$next_date] = $next_date."<br>".$next_ber;
$date_variable = 1;
}
}
$data['attendance'] = $attendance;
$data['present_month_date'] = $present_month_date;
$data['next_month'] = date('Y-m', strtotime($first_date_next_month));
$this->load->view('student_attendance_show', $data);
}
}
<file_sep><?php
Class Model_student_login extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function loginCredentials($data) {
$query = $this->db->get_where('student_register', array('student_id' => $data, 'status' => 1, 'is_deleted' => 0 ));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
}<file_sep><?php
Class Model_school_login extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function login($data) {
$query = $this->db->get_where('school_register', array('register_code' => $data['user_name'], 'password' => $data['<PASSWORD>'], 'status' => 1, 'is_deleted' => 0 ));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
function loginCredentials($data) {
$query = $this->db->get_where('school_register', array('register_code' => $data, 'status' => 1, 'is_deleted' => 0 ));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
}<file_sep><?php
Class Model_common extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function viewTableStatus( $id, $table ){
$this->db->select('status');
$query = $this->db->get_where( $table, array('id' => $id));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
}<file_sep>
<?= form_open_multipart( '', array('class' => '') ); ?>
<?= form_label('Session'); ?>
<?= form_dropdown('exam_session', $session); ?>
<?= br(1); ?>
<?= form_label('Exam Type'); ?>
<?= form_dropdown('exam_type', $types); ?>
<?= br(1); ?>
<?= form_label('Subject'); ?>
<?php
$attributes = array(
'name' => 'subject',
'class' => 'm-wrap span12',
'id' => 'subject',
);
echo form_input($attributes);
?>
<?= form_error( 'subject', '<span class = "req">', '</span>'); ?>
<?= br(1); ?>
<?= form_label('Marks'); ?>
<?php
$attributes = array(
'name' => 'marks',
'class' => 'm-wrap span12',
'id' => 'marks',
);
echo form_input($attributes);
?>
<?= form_error( 'marks', '<span class = "req">', '</span>'); ?>
<?= br(1); ?>
<?= form_label('Out of'); ?>
<?php
$attributes = array(
'name' => 'out_of',
'class' => 'm-wrap span12',
'id' => 'out_of',
);
echo form_input($attributes);
?>
<?= form_error( 'out_of', '<span class = "req">', '</span>'); ?>
<?= br(1); ?>
<?= form_label('Comments'); ?>
<?php
$attributes = array(
'name' => 'comment',
'class' => 'm-wrap span12',
'id' => 'comment',
);
echo form_textarea($attributes);
?>
<?= form_error( 'comment', '<span class = "req">', '</span>'); ?>
<?= br(1); ?>
<?= form_label('Taken By'); ?>
<?php
$attributes = array(
'name' => 'taken_by',
'class' => 'm-wrap span12',
'id' => 'taken_by',
);
echo form_input($attributes);
?>
<?= form_error( 'taken_by', '<span class = "req">', '</span>'); ?>
<?= br(1); ?>
<?php
$options = array(
'1' => 'Active',
'0' => 'Inactive',
);
echo form_dropdown('status', $options, 1, array( 'class' => 'm-wrap span12' ));
?>
<?= br(1); ?>
<button type="submit" class="btn blue"><i class="icon-ok"></i> Add</button>
<?= form_button('name','Cancel', array( 'class' => 'btn' )); ?>
<?= form_close(); ?>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Logout extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
}
public function index()
{
$this->session->unset_userdata('school_admin');
$this->session->sess_destroy();
redirect('school-admin-login/login');
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class School extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
$this->load->model('model_school');
if (!$this->session->userdata('super_admin')) {
redirect('super-admin-login/login');
}
}
public function registerSchool()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
if ($this->input->post()) {
$insert_data = $this->input->post();
$insert_data['password'] = md5($this->input->post('password'));
$this->db->insert('school_register', $insert_data);
redirect('super-admin-school/school/registerSchool');
}else{
$this->load->view('register_school', $data);
}
}
public function ajaxCheckForSchoolCode()
{
if ($this->input->is_ajax_request()) {
if($this->input->post('name')){
$name = $this->input->post('name');
$short_code = $this->checkDataBaseShortCode($name);
echo $short_code;
exit;
}else{
exit('name not found');
}
}else{
exit('No direct script access allowed');
}
}
public function checkDataBaseShortCode($name)
{
$short_code = "";
$name_array = explode(" ", $name);
foreach($name_array as $short){
$short_code .= strtoupper($short[0]);
}
$rand = rand( 1000, 9999 );
$short_code = $short_code.$rand;
$result = $this->model_school->checkForShortCode($short_code);
if($result){
$this->checkDataBaseShortCode($name);
}else{
return $short_code;
}
}
public function ajaxCheckForSchoolCodeExist()
{
if ($this->input->is_ajax_request()) {
if($this->input->post('code')){
$code = $this->input->post('code');
$result = $this->model_school->checkForShortCode($code);
if($result){
echo "match";
}else{
echo "not match";
}
exit;
}else{
exit('code not found');
}
}else{
exit('No direct script access allowed');
}
}
public function viewRegisterSchool()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['schools'] = $this->model_school->showAllSchool();
$this->load->view('view_register_school', $data);
}
public function editRegisterSchool($id)
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
if ($this->input->post()) {
$update = $this->input->post();
$this->db->update( 'school_register', $update, "id = " . $this->input->post('id'));
redirect('super-admin-school/school/viewRegisterSchool');
}else{
$data['school'] = $this->model_school->showAllSchoolDetails($id);
$this->load->view('edit_register_school', $data);
}
}
}
<file_sep><?php
Class Model_exam_type extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function showAllTypes() {
$query = $this->db->get_where('exam_type', array('is_deleted' => 0));
$result = ($query->num_rows() > 0) ? $query->result(): '';
return $result;
}
function showExamTypeDetails($data) {
$query = $this->db->get_where('exam_type', array('id' => $data));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
function showAllTypesFrontend() {
$query = $this->db->get_where('exam_type', array( 'status' => 1, 'is_deleted' => 0));
$results = ($query->num_rows() > 0) ? $query->result(): '';
if(!empty($results)){
foreach ($results as $value) {
$result[$value->id] = $value->exam_type;
}
return $result;
}else{
return $results;
}
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Student_register extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->helper('html');
$this->load->library('session');
$this->load->model('super-admin-school/model_school');
if (!$this->session->userdata('school_admin')) {
redirect('school-admin-login/login');
}
}
public function index()
{
$session_details = $this->session->userdata('school_admin');
$data['logged_id'] = $session_details->logged_id;
$data['school'] = $session_details->school;
if ($this->input->post()) {
$school_details = $this->model_school->showAllSchoolDetails($data['logged_id']);
$insert_data = $this->input->post();
$insert_data['school_id'] = $session_details->logged_id;
$insert_data['password'] = md5('<PASSWORD>');
$insert_data['created_at'] = time();
$this->db->insert('student_register', $insert_data);
$insert_id = $this->db->insert_id();
$update = array( 'student_id' => $school_details->register_code.$this->input->post('student_name')[0].$insert_id );
$this->db->update( 'student_register', $update, "id = " . $insert_id);
redirect('school-admin-student/student_register');
}else{
$this->load->view('register_student', $data);
}
}
public function ajaxCheckForSchoolCode()
{
if ($this->input->is_ajax_request()) {
if($this->input->post('name')){
$name = $this->input->post('name');
$short_code = $this->checkDataBaseShortCode($name);
echo $short_code;
exit;
}else{
exit('name not found');
}
}else{
exit('No direct script access allowed');
}
}
public function checkDataBaseShortCode($name)
{
$short_code = "";
$name_array = explode(" ", $name);
foreach($name_array as $short){
$short_code .= strtoupper($short[0]);
}
$rand = rand( 1000, 9999 );
$short_code = $short_code.$rand;
$result = $this->model_school->checkForShortCode($short_code);
if($result){
$this->checkDataBaseShortCode($name);
}else{
return $short_code;
}
}
public function ajaxCheckForSchoolCodeExist()
{
if ($this->input->is_ajax_request()) {
if($this->input->post('code')){
$code = $this->input->post('code');
$result = $this->model_school->checkForShortCode($code);
if($result){
echo "match";
}else{
echo "not match";
}
exit;
}else{
exit('code not found');
}
}else{
exit('No direct script access allowed');
}
}
public function viewRegisterSchool()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['schools'] = $this->model_school->showAllSchool();
$this->load->view('view_register_school', $data);
}
public function editRegisterSchool($id)
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
if ($this->input->post()) {
$update = $this->input->post();
$this->db->update( 'school_register', $update, "id = " . $this->input->post('id'));
redirect('super-admin-school/school/viewRegisterSchool');
}else{
$data['school'] = $this->model_school->showAllSchoolDetails($id);
$this->load->view('edit_register_school', $data);
}
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Common extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
$this->load->model('model_common');
}
public function isDeleted() {
$id = $this->uri->segment(3);
$table = $this->uri->segment(4);
$controller = $this->uri->segment(5);
$function = $this->uri->segment(6);
$modules = $this->uri->segment(7);
$update = array(
'is_deleted' => 1
);
$this->db->update($table, $update, "id = " . $id);
redirect($modules . "/" . $controller . "/" . $function);
}
public function ajaxChangeStatus() {
$id = $this->input->post('id');
$table = $this->input->post('table');
$details = $this->model_common->viewTableStatus($id, $table);
if($details->status == 1){
$update_status = 0;
}else{
$update_status = 1;
}
$update = array(
'status' => $update_status
);
$this->db->update($table, $update, "id = " . $id);
if($update_status == 0){
echo '<img src="'.base_url() . 'assets/img/inactive.png" alt="Inactive" >';
}else{
echo '<img src="'.base_url() . 'assets/img/active.gif" alt="Active" >';
}
}
}
<file_sep><?php
Class Model_login extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function login($data) {
$query = $this->db->get_where('super_admin', array('email' => $data['user_name'], 'password' => $data['<PASSWORD>'], 'status' => 1, 'is_deleted' => 0 ));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
function checkOldPassword($data, $id) {
$query = $this->db->get_where('super_admin', array( 'password' => $data, 'id' => $id ));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
function checkOldPasswordMaster($data, $id) {
$query = $this->db->get_where('master_password', array( 'password' => $data, 'id' => $id ));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
function fetchMasterPassword($id) {
$query = $this->db->get_where('master_password', array( 'id' => $id ));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result->password;
}
}<file_sep><?php
Class Model_school_attendance extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function showAllStudentAttendance($data) {
$this->db->select(' student_register.student_name, student_register.student_id, student_attendance.*');
$this->db->join('student_attendance', 'student_attendance.student_id = student_register.id', 'left');
$query = $this->db->get_where('student_register', array('student_register.status' => 1, 'student_register.is_deleted' => 0, 'student_register.school_id' => $data['school_id'], 'student_attendance.month' => $data['recent_month'] ));
$result = ($query->num_rows() > 0) ? $query->result(): '';
return $result;
}
function showStudentAttendance( $id, $month ) {
$query = $this->db->get_where('student_attendance', array( 'student_id' => $id, 'month' => $month ));
$result = ($query->num_rows() > 0) ? $query->first_row(): '';
return $result;
}
}<file_sep><?= heading('Welcome Dashboard!', 1); ?>
<?= br(1); ?>
<?= heading($student_name, 1); ?>
<?= br(1); ?>
<?= anchor('student-logout/logout', 'Logout', array('title' => 'Logout')); ?>
<?= br(1); ?>
<?= anchor('student-attendance/student_attendance/showAttendance', 'Student Attendance', array('title' => 'Student Attendance')); ?><file_sep><?php
Class Model_student_register extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function showAllStudent($id) {
$query = $this->db->get_where('student_register', array('school_id' => $id, 'status' => 1, 'is_deleted' => 0));
$result = ($query->num_rows() > 0) ? $query->result(): '';
return $result;
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Settings extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
$this->load->model('super-admin-login/model_login');
if (!$this->session->userdata('super_admin')) {
redirect('super-admin-login/login');
}
}
public function superAdminPasswordChange()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
if ($this->input->post()) {
$old_password = md5($this->input->post('old_password'));
$result = $this->model_login->checkOldPassword($old_password, $data['logged_id']);
if($result){
$this->db->update( 'super_admin', array( 'password' => md5($this->input->post('new_password'))), "id = " . $data['logged_id']);
redirect('super-admin-settings/settings/superAdminPasswordChange');
}else{
$data['error'] = "Old password not matched";
$this->load->view('super_admin_password_change', $data);
}
}else{
$this->load->view('super_admin_password_change', $data);
}
}
public function masterPasswordChange()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
if ($this->input->post()) {
$old_password = md5($this->input->post('old_password'));
$result = $this->model_login->checkOldPasswordMaster($old_password, 1);
if($result){
$this->db->update( 'master_password', array( 'password' => md5($this->input->post('new_password'))), "id = " . $data['logged_id']);
redirect('super-admin-settings/settings/masterPasswordChange');
}else{
$data['error'] = "Old password not matched";
$this->load->view('master_password_change', $data);
}
}else{
$this->load->view('master_password_change', $data);
}
}
}
<file_sep>
<?= form_open_multipart(); ?>
<?= form_label('Name', 'student_name'); ?>
<?php
$attributes = array(
'name' => 'student_name',
);
echo form_input($attributes);
?>
<?= br(1); ?>
<?= form_label('Father name', 'father_name'); ?>
<?php
$attributes = array(
'name' => 'father_name',
);
echo form_input($attributes);
?>
<?= br(1); ?>
<?= form_label('Class', 'classes'); ?>
<?php
$attributes = array(
'name' => 'classes',
);
echo form_input($attributes);
?>
<?= br(1); ?>
<?= form_label('Section', 'sec'); ?>
<?php
$attributes = array(
'name' => 'sec',
);
echo form_input($attributes);
?>
<?= br(1); ?>
<?= form_label('Roll No', 'roll'); ?>
<?php
$attributes = array(
'name' => 'roll',
);
echo form_input($attributes);
?>
<?= br(1); ?>
<?= form_label('Mobile', 'mobile'); ?>
<?php
$attributes = array(
'name' => 'mobile',
);
echo form_input($attributes);
?>
<?= br(1); ?>
<?= form_submit('','Register'); ?>
<?= form_close(); ?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Exam_type extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
$this->load->library('form_validation');
$this->load->model('model_exam_type');
if (!$this->session->userdata('super_admin')) {
redirect('admin-login/login');
}
}
public function index()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
if ($this->input->post()) {
$this->form_validation->set_rules('exam_type', 'Exam Type', 'trim|required|max_length[255]');
$this->form_validation->set_message('required', '%s can\'t be blank');
$this->form_validation->set_message('max_length', 'Max 255 character only allowed');
if( $this->form_validation->run() === FALSE ){
$this->load->view('create_exam_type', $data);
}else{
$insert_data = $this->input->post();
$this->db->insert('exam_type', $insert_data);
redirect('super-admin-exam-type/exam_type');
}
}else{
$this->load->view('create_exam_type', $data);
}
}
public function viewExamTypes()
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
$data['types'] = $this->model_exam_type->showAllTypes();
$this->load->view('view_exam_type', $data);
}
public function editExamType($id)
{
$session_details = $this->session->userdata('super_admin');
$data['users_type'] = $session_details->users_type;
$data['users_nikname'] = $session_details->users_nikname;
$data['logged_id'] = $session_details->logged_id;
if ($this->input->post()) {
$this->form_validation->set_rules('exam_type', 'Exam Type', 'trim|required|max_length[255]');
$this->form_validation->set_message('required', '%s can\'t be blank');
$this->form_validation->set_message('max_length', 'Max 255 character only allowed');
if( $this->form_validation->run() === FALSE ){
$this->load->view('edit_exam_type', $data);
}else{
$this->db->update( 'exam_type', $this->input->post(), "id = " . $this->input->post('id'));
redirect('super-admin-exam-type/exam_type/viewExamTypes');
}
}else{
$data['type'] = $this->model_exam_type->showExamTypeDetails($id);
$this->load->view('edit_exam_type', $data);
}
}
}
<file_sep>
<?= form_open(); ?>
<?php
$attributes = array(
'name' => 'school_admin_code',
'placeholder' => 'School Code',
);
echo form_input($attributes);
?>
<?php
$attributes = array(
'name' => 'school_admin_password',
'autocomplete' => 'off',
'placeholder' => '<PASSWORD>',
);
echo form_password($attributes);
?>
<?= form_submit('mysubmit', 'Login'); ?>
<?= form_close(); ?><file_sep><table border = 1>
<tr>
<th></th>
<?php
foreach( $present_month_date as $date_id => $date){
echo "<th>".$date."</th>";
}
?>
</tr>
<?php
echo form_open_multipart( '', array('class' => 'horizontal-form'), array('hid_month' => $present_month) );
foreach( $school_students as $student ){
if(!empty($attendance[$student->id])){
$already_attend = (array)json_decode($attendance[$student->id]->attendance);
}else{
$already_attend = array();
}
echo "<tr>";
echo "<td>".$student->student_name."</td>";
foreach( $present_month_date as $date_id => $date){
?>
<td><input type = "checkbox" name = 'attendance[<?= $student->id; ?>][<?= $date_id; ?>]' value = "1" <?php if(array_key_exists( $date_id, $already_attend )){ echo "checked"; } ?> ></td>
<?php
}
echo "</tr>";
}
echo form_submit('mysubmit', 'Update Attendance');
echo form_close();
?>
<br>
<?= anchor('school-admin-attendance/student_attendance/giveAttendance/'.$previous_month, 'Previous month', array('title' => 'Previous month')); ?>
<br>
<?= anchor('school-admin-attendance/student_attendance/giveAttendance/'.$next_month, 'Next month', array('title' => 'Next month')); ?>
</table><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Student_attendance extends CI_Controller {
/**
* Login form of super admin.
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->helper('html');
$this->load->library('session');
$this->load->model('school-admin-student/model_student_register');
$this->load->model('model_school_attendance');
if (!$this->session->userdata('school_admin')) {
redirect('school-admin-login/login');
}
}
public function giveAttendance( $attendance_month = NULL )
{
$session_details = $this->session->userdata('school_admin');
$data['logged_id'] = $session_details->logged_id;
$data['school'] = $session_details->school;
if ($this->input->post()) {
foreach( $this->input->post('attendance') as $student_id => $attendance ){
$checkMonthAttendance = $this->model_school_attendance->showStudentAttendance( $student_id, $this->input->post('hid_month') );
$insert_data = array(
'school_id' => $data['logged_id'],
'student_id' => $student_id,
'month' => $this->input->post('hid_month'),
'attendance' => json_encode($attendance)
);
if(empty($checkMonthAttendance)){
$this->db->insert('student_attendance', $insert_data);
}else{
$this->db->update( 'student_attendance', $insert_data, "id = " . $checkMonthAttendance->id);
}
}
redirect('school-admin-attendance/student_attendance/giveAttendance/'.$attendance_month);
}else{
if( $attendance_month != NULL ){
$present_date_array = explode("-",$attendance_month);
$next_date = $present_date_array[0]."-".$present_date_array[1]."-01";
$data['present_month'] = $attendance_month;
}else{
$present_date = date('Y-m-d', time());
$present_date_array = explode("-",$present_date);
$next_date = $present_date_array[0]."-".$present_date_array[1]."-01";
$data['present_month'] = date('Y-m', strtotime($next_date));
}
$present_month_date[$next_date] = $next_date."<br>".date('D', strtotime($next_date));
$previous_month_date = date('Y-m-d', strtotime($next_date .' -1 day'));
$data['previous_month'] = date('Y-m', strtotime($previous_month_date));
$date_variable = 1;
$data['school_students'] = $this->model_student_register->showAllStudent($data['logged_id']);
if(!empty($data['school_students'])){
foreach( $data['school_students'] as $student ){
$attendance[$student->id] = $this->model_school_attendance->showStudentAttendance( $student->id, $data['present_month'] );
}
}
while($date_variable == 1) {
$current_date_array = explode("-",$next_date);
$next_date = date('Y-m-d', strtotime($next_date .' +1 day'));
$next_ber = date('D', strtotime($next_date));
$present_date_array = explode("-",$next_date);
if( ($present_date_array[2] - $current_date_array[2]) != 1 ){
$date_variable = 2;
$first_date_next_month = $next_date;
break;
}else{
$present_month_date[$next_date] = $next_date."<br>".$next_ber;
$date_variable = 1;
}
}
$data['attendance'] = $attendance;
$data['present_month_date'] = $present_month_date;
$data['next_month'] = date('Y-m', strtotime($first_date_next_month));
$this->load->view('student_attendance_entry', $data);
}
}
}
<file_sep><?php
Class Model_student_attendance extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function showAllStudentAttendance($data) {
$query = $this->db->get_where('super_admin', array('email' => $data['user_name'], 'password' => $data['<PASSWORD>']));
$result = ($query->num_rows() > 0) ? $query->first_row() : '';
return $result;
}
} | 21ada7aafd27984ff66562dd41802d711e5507fa | [
"JavaScript",
"SQL",
"PHP"
] | 30 | SQL | suman-cn/school | 62b462a17c18db6248cb87d54947bd9ad16f8edc | 408d8ea648415ade9650236440805f5bcef336f0 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Methods_HW
{
class Program
{
static void Main(string[] args)
{
#region question 1
//function is a block of commands with a number of code lines that do some sort of specified work.
#endregion
#region question 2
/*the benefit of functions is, you can add code to the function and use it
instead of having to type the same repeating code lines.*/
#endregion
#region question 3
/*to build a function you need: 1.accessibility level for example: public/private.
2.returned value, if expecting to get an answer else void.
3.name of the function usually each word with an UpperCaseLetter
4.parameters, what type of variable the function is expecting to get
5.block of commands, open { and close }
*/
#endregion
#region question 4
//it is possible to create a function that returns a value without a parameter
#endregion
#region question 5
//a function can only return one value.
#endregion
#region question 6
//each function is meant to be written in a class, for example: class Program.
#endregion
#region question 7
/*in a function that has to return a value, whenever return is that's where the function ends
in a function that doesn't have to return a value, void ends at the end of the command block*/
#endregion
#region question 8
//Console.WriteLine("enter a number 1-10");
//int enterNum = int.Parse(Console.ReadLine());
//PrintNumName(enterNum);
//if(enterNum < 1 || enterNum > 10)
//{
// Console.WriteLine("number is out of range");
//}
#endregion
#region question 9
//Console.WriteLine("how many times do you want the loop to run?");
//int loopRepetitions = int.Parse(Console.ReadLine());
//PrintNumbers(loopRepetitions);
#endregion
#region question 11
//Console.WriteLine("Enter a number to check if it's prime or not");
//int numberEntered = int.Parse(Console.ReadLine());
//int result = IsPrime(numberEntered);
//Console.WriteLine(result);
#endregion
#region question 12
//int[] myArr = { 2, 4, 9, 13, 17 };
//CheckArrayForPrimeNumbers(myArr);
#endregion
#region question 13
int[] arr1st = { 3, 8, 25, 4, 7 };
int[] arr2nd = { 6, 9, 23, 8, 1 };
WhichArrayIsBigger(arr1st, arr2nd);
int Answer = WhichArrayIsBigger(arr1st, arr2nd);
Console.WriteLine(Answer);
#endregion
}
public static void PrintNumName(int num)
{
switch (num)
{
case 1:
Console.WriteLine("one");
break;
case 2:
Console.WriteLine("two");
break;
case 3:
Console.WriteLine("three");
break;
case 4:
Console.WriteLine("four");
break;
case 5:
Console.WriteLine("five");
break;
case 6:
Console.WriteLine("six");
break;
case 7:
Console.WriteLine("seven");
break;
case 8:
Console.WriteLine("eight");
break;
case 9:
Console.WriteLine("nine");
break;
case 10:
Console.WriteLine("ten");
break;
}
}
private static bool PrintNumbers(int number)
{
if (number < 10 && number > 1)
{
return true;
}
else
return false;
for (int i = 0; i < number; i++)
{
Console.WriteLine(i);
}
}
private static int IsPrime(int numberByUser)
{
int checkIfPrime = 2;
while (numberByUser % checkIfPrime != 0)
{
checkIfPrime++;
}
if (numberByUser == checkIfPrime)
{
return 1;
}
else
{
return 0;
}
}
private static void CheckArrayForPrimeNumbers(int[] arr)
{
int divByNum = 2;
for (int i = 0; i < arr.Length; i++)
{
while (arr[i] % divByNum != 0)
{
divByNum++;
}
if (arr[i] == divByNum)
{
Console.WriteLine("Prime number");
}
else
{
Console.WriteLine("Not prime number");
}
}
}
private static int WhichArrayIsBigger(int[] arr1, int[] arr2)
{
int sum1 = 0;
int sum2 = 0;
for (int i = 0; i < arr1.Length; i++)
{
sum1 += arr1[i];
}
for (int j = 0; j < arr2.Length; j++)
{
sum2 += arr2[j];
}
if (sum1 > sum2)
return 1;
else if (sum1 == sum2)
return 0;
else
return -1;
}
}
}
| 50b7f3aebeea868c3e3af4f47800c42b582802f7 | [
"C#"
] | 1 | C# | orianM/Methods-basic-HW | a94679eae231b424cb87362240002b4d5ecc3af1 | bdad256a76150bee45a19d33ef22378a1954453d |
refs/heads/master | <repo_name>iperevozchikov/socket-tunnel<file_sep>/server.js
module.exports = function(options) {
// libs
var http = require('http');
var tldjs = require('tldjs');
var ss = require('socket.io-stream');
var uuid = require('uuid/v4');
// association between subdomains and socket.io sockets
var socketsByName = {};
// bounce incoming http requests to socket.io
var server = http.createServer(function (req, res) {
// without a hostname, we won't know who the request is for
var hostname = req.headers.host;
if (!hostname) {
res.statusCode = 502;
return res.end('Invalid hostname');
}
// make sure we received a subdomain
var subdomain = tldjs.getSubdomain(hostname);
if (!subdomain) {
res.statusCode = 502;
return res.end('Invalid subdomain');
}
// tldjs library return subdomain as all subdomain path from the main domain.
// Example:
// 1. super.example.com = super
// 2. my.super.example.com = my.super
// If want to run tunnel server on subdomain, then must use option serverSubdomainHost
// and correctly trim returned subdomain by tldjs
if (options['subdomain']) {
subdomain = subdomain.replace('.' + options['subdomain'], '');
}
var clientId = subdomain.toLowerCase();
var client = socketsByName[clientId];
// no such subdomain
// we use a 502 error to the client to signify we can't service the request
if (!client) {
res.statusCode = 502;
res.end(clientId + ' is currently unregistered or offline.');
} else {
var requestGUID = uuid();
client.emit('incomingClient', requestGUID);
ss(client).once(requestGUID, function (stream) {
stream.on('error', function () {
req.destroy();
stream.destroy();
});
// Pipe all data from tunnel stream to requesting connection
stream.pipe(req.connection);
var postData = [];
// Collect data of POST/PUT request to array buffer
req.on('data', function(data) {
postData.push(data);
});
// Proxy ended GET/POST/PUT/DELETE request to tunnel stream
req.on('end', function() {
var messageParts = [];
// Push request data
messageParts.push([req.method + ' ' + req.url + ' HTTP/' + req.httpVersion]);
// Push headers data
for (var i = 0; i < (req.rawHeaders.length-1); i += 2) {
messageParts.push(req.rawHeaders[i] + ': ' + req.rawHeaders[i+1]);
}
// Push delimiter
messageParts.push('');
// Push request body data
messageParts.push(Buffer.concat(postData).toString());
// Push delimiter
messageParts.push('');
var message = messageParts.join('\r\n');
stream.write(message);
});
});
}
});
// socket.io instance
var io = require('socket.io')(server);
io.on('connection', function (socket) {
socket.on('createTunnel', function (requestedName) {
if (socket.requestedName) {
// tunnel has already been created
return;
}
// domains are case insensitive
var reqNameNormalized = requestedName.toLowerCase();
// make sure the client is requesting an alphanumeric of reasonable length
if (/[^a-zA-Z0-9]/.test(reqNameNormalized) || reqNameNormalized.length === 0 || reqNameNormalized.length > 63) {
console.log(new Date() + ': ' + reqNameNormalized + ' -- bad subdomain. disconnecting client.');
return socket.disconnect();
}
// make sure someone else hasn't claimed this subdomain
if (socketsByName[reqNameNormalized]) {
console.log(new Date() + ': ' + reqNameNormalized + ' requested but already claimed. disconnecting client.');
return socket.disconnect();
}
// store a reference to this socket by the subdomain claimed
socketsByName[reqNameNormalized] = socket;
socket.requestedName = reqNameNormalized;
console.log(new Date() + ': ' + reqNameNormalized + ' registered successfully');
});
// when a client disconnects, we need to remove their association
socket.on('disconnect', function () {
if (socket.requestedName) {
delete socketsByName[socket.requestedName];
console.log(new Date() + ': ' + socket.requestedName + ' unregistered');
}
});
});
// http server
server.listen(options['port'], options['host']);
console.log(new Date() + ': socket-tunnel server started on port ' + options['port']);
};<file_sep>/README.md
# socket-tunnel
Tunnel HTTP Connections via socket.io streams. Inspired by [localtunnel](https://github.com/localtunnel/localtunnel).
## Blog Post
http://ericbarch.com/post/143994549052/tunneling-http-connections-via-socketio-streams
## Server Usage
1. Clone this repo and cd into it
2. docker build -t socket-tunnel .
3. docker run -d -p 80:3000 --restart=always --name st-server socket-tunnel
4. Get a domain name
5. Point your domain name's root A record at your server's IP
6. Point a wildcard (*) A record at your server's IP
## Client Usage
1. Clone this repo and cd into it
2. Configure REQUESTED\_SUBDOMAIN and LOCAL\_PORT in client.js
3. Set TUNNEL\_SERVER in client.js to point to your server's domain name
4. node client.js
5. Browse to http://REQUESTED\_SUBDOMAIN.YOURDOMAIN.com
6. See your service running on http://127.0.0.1:LOCAL_PORT available on the public internet
## TODO
Package this nicely and make it easy to use. Sorry, this was a quick reference implementation!
## Credits
Created by <NAME>.
## License
This project is licensed under the MIT License - see the LICENSE file for details<file_sep>/bin/server
#!/usr/bin/env node
var optimist = require('optimist');
var argv = optimist
.usage('Usage: $0 --hostname [string] --port [number] --subdomain [string]')
.options('h', {
alias: 'hostname',
default: '127.0.0.1',
describe: 'Accepts connections on the hostname'
})
.options('p', {
alias: 'port',
default: 3000,
describe: 'Listens port in OS'
})
.options('s', {
alias: 'subdomain',
default: '',
describe: "Name of subdomain uses. It's required when server listens on a subdomain."
})
.argv;
if (argv.help) {
optimist.showHelp();
process.exit();
}
require('../server.js')(argv); | 10d8342b284b5c0f2ea048652c791b6234dae2a2 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | iperevozchikov/socket-tunnel | 4e10c3b47d633b73c8b073b243dcb54193f0ae3c | 0054b055b4b6596f4a274a0cebf7408ffc732783 |
refs/heads/master | <repo_name>psoberanis/PracticalMachineLearning<file_sep>/testing_script.R
setwd("/Users/psoberanis/PracticalMachineLearning/")
pml.train <- read.csv("pml-training.csv")
pml.test <- read.csv("pml-testing.csv")
set.seed(137)
#partition data
inTrain<- createDataPartition(y=pml.train$classe,p=0.6,list=FALSE)
locTrain<-pml.train[inTrain,]
locTest<-pml.train[-inTrain,]
#Near zero values removed
locTrainNZV <- nearZeroVar(locTrain, saveMetrics=TRUE)
locNZVvar<-!locTrainNZV$nzv
locTrain<-locTrain[locNZVvar]
#Remove large number of NA's
locTrain<-locTrain[c(-1)]
myTrain <- locTrain #creating another subset to iterate in loop
for(i in 1:length(locTrain)) { #for every column in the training dataset
if( sum( is.na( locTrain[, i] ) ) /nrow(locTrain) >= .7 ) { #if n?? NAs > 70% of total observations
for(j in 1:length(myTrain)) {
if( length( grep(names(locTrain[i]), names(myTrain)[j]) ) ==1) { #if the columns are the same:
myTrain <- myTrain[ , -j] #Remove that column
}
}
}
}
cleanDataNames1<-colnames(myTrain)
cleanDataNames2<-colnames(myTrain[,-58])
myTest<-locTest[cleanDataNames1]
pml.test<-pml.test[cleanDataNames2]
###Coerce data
for (i in 1:length(pml.test) ) {
for(j in 1:length(myTrain)) {
if( length( grep(names(myTrain[i]), names(pml.test)[j]) ) ==1) {
class(pml.test[j]) <- class(myTrain[i])
}
}
}
pml.test <- rbind(myTrain[2, -58] , pml.test)
pml.test <- pml.test[-1,]
pml_rf<-train(classe~., data = myTrain, method='rf')
test1<-predict(pml_rf,myTest)
###
confusionMatrix(test1,myTest$classe)
pml_pred<-predict(pml_rf,pml.test)
<file_sep>/PML_Final_Project.Rmd
---
title: "PML Final Project"
author: "<NAME>"
date: "March 26, 2016"
output: html_document
---
```{r package_options, include = FALSE}
knitr::opts_knit$set(progress = TRUE, verbose = TRUE)
```
```{r, results = "hide", message = FALSE}
library(ElemStatLearn)
library(caret)
```
###Synopsis:
Using devices such as Jawbone Up, Nike FuelBand, and Fitbit it is now possible to collect a large amount of data about personal activity relatively inexpensively. These type of devices are part of the quantified self movement – a group of enthusiasts who take measurements about themselves regularly to improve their health, to find patterns in their behavior, or because they are tech geeks. One thing that people regularly do is quantify how much of a particular activity they do, but they rarely quantify how well they do it. In this project, your goal will be to use data from accelerometers on the belt, forearm, arm, and dumbell of 6 participants. They were asked to perform barbell lifts correctly and incorrectly in 5 different ways. More information is available from the website here: http://groupware.les.inf.puc-rio.br/har (see the section on the Weight Lifting Exercise Dataset).
####Data
The training data for this project are available here:
https://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv
The test data are available here:
https://d396qusza40orc.cloudfront.net/predmachlearn/pml-testing.csv
###Data Processing:
```{r}
pml.train <- read.csv("pml-training.csv")
pml.test <- read.csv("pml-testing.csv")
set.seed(137)
dim(pml.train)
dim(pml.test)
```
The first thing we do is to partition the training data set so that we can have some testing data to help validate our model before we try it on the test data provided for the project. This will allow us to do an out-of-sample testing before we apply the model to the provided test data. We use the convention of a 60-40 split with 60% of the data being used as the training data and the other 40% of the data being used to test the data.
```{r}
inTrain<- createDataPartition(y=pml.train$classe,p=0.6,list=FALSE) #partition the data
locTrain<-pml.train[inTrain,] #training data
locTest<-pml.train[-inTrain,] #cross validation testing data
dim(locTrain)
dim(locTest)
```
Next we do some data cleaning and transformation. We remove the variables that have variance close to zero and we remove the variables that have more than 70% of the data being NA's. This will allow us to have a fairly clean data set that we can then use to train our model.
```{r}
#Near zero values removed
locTrainNZV <- nearZeroVar(locTrain, saveMetrics=TRUE)
locNZVvar<-!locTrainNZV$nzv
locTrain<-locTrain[locNZVvar]
#Remove large number of NA's
locTrain<-locTrain[c(-1)]
myTrain <- locTrain
for(i in 1:length(locTrain)) { #for every column in the training dataset
if( sum( is.na( locTrain[, i] ) ) /nrow(locTrain) >= .7 ) { #if the number of NAs > 70% of total observations
for(j in 1:length(myTrain)) {
if( length( grep(names(locTrain[i]), names(myTrain)[j]) ) ==1) { #if the columns are the same:
myTrain <- myTrain[ , -j] #Remove that column
}
}
}
}
```
We now do the same data transformations to the two testing sets to ensure that we can use the data with the predict function and get reasonable results.
```{r}
cleanDataNames1<-colnames(myTrain)
cleanDataNames2<-colnames(myTrain[,-58])
myTest<-locTest[cleanDataNames1]
pml.test<-pml.test[cleanDataNames2]
dim(myTrain); dim(myTest)
```
In order for the training data supplied to work we need to make some minor modifications to ensure that it meets the
requirements
```{r}
for (i in 1:length(pml.test) ) {
for(j in 1:length(myTrain)) {
if( length( grep(names(myTrain[i]), names(pml.test)[j]) ) ==1) {
class(pml.test[j]) <- class(myTrain[i])
}
}
}
pml.test <- rbind(myTrain[2, -58] , pml.test)
pml.test <- pml.test[-1,]
dim(pml.test)
```
Now when we examine the data we see that it meets the criteria for us to test our model once we create it.
###Model Fitting
Given that we are looking to classify the data into multiple classes we first try a random forest to see how well this model will fit the data.
```{r}
pml_rf<-train(classe~., data = myTrain, method='rf')
plot(pml_rf)
```
From the plot of the model we see that around 40 randomly selected predictors we were able to achieve the best accurracy. We use the model to predict what our test data results will be and then we look at the accuracy of the prediction.
```{r}
test1<-predict(pml_rf,myTest)
confusionMatrix(test1,myTest$classe)$overall
```
From the confusion matrix we see that our model has an accuracy of 99.9% with a 95% confidence interval. Given that level of accuracy I chose not to puruse another model. With such a high level of cross validation accuracy and taking into account the time it takes the ElemStatLearn package to churn through the learning process and produce the model, I figured it was best to try this one before pursuing alternatives.
Finally, we use the model to predict the classes for the test data that will be submitted for the project quiz.
```{r}
pml_pred<-predict(pml_rf,pml.test)
pml_pred
```
###Conclusion
The Random Forest method that was used allowed for a model that was 99.9% accurate based on out-of-sample testing. Using this model we were able to predict the classes for the quiz with 100% accurracy.
| 25b068ec38d2802ba633020451d31a15f94197dd | [
"R",
"RMarkdown"
] | 2 | R | psoberanis/PracticalMachineLearning | 1f692c56c928d2d2ae36cd94a9d2caf1f9cbe2dc | e4aa4e4aad3e16189cddae32ad9ed351cc348a74 |
refs/heads/master | <repo_name>Mishra121/PollyWin<file_sep>/routes/api/votes.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
// Load User Model
const User = require('../../models/User');
// @route GET api/votes/rankings
// @desc Geting all user rankings based on like and dislike
// | like +5 points dislike -5 points |
// @access Private
router.get('/rankings', (req, res) => {
User.find()
.then(users => {
users.sort((a, b) => {
return ((b.likes.length * 5) - (b.dislikes.length * 3))
- ((a.likes.length * 5) - (a.dislikes.length * 3));
})
if(users.length > 10){
users = users.slice(0,10);
res.json(users);
}else{
res.json(users);
}
})
.catch((err) => console.log(err));
});
// @route GET api/votes/randUser
// @desc Geting random user card
// Do not show already liked or disliked user
// @access Private
router.get('/randUser', passport.authenticate('jwt', {session: false}), (req, res) => {
const user_id = req.user.id;
User.find()
.then((users) => {
// Filtering on the basis of likes and dislikes
var randUserArray = users.filter((user) => {
if(user.likes.includes(user_id) || user.dislikes.includes(user_id)) {
return false;
}else{
return true;
}
})
// Finding a random user
const randUserDetails = randUserArray[Math.floor(Math.random() * randUserArray.length)];
const randUser = {
id: randUserDetails._id,
name: randUserDetails.name,
info: randUserDetails.info,
imageURL: randUserDetails.imageURL
}
res.json({randUser});
})
.catch((err) => console.log(err));
});
// @route POST api/votes/like
// @desc For liking the User Given
// @access Private
router.post('/like', passport.authenticate('jwt', {session: false}), (req, res) => {
const like_id = req.body.id;
const user_id = req.user.id;
User.findById({_id :like_id})
.then( user => {
// Add user id to likes array
user.likes.push(user_id);
user.save().then(() => res.json({success: true}));
})
.catch(err => console.log(err));
});
// @route POST api/votes/dislike
// @desc For disliking the User Given
// @access Private
router.post('/dislike', passport.authenticate('jwt', {session: false}), (req, res) => {
const dislike_id = req.body.id;
const user_id = req.user.id;
User.findById({_id : dislike_id})
.then( user => {
// Add user id to dislikes array
user.dislikes.push(user_id)
user.save().then(() => res.json({success: true}));
})
.catch(err => console.log(err));
});
module.exports = router;<file_sep>/client/src/components/layout/Navbar.js
import React, { Component } from 'react'
import imageBrand from '../../img/favicon-32x32.png';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { logoutUser } from '../../actions/authActions';
class Navbar extends Component {
onLogoutClick(e) {
e.preventDefault();
this.props.logoutUser();
}
render() {
const { isAuthenticated, user } = this.props.auth;
const imageForProfile = (
<img className="rounded-circle"
src={user.imageURL}
alt={user.name}
style={{width: '25px', marginRight: '5px'}}
/>
)
const authLinks = (
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<Link className="nav-link" to='/leaderboard'>Leaderboard</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/vote">Vote Now</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/profile">
{user.imageURL ? imageForProfile : ''}
{user.name}
</Link>
</li>
<li className="nav-item">
<a
onClick={this.onLogoutClick.bind(this)}
className="nav-link" href="">
Logout
</a>
</li>
</ul>
);
return (
<nav className="navbar sticky-top navbar-expand-lg navbar-dark bg-dark">
<Link className="navbar-brand" to="/"><img src={imageBrand} alt=""/> PollyWin</Link>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
{isAuthenticated ?
authLinks :
(
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<Link className="nav-link" to='/leaderboard'>Leaderboard</Link>
</li>
</ul>
)
}
</div>
</nav>
)
}
}
const mapStateToProps = (state) => ({
auth: state.auth
});
export default connect(mapStateToProps, { logoutUser })(Navbar);<file_sep>/client/src/actions/rankAction.js
import axios from 'axios';
import { GET_RANKS, RANKS_LOADING, RAND_USER } from './types';
// Random User Generator for making a like dislike move
export const randUser = () => dispatch => {
axios.
get('api/votes/randUser')
.then(
res => {
dispatch({
type: RAND_USER,
payload: res.data
})
}
)
.catch(err =>
dispatch({
type: GET_RANKS,
payload: null
})
);
}
// Like the random User generated and then give a new random user
export const likeUser = (id) => dispatch => {
axios.
post('api/votes/like', {id})
.then(
res => {
if(res.data.success)
{
dispatch(randUser());
}
}
).catch(err =>
{console.log(err);}
);
}
// Dislike the random User generated and then give a new random user
export const dislikeUser = (id) => dispatch => {
axios.
post('api/votes/dislike', {id})
.then(
res => {
if(res.data.success)
{
dispatch(randUser());
}
}
).catch(err =>
{console.log(err);}
);
}
// Get Ranks for leaderboard component
export const getRanks = () => dispatch => {
dispatch(setRanksLoading());
axios
.get('/api/votes/rankings')
.then(res => {
dispatch({
type: GET_RANKS,
payload: res.data
})
}
)
.catch(err =>
dispatch({
type: GET_RANKS,
payload: null
})
);
};
// Ranks Loading
export const setRanksLoading = () => {
return{
type: RANKS_LOADING
}
}<file_sep>/config/token.js
// FILE NOT USED JUST TO REMEMBER JWT LOGIC
const jwt = require('jsonwebtoken');
const key = require('./key');
// Load User Model
const User = require('../models/User');
// Generate an Access Token for the given User ID
function generateAccessToken(id) {
userId = id;
console.log(userId);
User.findById(userId)
.then(user => {
const payload = {
id: user.id,
name: user.name,
info: user.info,
imageURL: user.imageURL,
imageID: user.imageID
}
// Sign JWT Token
jwt.sign(payload, key.secretOrKey, {expiresIn: 5400}, (err, token) => {
return res.json({
success: true,
token: 'Bearer ' + token
})
})
}
)
}
module.exports = {
generateAccessToken: generateAccessToken
}<file_sep>/client/src/components/Random/Random.js
import React, { Component } from 'react'
import { connect } from 'react-redux';
import { randUser, likeUser, dislikeUser } from '../../actions/rankAction';
class Random extends Component {
constructor(props) {
super(props);
this.handleDislike = this.handleDislike.bind(this);
this.handleLike = this.handleLike.bind(this);
}
componentDidMount() {
this.props.randUser();
}
handleLike() {
const { random } = this.props.ranks;
var id = random.randUser.id;
this.props.likeUser(id);
}
handleDislike() {
const { random } = this.props.ranks;
var id = random.randUser.id;
this.props.dislikeUser(id);
}
render() {
var contentName = <h1 className="display-5 text-center"></h1>
var contentInfo = <p className="lead"></p>
var contentImage = <img className="img-thumbnail rounded" src="http://www.free-icons-download.net/images/commercial-male-user-icon-32765.png"/>;
const { random } = this.props.ranks;
//id name info imageURL
if(random){
if(random.randUser.info){
var contentInfo = <p className="lead"> {random.randUser.info} </p>
}
if(random.randUser.imageURL) {
var contentImage = <img className="img-thumbnail rounded" src={random.randUser.imageURL}/>
}
if(random.randUser.name) {
var contentName = <h1 className="display-5 text-center">{random.randUser.name}</h1>
}
}
return (
<div className="container">
<div className="row">
<div className="col-md-4 m-auto">
<div className="card card-body bg-primary mt-3 m-auto">
{contentImage}
<div className="text-center text-white">
<br/>
{contentName}
</div>
<div className="buttonslikedislike m-auto">
<button onClick={this.handleLike} className="btn btn-lg btn-success mr-3">
<a><i className="fas fa-heart"></i></a>
</button>
<button onClick={this.handleDislike} className="btn btn-lg btn-danger">
<a><i className="fas fa-thumbs-down"></i></a>
</button>
</div>
</div>
<div className="card card-body m-auto">
{contentInfo}
</div>
</div>
</div>
</div>
)
}
}
const mapStateToProps = state => ({
ranks: state.ranks
});
export default connect(mapStateToProps, { randUser, likeUser, dislikeUser } )(Random);<file_sep>/routes/api/authRoutes.js
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const key = require('../../config/key');
// @route POST /auth/token-fb
// @desc For creating JWT for client side using fb details from fb callback.
router.post('/token-fb', (req, res) => {
const profile_id = req.body.id;
const profile_name = req.body.name;
const profile_email = req.body.email;
if(!profile_id) {
return res.json('No Profile Id obtained.');
}
User.findOne({ fbId: profile_id })
.then(user => {
if(user) {
const payload = {
id: user.id,
name: user.name,
info: user.info,
imageURL: user.imageURL,
imageID: user.imageID
}
// Sign JWT Token
jwt.sign(payload, key.secretOrKey, {expiresIn: 5400}, (err, token) => {
return res.json({
success: true,
token: 'Bearer ' + token
})
})
}else {
const newUser = new User({
fbId: profile_id,
name: profile_name,
email: profile_email
})
newUser.save()
.then(user => {
const payload = {
id: user.id,
name: user.name,
info: user.info,
imageURL: user.imageURL,
imageID: user.imageID
}
// Sign JWT Token
jwt.sign(payload, key.secretOrKey, {expiresIn: 5400}, (err, token) => {
return res.json({
success: true,
token: 'Bearer ' + token
})
})
})
}
})
});
module.exports = router;<file_sep>/config/keys_prod.js
module.exports = {
mongoURI: process.env.MONGO_URI,
secretOrKey: process.env.SECRET_OR_KEY,
cloudKey: process.env.CLOUD_KEY,
cloudSecret: process.env.CLOUD_SECRET,
cloudName: process.env.CLOUD_NAME,
fbID: process.env.FB_ID,
fbSecret: process.env.FB_SECRET
};<file_sep>/client/src/actions/types.js
export const RAND_USER = 'RAND_USER';
export const SET_CURRENT_USER = 'SET_CURRENT_USER';
export const GET_ERRORS = 'GET_ERRORS';
export const GET_RANKS = 'GET_RANKS';
export const RANKS_LOADING = 'RANKS_LOADING';
export const EDIT_BIO = 'EDIT_BIO';
export const PROFILE_LOADING = 'PROFILE_LOADING';<file_sep>/client/src/components/layout/Landing.js
import React, { Component } from 'react'
import './Landing.css'
import { connect } from 'react-redux'
import { loginUser } from '../../actions/authActions';
import FacebookLogin from 'react-facebook-login';
class Landing extends Component {
constructor() {
super();
this.state = {
errors: {}
}
}
componentDidMount() {
if(this.props.auth.isAuthenticated) {
this.props.history.push('/leaderboard');
}
}
componentWillReceiveProps(nextProps) {
if(nextProps.auth.isAuthenticated) {
this.props.history.push('/leaderboard');
}
if(nextProps.errors) {
this.setState({errors: nextProps})
}
}
render() {
const { errors } = this.state;
const responseFacebook = (response) => {
var {name, id, email} = response;
this.props.loginUser({name, id, email});
}
return (
<header className="masthead img-fluid">
<div className="container h-100 ">
<div className="row h-100">
<div className="col-12 align-self-center">
<h1 className="font-weight-light">Vote To Win</h1>
<FacebookLogin
appId="552016471966082"
fields="name,email"
callback={responseFacebook}
disableMobileRedirect={true}
/>
</div>
</div>
</div>
</header>
)
}
}
const mapStateToProps = (state) => ({
auth: state.auth,
errors: state.errors
})
export default connect(mapStateToProps, {loginUser})(Landing);<file_sep>/client/src/components/LeaderBoard/RankElement.js
import React, { Component } from 'react'
import RankItem from './RankItem'
export default class RankElement extends Component {
render() {
const { ranks } = this.props;
return ranks.map(rank => <RankItem key={rank._id} rank={rank} />)
}
}
<file_sep>/client/src/components/LeaderBoard/LeaderBoard.js
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'
import Spinner from '../Spinner'
import RankElement from './RankElement';
import { getRanks } from '../../actions/rankAction'
class LeaderBoard extends Component {
componentDidMount() {
this.props.getRanks();
}
render() {
const { ranks, loading } = this.props.ranks;
let rankContent;
if(ranks === null || loading) {
rankContent = <Spinner/>
} else{
rankContent = <RankElement ranks={ranks} />
}
return (
<div className="container">
<div className="row">
<div className="col-md-6 m-auto">
<div className="card">
<div className="card-header text-center">
<h4>Current Top Profiles...</h4>
</div>
<br/>
<div className="gaadiex-list m-auto">
{rankContent}
<hr/>
<button className="btn btn-outline-dark" ><Link to="/vote">Poll Now <i className="fas fa-angle-double-right"></i></Link></button>
<hr/>
</div>
</div>
</div>
</div>
</div>
)
}
}
const mapStateToProps = state => ({
ranks: state.ranks
});
export default connect(mapStateToProps, { getRanks })(LeaderBoard); | 5992376e03f61f0f345766b24b7a328ac6369288 | [
"JavaScript"
] | 11 | JavaScript | Mishra121/PollyWin | 3f52aa433ed531410d0f10a9ac0970cb73d94374 | 152c2f85fc560ee8b9f920e730a06966f5080b10 |
refs/heads/master | <repo_name>nopphon3211/work_shop_two<file_sep>/src/component/HeroSection.js
import React, { Component } from 'react'
import '../App.css'
import { Button } from './Button'
import './HeroSection.css'
import vedio1 from '../Video/video-2.mp4'
export default class HeroSection extends Component {
render() {
return (
<>
<div className="hero-container">
<video src={vedio1} autoPlay loop muted />
<h1>ADVENTURE AWAITS</h1>
<p>What are you waithing for ?</p>
<div className="hero-btns">
<Button className="btns" buttonStyle='btn--outline' buttonSize='btn--large'>Get START
</Button>
<Button className="btns" buttonStyle='btn-primary' buttonSize='btn--large'>WATCH TRAILER <i className='far fa-play-circle' />
</Button>
</div>
</div>
</>
)
}
}
// import React from 'react'
// import '../App.css'
// import { Button } from './Button'
// import './HeroSection.css'
// function HeroSection() {
// return (
// <div className="hero-container">
// <video src="/video/video-1.mp4" autoPlay loop muted />
// <h1>ADVENTURE AWAITS</h1>
// <p>What are you waithing for ?</p>
// <div className="hero-btns">
// <Button className="btns" buttonStyle='btn--outline' buttonSize='btn--large'>Get START
// </Button>
// <Button className="btns" buttonStyle='btn-primary' buttonSize='btn--large'>WATCH TRAILER <i className='far fa-play-circle' />
// </Button>
// </div>
// </div>
// )
// }
// export default HeroSection
<file_sep>/src/img/Commitment.js
import React, { Component } from 'react'
export default class Commitment extends Component {
render() {
return (
<section className="content container">
<h3>OUR COMMITMENT</h3>
<p className="p2" />
<div className="content-grid">
<h2>THE HOME OF FRESHNESS</h2>
<div>
Two exquisite objection delighted deficient yet its contained. Cordial because are account evident its subject but eat. Can properly followed learning prepared you doubtful yet him. Over many our good lady feet ask that. Expenses own moderate day fat trifling stronger sir domestic feelings. <br /><br />Itself at be answer always exeter up do. Though or my plenty uneasy do. Friendship so considered remarkably be to sentiments. Offered mention greater fifteen one promise because nor. Why denoting speaking fat indulged saw dwelling raillery.
</div>
</div>
</section>
)
}
}
| c621b24a32045bfed565e36a9f6b7a5ff26927fb | [
"JavaScript"
] | 2 | JavaScript | nopphon3211/work_shop_two | 38a0945d7265f3ec861a46be5d963c1c760ffc29 | cc4620bea06ab829432830394a6f1de8a3ab2560 |
refs/heads/master | <repo_name>ShivamK-Cuelogic/NodeJsAssignment<file_sep>/server/server.js
var http = require("http");
var fs = require("fs");
var dotenv = require("dotenv").config();
var server = http.createServer(function(request,response) {
fs.readFile("./index.html" , function(err,content) {
if(err) {
console.log("Error==>",err);
} else {
response.writeHead(200,{ "Content-Type" : "text/html" });
response.write(content);
response.end();
}
})
})
console.log("Server is listening on port ",process.env.port);
var io = require("socket.io").listen(server);
io.sockets.on('connection' , function(socket) {
socket.emit('welcomeMessageFromServer',"Hi Client !! You are connected ");
socket.on('clients_name',function(name){
socket.name = name;
console.log( socket.name + " is connected..");
})
socket.on('messageFromClientToServer' , function(msg) {
console.log(socket.name + " is saying " + msg);
})
setTimeout(function() {
socket.emit('msgFromServerToClient' , "Hi client !!! How are you ??");
socket.broadcast.emit('msgToAllClients' ,'Hi clients.. all good ??');
},5000);
})
server.listen(process.env.port); | da78c71b5e54fb2d9184b2bdeadea897e54b13f7 | [
"JavaScript"
] | 1 | JavaScript | ShivamK-Cuelogic/NodeJsAssignment | a2985bff1ed4f2f2337c6c8a89a4a0a25a540a36 | a25f292859bcbfe2ca3f0618479a6862c57fa162 |
refs/heads/master | <file_sep>package com.mobile.azrinurvani.rxkotlinwithroomdb.entitiy.db
import androidx.room.*
import com.mobile.azrinurvani.rxkotlinwithroomdb.entitiy.PersonData
import io.reactivex.Completable
import io.reactivex.Single
@Dao
interface PersonalDataDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertPersonData(data: PersonData) : Completable
@Query("SELECT * FROM ${PersonData.TABLE_NAME}")
fun getAllRecords(): Single<List<PersonData>>
@Delete
fun detelePersonData(person: PersonData) : Completable
@Update
fun updatePersonData(person: PersonData)
}<file_sep>package com.mobile.azrinurvani.rxkotlinwithroomdb.entitiy.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.mobile.azrinurvani.rxkotlinwithroomdb.entitiy.PersonData
const val DB_VERSION = 1
const val DB_NAME = "PersonDataSample.db"
@Database(entities = [PersonData::class],version = DB_VERSION,exportSchema = false)
abstract class PersonalDetailsDataBase : RoomDatabase() {
abstract fun personDataDao() : PersonalDataDao
companion object{
@Volatile
private var databaseInstance : PersonalDetailsDataBase? = null
fun getDatabaseInstance(mContext : Context): PersonalDetailsDataBase =
databaseInstance ?: synchronized(this){
databaseInstance ?: buildDatabaseInstance(mContext).also{
databaseInstance = it
}
}
private fun buildDatabaseInstance(mContext: Context) =
Room.databaseBuilder(mContext,PersonalDetailsDataBase::class.java, DB_NAME)
.fallbackToDestructiveMigration()
.build()
}
}<file_sep>package com.mobile.azrinurvani.rxkotlinwithroomdb.entitiy
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName=PersonData.TABLE_NAME)
class PersonData (
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ID)
var userID:Int ?= null,
@ColumnInfo(name = NAME)
var nameFUll: String? = null,
@ColumnInfo(name = AGE)
var ageTotal: Int? = null
){
companion object{
const val TABLE_NAME="personal_details"
const val ID = "id"
const val NAME ="name"
const val AGE = "age"
}
}
<file_sep>package com.mobile.azrinurvani.rxkotlinwithroomdb.view_model
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.mobile.azrinurvani.rxkotlinwithroomdb.entitiy.PersonData
import com.mobile.azrinurvani.rxkotlinwithroomdb.entitiy.db.PersonalDetailsDataBase
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
class MainViewModel : ViewModel() {
protected val compositeDisposable = CompositeDisposable()
private var dataBaseInstance : PersonalDetailsDataBase? = null
val personList = MutableLiveData<List<PersonData>>()
fun setInstanceOfDb(dataBaseInstance : PersonalDetailsDataBase){
this.dataBaseInstance = dataBaseInstance
}
fun saveDataIntoDb(data: PersonData){
dataBaseInstance?.personDataDao()?.insertPersonData(data)
?.subscribeOn(Schedulers.io())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribe(
{
},{
}
)?.let {
compositeDisposable.add(it)
}
}
fun getPersonData(){
dataBaseInstance?.personDataDao()?.getAllRecords()
?.subscribeOn(Schedulers.io())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribe({
if(!it.isNullOrEmpty()){
personList.postValue(it)
}else{
personList.postValue(listOf())
}
it?.forEach{
Log.v("Person Name ",it.nameFUll)
}
},{
})?.let {
compositeDisposable.add(it)
}
}
override fun onCleared() {
compositeDisposable.dispose()
compositeDisposable.clear()
super.onCleared()
}
fun deletePerson(person: PersonData){
dataBaseInstance?.personDataDao()?.detelePersonData(person)
?.subscribeOn(Schedulers.io())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribe(
{
},{
}
)?.let {
compositeDisposable.add(it)
}
}
}<file_sep>package com.mobile.azrinurvani.rxkotlinwithroomdb.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.mobile.azrinurvani.rxkotlinwithroomdb.R
import com.mobile.azrinurvani.rxkotlinwithroomdb.entitiy.PersonData
import kotlinx.android.synthetic.main.item_person.view.*
class PersonDataAdapter(private val onDeleteClick: (PersonData)-> Unit):
RecyclerView.Adapter<PersonDataAdapter.DataViewHolder>() {
private var personDataList = mutableListOf<PersonData>()
fun setData(list: List<PersonData>){
personDataList.clear()
personDataList.addAll(list)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataViewHolder {
return DataViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_person,parent,false)
){
onDeleteClick.invoke(it)
}
}
override fun getItemCount(): Int {
return personDataList.size ?: 0
}
override fun onBindViewHolder(holder: DataViewHolder, position: Int) {
holder.setData(personDataList[position])
}
inner class DataViewHolder(itemView: View, val onDeleteClick: (PersonData) -> Unit): RecyclerView.ViewHolder(itemView) {
fun setData(personData: PersonData){
itemView.apply {
txtName.text = "Name : ${personData.nameFUll}"
txtAge.text = "Age : ${personData.ageTotal.toString()}"
imDelete.setOnClickListener {
onDeleteClick(personData)
}
}
}
}
}<file_sep>rootProject.name='Rx Kotlin with RoomDB'
include ':app'
<file_sep>package com.mobile.azrinurvani.rxkotlinwithroomdb.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.mobile.azrinurvani.rxkotlinwithroomdb.R
import com.mobile.azrinurvani.rxkotlinwithroomdb.adapter.PersonDataAdapter
import com.mobile.azrinurvani.rxkotlinwithroomdb.entitiy.PersonData
import com.mobile.azrinurvani.rxkotlinwithroomdb.entitiy.db.PersonalDetailsDataBase
import com.mobile.azrinurvani.rxkotlinwithroomdb.view_model.MainViewModel
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private var viewModel: MainViewModel? = null
private var personAdapter: PersonDataAdapter ?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
var databaseInstance = PersonalDetailsDataBase.getDatabaseInstance(this)
viewModel?.setInstanceOfDb(databaseInstance)
initViews()
setListeners()
observeViewModel()
}
private fun observeViewModel() {
viewModel?.personList?.observe(this, Observer {
if(!it.isNullOrEmpty()){
handleData(it)
}else{
handleZeroCase()
}
})
}
private fun handleData(data: List<PersonData>?) {
rvSavedRecords.visibility = View.VISIBLE
personAdapter?.setData(data!!)
}
private fun handleZeroCase() {
rvSavedRecords.visibility = View.GONE
Toast.makeText(this,"No Records Found ",Toast.LENGTH_LONG).show()
}
private fun setListeners() {
saveBtn.setOnClickListener {
saveData()
}
retrieveBtn.setOnClickListener {
viewModel?.getPersonData()
}
}
private fun saveData() {
var name = edtName.text.trim().toString()
var age = edtAge.text.trim().toString()
edtName.setText("")
edtAge.setText("")
if(name.isNullOrBlank()|| age.isNullOrBlank()){
Toast.makeText(this, "Please enter valid details", Toast.LENGTH_LONG).show()
}else{
val person = PersonData(nameFUll = name,ageTotal = age.toInt())
viewModel?.saveDataIntoDb(person)
}
}
private fun initViews() {
rvSavedRecords.layoutManager = LinearLayoutManager(this)
personAdapter = PersonDataAdapter(){
it.let {
viewModel?.deletePerson(it)
}
}
rvSavedRecords.adapter = personAdapter
}
}
| 9237156fa40844d790b67a18ebb7be6710725376 | [
"Kotlin",
"Gradle"
] | 7 | Kotlin | azrinurvani/Rx-Kotlin-wih-RoomDB | cb51f684afb666e14cb62a424e2fd557c4f315d6 | 080170d1232af842eee261b97c2729573ea4f1b7 |
refs/heads/master | <file_sep>package com.alvxyz.radiobuttondemo;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.RadioGroup;
import androidx.appcompat.app.AppCompatActivity;
import com.alvxyz.radiobuttondemo.ui.login.LoginActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
RadioGroup rgLanguages;
Button btnReset, btnSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rgLanguages = findViewById(R.id.rgLanguages);
btnReset = findViewById(R.id.btnReset);
btnSubmit = findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
btnReset.setOnClickListener(this);
}
public void onButtonSubmitClicked() {
int checkedId = rgLanguages.getCheckedRadioButtonId();
if (checkedId == -1) {
// No Radio buttons are checked
Message.message(getApplicationContext(), "Please seleceted Language");
} else {
// One of radio buttons is checked
findRadioButton(checkedId);
}
}
// This Method use for find radio button adn make Toast From Class Message
private void findRadioButton(int checkedId) {
switch (checkedId) {
case R.id.radioButton:
Message.message(getApplicationContext(), "I Like C.");
break;
case R.id.radioButton2:
Message.message(getApplicationContext(), "I Like C++");
break;
case R.id.radioButton3:
Message.message(getApplicationContext(), "I Like Java");
break;
case R.id.radioButton4:
Message.message(getApplicationContext(), "I Like Pyhton");
break;
case R.id.radioButton5:
Message.message(getApplicationContext(), "I Like PHP");
break;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmit:
onButtonSubmitClicked();
break;
case R.id.btnReset:
rgLanguages.clearCheck();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
break;
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
<file_sep>rootProject.name='Tes-Kedua'
include ':app'
| 6565733f6c1a653c3230d8e9ee85e28e4de998e8 | [
"Java",
"Gradle"
] | 2 | Java | alvxyz/PemrogramanMobile-4 | e51ceb393c43c0fa6741dea47ddc38eef017807b | 5d1de1cdf4208c7516f2f8d7e26db0030f5ef371 |
refs/heads/master | <repo_name>Frostlys/leetcode-cheat<file_sep>/src/codeTemplates/trie.js
import treeLogo from "../imgs/tree.svg";
const cppCode = `
struct TrieNode {
TrieNode *children[26];
bool isEnd;
TrieNode(bool end=false) {
isEnd = end;
memset(children, 0, sizeof(children));
}
};
class Trie {
private:
TrieNode *root;
TrieNode* findString(string word) {
TrieNode *p = root;
for (size_t i=0; i<word.size(); i++) {
int index = word[i] - 'a';
if(p->children[index] == nullptr)
return nullptr;
p = p->children[index];
}
return p;
}
void clear(TrieNode *root) {
for (size_t i = 0; i < 26; i ++)
if (root->children[i])
clear(root->children[i]);
delete root;
}
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
~Trie() {
clear(root);
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *p = root;
for(size_t i=0; i<word.size(); i++) {
int index = word[i] - 'a';
if (!p->children[index])
p->children[index] = new TrieNode();
p = p->children[index];
}
p->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *p = findString(word);
return p != nullptr && p->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *p = findString(prefix);
return p != nullptr;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
`;
const goCode = `
type Node struct {
isWord bool
next map[byte]*Node
}
func NewNode(isWord bool) *Node {
return &Node{isWord: isWord, next: make(map[byte]*Node)}
}
type Trie struct {
root *Node
}
//func NewTrie() *Trie {
// return &Trie{root: NewNode(false)}
//}
/** Initialize your data structure here. */
func Constructor() Trie {
return Trie{root: NewNode(false)}
}
/** Inserts a word into the trie. */
func (t *Trie) Insert(word string) {
cur := t.root
for i := 0; i < len(word); i++ {
c := word[i]
_, ok := cur.next[c]
if !ok { //
cur.next[c] = NewNode(false)
}
cur = cur.next[c]
}
if !cur.isWord { // 标记为单词
cur.isWord = true
}
}
/** Returns if the word is in the trie. */
func (t *Trie) Search(word string) bool {
cur := t.root
for i := 0; i < len(word); i++ {
c := word[i]
v, ok := cur.next[c]
if !ok {
return false
}
cur = v
}
return cur.isWord
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func (t *Trie) StartsWith(prefix string) bool {
cur := t.root
for i := 0; i < len(prefix); i++ {
c := prefix[i]
v,ok := cur.next[c]
if !ok {
return false
}
cur = v
}
return true
}
`;
const javaCode = `
class Trie {
class TireNode {
boolean isEnd = false;
TireNode[] next = new TireNode[26];
TireNode() {}
}
private TireNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TireNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TireNode node = root;
for (char ch : word.toCharArray()) {
if (node.next[ch-'a'] == null) {
node.next[ch-'a'] = new TireNode();
}
node = node.next[ch-'a'];
}
node.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TireNode node = root;
for (char ch : word.toCharArray()) {
if (node.next[ch-'a'] == null) return false;
node = node.next[ch-'a'];
}
return node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TireNode node = root;
for (char ch : prefix.toCharArray()) {
if (node.next[ch-'a'] == null) return false;
node = node.next[ch-'a'];
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/
`;
export default {
title: "前缀树",
logo: treeLogo,
list: [
{
text: "标准前缀树",
problems: [
{
title: "208.实现 Trie (前缀树)",
id: "implement-trie-prefix-tree",
},
{
title: "211.添加与搜索单词 - 数据结构设计",
id: "add-and-search-word-data-structure-design",
},
{
id: "word-search-ii",
title: "212.单词搜索 II",
},
{
id: "concatenated-words",
title: "472.连接词",
},
{
title: "648. 单词替换",
id: "replace-words",
},
{
id: "short-encoding-of-words",
title: "820.单词的压缩编码",
},
{
title: "1032.字符流",
id: "stream-of-characters",
},
],
codes: [
{
language: "py",
text: `
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.Trie = {}
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
curr = self.Trie
for w in word:
if w not in curr:
curr[w] = {}
curr = curr[w]
curr['#'] = 1
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
curr = self.Trie
for i, w in enumerate(word):
if w == '.':
wizards = []
for k in curr.keys():
if k == '#':
continue
wizards.append(self.search(word[:i] + k + word[i + 1:]))
return any(wizards)
if w not in curr:
return False
curr = curr[w]
return "#" in curr
`,
},
{
language: "js",
text: `
function TrieNode(val) {
this.val = val;
this.children = [];
this.isWord = false;
}
function computeIndex(c) {
return c.charCodeAt(0) - "a".charCodeAt(0);
}
/**
* Initialize your data structure here.
*/
var Trie = function() {
this.root = new TrieNode(null);
};
/**
* Inserts a word into the trie.
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function(word) {
let ws = this.root;
for (let i = 0; i < word.length; i++) {
const c = word[i];
const current = computeIndex(c);
if (!ws.children[current]) {
ws.children[current] = new TrieNode(c);
}
ws = ws.children[current];
}
ws.isWord = true;
};
/**
* Returns if the word is in the trie.
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function(word) {
let ws = this.root;
for (let i = 0; i < word.length; i++) {
const c = word[i];
const current = computeIndex(c);
if (!ws.children[current]) return false;
ws = ws.children[current];
}
return ws.isWord;
};
/**
* Returns if there is any word in the trie that starts with the given prefix.
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function(prefix) {
let ws = this.root;
for (let i = 0; i < prefix.length; i++) {
const c = prefix[i];
const current = computeIndex(c);
if (!ws.children[current]) return false;
ws = ws.children[current];
}
return true;
};
/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/
`,
},
{
language: "cpp",
text: cppCode,
},
{
language: "go",
text: goCode,
},
{
language: "java",
text: javaCode,
},
],
},
],
link:
"https://github.com/azl397985856/leetcode/blob/master/thinkings/trie.md",
};
| 470c377623d9d6d97a2498bf47e17ad67fe1b96e | [
"JavaScript"
] | 1 | JavaScript | Frostlys/leetcode-cheat | 3e594f51621d80a4d28e41b7bf8ab460350fddb9 | 243da134b490f083426a840868d46b16294cce2f |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import './Tabs.css';
class Tabs extends Component {
render () {
return (
<div className="tab-container">
<ul className="tabs">
<li className="active">Upcoming Campains</li>
<li>Live Campains</li>
<li>Past Campains</li>
</ul>
</div>
)
}
}
export default Tabs;<file_sep>import React, { Component } from 'react';
import Tabs from '../../components/Tabs';
import CampainList from '../../components/CampainList';
class ManageCampain extends Component {
render () {
return (
<div>
<h1>Manage Campain</h1>
<Tabs />
<div className="mb3" ></div>
<CampainList />
</div>
)
}
}
export default ManageCampain; | e7c834ae06a2a7aed7c036d7c0bc91697e12262c | [
"JavaScript"
] | 2 | JavaScript | divyamoyal/bluestacks-manage-campaigns | 81e5b87780443acd068613f310351b52a01c1d39 | 309d62cbbbd1514f737a145f20acdef37ad29eaa |
refs/heads/master | <repo_name>Makcy/xx-dict<file_sep>/README.md
查查字典
A Quick Shell Dict For Geek
yarn global add xx-dict
Usage: xx [word]
<file_sep>/bin/cli
#!/usr/bin/env node
'use strict';
const program = require('commander');
const pkg = require('../package.json');
const lookup = require('../index');
program
.description(pkg.description)
.version(pkg.version)
.usage('<word>')
.parse(process.argv)
lookup(program.args[0]);
if (process.argv.length === 2) {
program.help();
}<file_sep>/src/lookup.js
const request = require('request');
const cheerio = require('cheerio');
const urlencode = require('urlencode');
function lookup(word) {
// TODO: Ugly Code!!!
if (!word) return;
let isCn = /^[\u4E00-\u9FA5]+$/.test(word);
const URL = isCn ? `http://dict.youdao.com/w/eng/${urlencode(word)}`:`http://dict.youdao.com/w/${word}`
request(URL, (err, response, body) => {
const $ = cheerio.load(body);
if(isCn){
$('div.trans-container > ul').find('p.wordGroup').each(function(i,elm){
var line = $(this).text().replace(/\s+/g," ");
console.log(line);
});
}else{
console.log($('div#phrsListTab > div.trans-container > ul').text());
}
});
};
module.exports = lookup; | 134db75c97aceaea53afd92f9d7d9c65a1ac2028 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | Makcy/xx-dict | d0747cf9179059bbcb833c653a7205166295ff4a | e3557d9ba460a9b9c7b1c1e883554e3a3418a681 |
refs/heads/master | <file_sep>package com.linearlayout.chototapp.Model;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Filter {
@SerializedName("propertyid")
@Expose
public Integer propertyid;
@SerializedName("name")
@Expose
public String name;
@SerializedName("type")
@Expose
public String type;
@SerializedName("option")
@Expose
public List<Option> option = null;
}<file_sep>package com.linearlayout.chototapp.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class ListChildCate implements Serializable {
@SerializedName("CateID")
@Expose
public String cateID;
@SerializedName("CateName")
@Expose
public String cateName;
@SerializedName("urlImage")
@Expose
public String urlImage;
@SerializedName("parent_id")
@Expose
public String parentId;
@SerializedName("tid")
@Expose
public Object tid;
public String getCateID() {
return cateID;
}
public void setCateID(String cateID) {
this.cateID = cateID;
}
public String getCateName() {
return cateName;
}
public void setCateName(String cateName) {
this.cateName = cateName;
}
public String getUrlImage() {
return urlImage;
}
public void setUrlImage(String urlImage) {
this.urlImage = urlImage;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public Object getTid() {
return tid;
}
public void setTid(Object tid) {
this.tid = tid;
}
}<file_sep># MarketVietNam247
This app is designed and coded by Sơn , Hạnh , Tâm
<file_sep>package com.linearlayout.chototapp.Adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.linearlayout.chototapp.Controller.DetailActivity;
import com.linearlayout.chototapp.Model.Category;
import com.linearlayout.chototapp.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeViewHolder> {
public List<Category> datahome;
public Context context;
public void setDatahome(List<Category> datahome) {
this.datahome = datahome;
}
public void setContext(Context context) {
this.context = context;
}
@NonNull
@Override
public HomeViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.home_item_layout, viewGroup, false);
return new HomeViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull HomeViewHolder viewHolder, final int position) {
final Category category = datahome.get(position);
viewHolder.tvHomeTitle.setText(category.getCateName());
Picasso.get().load(category.getUrlImage()).into(viewHolder.imgHome);
//phần chuyển màn hình
viewHolder.imgHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("Category",datahome.get(position));
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return datahome.size();
}
public class HomeViewHolder extends RecyclerView.ViewHolder {
ImageView imgHome;
TextView tvHomeTitle;
public HomeViewHolder(@NonNull View itemView) {
super(itemView);
imgHome = itemView.findViewById(R.id.img_category);
tvHomeTitle = itemView.findViewById(R.id.tv_category);
}
}
}
<file_sep>package com.linearlayout.chototapp.Adapter;
public class PostAdapter {
}
<file_sep>package com.linearlayout.chototapp.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Option {
@SerializedName("id")
@Expose
public Integer id;
@SerializedName("value")
@Expose
public String value;
} | ccd03f2e5e198d0a2557c4811fa7548cb589c9dd | [
"Markdown",
"Java"
] | 6 | Java | tranminhson041098/MarketVietNam247 | f289caa92e0d2b12e012589b713b0e50f4c7f387 | fd26e631a9f3054adf59c730d5f63ec0625840ba |
refs/heads/main | <repo_name>hong-dev/pandas_practice<file_sep>/stack.py
# Split strings in a cell into rows
import pandas as pd
df = pd.read_csv(
"data.csv",
encoding="euc-kr",
usecols=[0, 1, 2, 3, 4],
names=["A", "B", "C", "D", "E"],
skiprows=1,
).dropna()
new_df = pd.DataFrame(
df.E.str.split(",").tolist(), index=[df.A, df.B, df.C, df.D]
).stack()
new_df = new_df.reset_index(["A", "B", "C", "D"])
new_df.columns = ["광고그룹명", "판매자 ID", "사이트", "상품 번호", "키워드"]
# new_df.to_excel("final.xlsx", index=False)
new_df.to_csv("final.csv", index=False, encoding="euc-kr")
<file_sep>/README.md
# Pandas Exercises
## 1. Stack
[Before]
|Index|Column|
|-|-|
|A|B, C, D|
[After]
|Index|Column|
|-|-|
|A|B|
|A|C|
|A|D|
<file_sep>/rename_columns.py
import pandas as pd
filepath = "data/exoTrain.csv"
df = pd.read_csv(filepath)
mapping = {}
for column in df.columns:
if "." in column:
mapping[column] = column.replace(".", "")
else:
mapping[column] = column
df = df.rename(columns=mapping)
df.to_csv(filepath, index=False)
<file_sep>/create_schema.py
import pandas as pd
filepath = "data/exoTrain.csv"
df = pd.read_csv(filepath)
schema = []
for column in df.columns:
info = {"mlcoreType": "number", "type": "float"}
info["name"] = column
schema.append(info)
print(schema)
| e0708a75e623bb43b00a7912995682aa94c0ac20 | [
"Markdown",
"Python"
] | 4 | Python | hong-dev/pandas_practice | 342fb541494bd06f83b7dfc1dfdae1d8650e12ed | 1fde1c62ff7116ca7acb02a5cbbe6c30a41b4baa |
refs/heads/master | <file_sep>/*
* open-bo-api - C++ API for working with binary options brokers
*
* Copyright (c) 2020 <NAME>. Email: <EMAIL>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef OPEN_BO_API_SETTINGS_HPP_INCLUDED
#define OPEN_BO_API_SETTINGS_HPP_INCLUDED
#include <iostream>
#include <string>
#include <cstdlib>
#include <nlohmann/json.hpp>
namespace open_bo_api {
using json = nlohmann::json;
class Settings {
private:
bool is_error = false;
public:
std::string environmental_variable;
std::string json_file_name; /**< Имя JSON файла */
std::string trading_robot_work_log_file = "logger/trading_robot_work_file.log";
std::string trading_robot_work_path = "logger/";
std::string news_sert_file = "curl-ca-bundle.crt";
std::string intrade_bar_sert_file = "curl-ca-bundle.crt";
std::string intrade_bar_cookie_file = "cookie/intrade-bar.cookie";
std::string intrade_bar_bets_log_file = "logger/intrade-bar-bets.log";
std::string intrade_bar_work_log_file = "logger/intrade-bar-https-work.log";
std::string intrade_bar_websocket_log_file = "logger/intrade-bar-websocket.log";
std::string intrade_bar_email;
std::string intrade_bar_password;
uint32_t intrade_bar_number_bars = 100; /**< количество баров м1 для инициализации исторических данных */
bool is_intrade_bar_demo_account = true;
bool is_intrade_bar_rub_currency = true;
bool is_intrade_bar = false;
uint32_t olymp_trade_port = 8080; /**< Порт сервера для подключения к расширению брокера Olymptrade */
bool is_olymp_trade_demo_account = true;
bool is_olymp_trade = false;
uint32_t mt_bridge_port = 5555; /**< Порт "Моста" для подключения к MetaTrader4 */
std::string telegram_token;
std::string telegram_proxy;
std::string telegram_proxy_pwd;
std::string telegram_sert_file = "curl-ca-bundle.crt";
std::string telegram_chats_id_file = "telegram/save_chats_id.json";
std::string history_tester_storage_path;
double history_tester_time_speed = 1.0;
uint32_t history_tester_number_bars = 100;
xtime::timestamp_t history_tester_start_timestamp = 0;
xtime::timestamp_t history_tester_stop_timestamp = 0;
Settings() {};
void init(json &j) {
try {
if(j["environmental_variable"] != nullptr) {
environmental_variable = j["environmental_variable"];
}
//
if(j["telegram"]["token"] != nullptr) {
telegram_token = j["telegram"]["token"];
}
if(j["telegram"]["proxy"] != nullptr) {
telegram_proxy = j["telegram"]["proxy"];
}
if(j["telegram"]["proxy_pwd"] != nullptr) {
telegram_proxy_pwd = j["telegram"]["proxy_pwd"];
}
if(j["telegram"]["sert_file"] != nullptr) {
telegram_sert_file = j["telegram"]["sert_file"];
}
if(j["telegram"]["chats_id_file"] != nullptr) {
telegram_chats_id_file = j["telegram"]["chats_id_file"];
}
//
if(j["mt_bridge"]["port"] != nullptr) {
mt_bridge_port = j["mt_bridge"]["port"];
}
//
if(j["news"]["sert_file"] != nullptr) {
news_sert_file = j["news"]["sert_file"];
}
//
if(j["intrade_bar"]["email"] != nullptr) {
intrade_bar_email = j["intrade_bar"]["email"];
}
if(j["intrade_bar"]["password"] != nullptr) {
intrade_bar_password = j["<PASSWORD>"]["password"];
}
if(j["intrade_bar"]["sert_file"] != nullptr) {
intrade_bar_sert_file = j["intrade_bar"]["sert_file"];
}
if(j["intrade_bar"]["cookie_file"] != nullptr) {
intrade_bar_cookie_file = j["intrade_bar"]["cookie_file"];
}
if(j["intrade_bar"]["bets_log_file"] != nullptr) {
intrade_bar_bets_log_file = j["intrade_bar"]["bets_log_file"];
}
if(j["intrade_bar"]["work_log_file"] != nullptr) {
intrade_bar_work_log_file = j["intrade_bar"]["work_log_file"];
}
if(j["intrade_bar"]["websocket_log_file"] != nullptr) {
intrade_bar_websocket_log_file = j["intrade_bar"]["websocket_log_file"];
}
if(j["intrade_bar"]["demo_account"] != nullptr) {
is_intrade_bar_demo_account = j["intrade_bar"]["demo_account"];
}
if(j["intrade_bar"]["rub_currency"] != nullptr) {
is_intrade_bar_rub_currency = j["intrade_bar"]["rub_currency"];
}
if(j["intrade_bar"]["number_bars"] != nullptr) {
intrade_bar_number_bars = j["intrade_bar"]["number_bars"];
}
if(j["intrade_bar"]["use"] != nullptr) {
is_intrade_bar = j["intrade_bar"]["use"];
}
//
if(j["olymp_trade"]["port"] != nullptr) {
olymp_trade_port = j["olymp_trade"]["port"];
}
if(j["olymp_trade"]["demo_account"] != nullptr) {
is_olymp_trade_demo_account = j["olymp_trade"]["demo_account"];
}
if(j["olymp_trade"]["use"] != nullptr) {
is_olymp_trade = j["olymp_trade"]["use"];
}
//
if(j["trading_robot"]["work_log_file"] != nullptr) {
trading_robot_work_log_file = j["trading_robot"]["work_log_file"];
}
if(j["trading_robot"]["work_path"] != nullptr) {
trading_robot_work_path = j["trading_robot"]["work_path"];
}
//
if(j["history_tester"]["storage_path"] != nullptr) {
history_tester_storage_path = j["history_tester"]["storage_path"];
}
if(j["history_tester"]["time_speed"] != nullptr) {
history_tester_time_speed = j["history_tester"]["time_speed"];
}
if(j["history_tester"]["number_bars"] != nullptr) {
history_tester_number_bars = j["history_tester"]["number_bars"];
}
if(j["history_tester"]["start_timestamp"] != nullptr) {
std::string date = j["history_tester"]["start_timestamp"];
xtime::convert_str_to_timestamp(date, history_tester_start_timestamp);
}
if(j["history_tester"]["stop_timestamp"] != nullptr) {
std::string date = j["history_tester"]["stop_timestamp"];
xtime::convert_str_to_timestamp(date, history_tester_stop_timestamp);
}
}
catch (json::parse_error &e) {
std::cerr << "open_bo_api::Settings, json parser error: " << std::string(e.what()) << std::endl;
is_error = true;
return;
}
catch (std::exception e) {
std::cerr << "open_bo_api::Settings, json parser error: " << std::string(e.what()) << std::endl;
is_error = true;
return;
}
catch(...) {
std::cerr << "open_bo_api::Settings, json parser error" << std::endl;
is_error = true;
return;
}
if(environmental_variable.size() != 0) {
const char* env_ptr = std::getenv(environmental_variable.c_str());
if(env_ptr == NULL) {
std::cerr << "open_bo_api::Settings, error, no environment variable!" << std::endl;
is_error = true;
return;
}
news_sert_file = std::string(env_ptr) + "\\" + news_sert_file;
intrade_bar_sert_file = std::string(env_ptr) + "\\" + intrade_bar_sert_file;
intrade_bar_cookie_file = std::string(env_ptr) + "\\" + intrade_bar_cookie_file;
intrade_bar_bets_log_file = std::string(env_ptr) + "\\" + intrade_bar_bets_log_file;
intrade_bar_work_log_file = std::string(env_ptr) + "\\" + intrade_bar_work_log_file;
intrade_bar_websocket_log_file = std::string(env_ptr) + "\\" + intrade_bar_websocket_log_file;
trading_robot_work_log_file = std::string(env_ptr) + "\\" + trading_robot_work_log_file;
telegram_sert_file = std::string(env_ptr) + "\\" + telegram_sert_file;
telegram_chats_id_file = std::string(env_ptr) + "\\" + telegram_chats_id_file;
trading_robot_work_path = std::string(env_ptr) + "\\" + trading_robot_work_path;
}
}
Settings(json &j) {
init(j);
}
/** \brief Проверить наличие ошибки
* \return Вернет true, если есть ошибка
*/
inline bool check_error() {
return is_error;
}
std::string get_date_name(const xtime::timestamp_t timestamp) {
xtime::DateTime date_time(timestamp);
std::string temp;
temp += std::to_string(date_time.year);
temp += "_";
temp += std::to_string(date_time.month);
temp += "_";
temp += std::to_string(date_time.day);
return temp;
}
std::string get_date_name() {
return get_date_name(xtime::get_timestamp());
}
std::string get_work_log_file_name() {
std::string temp;
temp += trading_robot_work_path;
temp += "//";
temp += get_date_name();
temp += ".log";
return temp;
}
};
}
#endif // OPEN_BO_API_SETTINGS_HPP_INCLUDED
| 94237c7f79b787a55baeadfb32b85bfb256cb76f | [
"C++"
] | 1 | C++ | mpvyard/open-bo-api | 9ad563d7a78ea5671c160c5176d3d1a064eb17cf | 7cba6c929e3fc18d6bd7c9e746193fb2ea7212d0 |
refs/heads/master | <file_sep>require('dotenv').config();
const jwt = require('jsonwebtoken')
const generateToken = ()=>{
const token = jwt.sign({id: 23, email:"<EMAIL>"},process.env.SECRET_KEY, {expiresIn: '1800s'} );
}
const verifyToken = (token)=>{
const decodedData = jwt.decode(token, process.env.SECRET_KEY);
console.log({decodedData});
}
verifyToken("<KEY>")
<file_sep>const bcrypt = require('bcrypt')
const hashPassword = async (password)=>{
const salt = await bcrypt.genSalt(5)
const salt2 = await bcrypt.genSalt(31)
const hash = await bcrypt.hash(password, salt)
const hash2 = await bcrypt.hash(password, salt2)
console.log({salt});
console.log({salt2});
console.log({hash});
console.log({hash2});
return hash;
}
const comparePass = async (plaintext, hash)=>{
const isValid = await bcrypt.compare(plaintext, hash)
console.log(isValid);
}
const hash = "$2b$10$sRjhTFwtg2NbHfEm/LfULuNDbSjmjKtHk64uzeu0iOn7uTeZVzWuu";
// hashPassword("<PASSWORD>")
hashPassword("<PASSWORD>")
| c5f7b07c11f4dc045fedcc18f5f7deb7d3dc60f5 | [
"JavaScript"
] | 2 | JavaScript | marville001/training-bcrypt-jwt | 8c9b46c6f1c3164c0857b0931cfee2701208eadd | e6e8dd63835c56d036955098ad2cbee0e31dc654 |
refs/heads/master | <file_sep>README
3,5,4 CHALLENGE
This is my project for the challenge, I tried to make it simple but efficient, the solution is showed with every step in the project, also i add a simple test with jest and enzyme to show how unit testing works
This project was created with the following technologies:
-react
-jest
-enzyme
-Material UI
Download the project:
- Create a folder
- On the command line or terminal write : 'git init' inside the folder already created
- git remote add origin https://github.com/Kennethbmt95/BucketChallenge.git
- git pull origin master
Initial configuration:
-npm install : to install all the dependencies
-npm start: to run the project
Run Test:
-npm test: to run all the test in the project
<file_sep>import React from 'react'
import Adapter from 'enzyme-adapter-react-16';
import { shallow, configure } from 'enzyme';
configure({adapter: new Adapter()});
import MainView from '../MainView'
let wrapper
describe('Main Component', () => {
it('starts with a count of 0', () => {
const wrapper = shallow(<MainView />);
const text = wrapper.find('h2').text();
expect(text).toEqual('Total Steps: 0');
});
});
<file_sep>import React, { useState, useEffect } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Liter from './Liter'
const useStyles = makeStyles(theme => ({
container: {
width: '100px',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'column'
},
}))
function Bucket(props) {
const classes = useStyles()
const renderSteps = (steps) => {
console.log(steps);
const stepsToRender = steps.map((item, index) => {
return (
<Liter
value={item.value}
/>
)
})
return stepsToRender
}
return (
<div className={classes.container}>
<span>{props.name}</span>
{renderSteps(props.steps)}
</div>
)
}
export default Bucket
<file_sep>import React, { useState, useEffect } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Button from '@material-ui/core/Button'
import TextField from '@material-ui/core/TextField'
const useStyles = makeStyles(theme => ({
form: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'column',
},
inputs: {
width: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: '10px',
},
button: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
borderRadius: 3,
border: 0,
color: 'white',
height: 48,
padding: '0 30px',
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
marginBottom: '20px',
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
},
label: {
textTransform: 'capitalize',
},
}))
function Form(props) {
const classes = useStyles()
return (
<form className={classes.form} onSubmit={props.handleSubmit}>
<div className={classes.inputs}>
<TextField
id="outlined-name"
label="Bucket A"
className={classes.textField}
onChange={props.changeBucketA}
margin="normal"
variant="outlined"
/>
<TextField
id="outlined-name"
label="Bucket B"
className={classes.textField}
onChange={props.changeBucketB}
margin="normal"
variant="outlined"
/>
</div>
<Button
classes={{
root: classes.button,
label: classes.label,
}}
type="submit"
>
Start
</Button>
</form>
)
}
export default Form
<file_sep>import React, { useState, useEffect } from 'react'
import { createMuiTheme, makeStyles, responsiveFontSizes } from '@material-ui/core/styles'
import { ThemeProvider } from '@material-ui/styles'
import Typography from '@material-ui/core/Typography'
import Bucket from './components/Bucket'
import Form from './components/Form'
let theme = createMuiTheme()
theme = responsiveFontSizes(theme)
let totalStepsA = [{value: 0}]
let totalStepsB = [{value: 0}]
const useStyles = makeStyles({
buckets: {
width: '300px',
padding: '30px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
},
container: {
width: '100%',
padding: '10px',
boxSizing: 'border-box',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'column',
},
h3: {
fontFamily: 'Roboto'
},
title: {
color: 'blue',
}
})
function MainView() {
const classes = useStyles()
const [calculate, setCalculate] = useState(false)
const [bucketA, setBucketA] = useState(0)
const [bucketB, setBucketB] = useState(0)
const [currentValueA, setCurrentValueA] = useState(0)
const [currentValueB, setCurrentValueB] = useState(0)
const [steps, setSteps] = useState(0)
const sleep = (milliseconds) => new Promise(resolve => setTimeout(resolve, milliseconds))
useEffect(() => {
if (calculate) {
if (currentValueA !== 0 || currentValueB !== 0) {
totalStepsA.push({ value: currentValueA })
totalStepsB.push({ value: currentValueB })
}
if ((currentValueA === 4 || currentValueB === 4) && (currentValueA === 0 || currentValueB === 0)) {
setCalculate(false)
setCurrentValueA(0)
setCurrentValueB(0)
} else {
if (currentValueB === bucketB && bucketB !== 0) {
empty()
setSteps(steps + 1)
}
if (currentValueA > 0 && currentValueB < bucketB) {
transfer()
setSteps(steps + 1)
}
if (currentValueA === 0 && bucketA !== 0) {
fill()
setSteps(steps + 1)
}
}
}
})
const empty = () => {
setCurrentValueB(0)
}
const fill = () => {
if (currentValueA === 0) {
setCurrentValueA(bucketA)
} else {
setCurrentValueA(bucketA - currentValueA)
}
}
const transfer = () => {
if (currentValueA > currentValueB) {
if (currentValueA >= (bucketB - currentValueB)) {
let valueToTransfer = bucketB - currentValueB
setCurrentValueB(valueToTransfer + currentValueB)
setCurrentValueA(currentValueA - valueToTransfer)
} else {
setCurrentValueB(currentValueA + currentValueB)
setCurrentValueA(currentValueA - currentValueA)
}
} else if (currentValueA === currentValueB) {
if ((currentValueA + currentValueB) > bucketB) {
setCurrentValueB(bucketB)
setCurrentValueA((currentValueA + currentValueB) - bucketB)
} else {
setCurrentValueB(currentValueA + currentValueB)
setCurrentValueA(currentValueA - currentValueA)
}
} else {
let valueToTransfer = bucketB - currentValueB
setCurrentValueB(valueToTransfer)
setCurrentValueA(currentValueA - valueToTransfer)
}
}
const changeBucketA = (event) => setBucketA(Number(event.target.value))
const changeBucketB = (event) => setBucketB(Number(event.target.value))
const handleSubmit = (event) => {
event.preventDefault()
totalStepsA = [{value: 0}]
totalStepsB = [{value: 0}]
setCalculate(true)
setSteps(0)
}
return (
<div className={classes.container}>
<ThemeProvider theme={theme}>
<Typography variant="h3">3,4,5 CHALLENGE</Typography>
</ThemeProvider>
<Form
handleSubmit={handleSubmit}
changeBucketA={changeBucketA}
changeBucketB={changeBucketB}
/>
<div className={classes.buckets}>
<Bucket
steps={totalStepsA}
name='Bucket A'
/>
<Bucket
steps={totalStepsB}
name='Bucket B'
/>
</div>
<h2 className={classes.h3}>{`Total Steps: ${steps}`}</h2>
</div>
)
}
export default MainView
| 8bed007ff44597d38db74e1e19a631c15802e604 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | Kennethbmt95/BucketChallenge | baa63c052a92636e2c0643938639a5d28cdff3a7 | 342cbfd32de796bfb6bd07b8a2432cb9f0b3ceca |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.